@spooky-sync/core 1.0.0-beta.8 → 1.0.0-beta.9
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/AGENTS.md +1 -1
- package/dist/index.d.ts +99 -2
- package/dist/index.js +942 -27
- package/dist/types.d.ts +68 -2
- package/package.json +3 -3
- package/skills/sp00ky-core/SKILL.md +2 -0
- package/src/client/sp00ky-client.test.ts +64 -1
- package/src/client/sp00ky-client.ts +53 -10
- package/src/index.ts +7 -0
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +358 -14
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +2 -2
- package/src/types.ts +5 -0
package/dist/index.js
CHANGED
|
@@ -1605,6 +1605,179 @@ function compileScope(schema, plan) {
|
|
|
1605
1605
|
where
|
|
1606
1606
|
};
|
|
1607
1607
|
}
|
|
1608
|
+
/** Past this many filters on one table a device just asks for all of it: the message stays small. */
|
|
1609
|
+
const MAX_INTEREST_FILTERS = 24;
|
|
1610
|
+
const knownOp = (op) => typeof op === "string" && Object.prototype.hasOwnProperty.call(OPS, op);
|
|
1611
|
+
/**
|
|
1612
|
+
* A `where` as a test the row alone decides, parameters filled in. `null`
|
|
1613
|
+
* when it cannot be one (an operator this file does not evaluate, a path
|
|
1614
|
+
* through a record link, a parameter without a value): then the query counts
|
|
1615
|
+
* as showing the whole table, which only costs a few messages too many.
|
|
1616
|
+
*/
|
|
1617
|
+
function rowFilter(columns, where, params) {
|
|
1618
|
+
const out = [];
|
|
1619
|
+
for (const node of where) {
|
|
1620
|
+
const resolved = [];
|
|
1621
|
+
for (const c of "or" in node ? node.or : [node]) {
|
|
1622
|
+
if (!knownOp(c.op)) return null;
|
|
1623
|
+
if (c.field.includes(".") && columns?.[c.field.split(".")[0]]?.recordId) return null;
|
|
1624
|
+
let value = c.value;
|
|
1625
|
+
if (value === void 0 && c.paramRef) {
|
|
1626
|
+
if (!(c.paramRef in params)) return null;
|
|
1627
|
+
value = params[c.paramRef];
|
|
1628
|
+
}
|
|
1629
|
+
resolved.push(c.swap ? {
|
|
1630
|
+
field: c.field,
|
|
1631
|
+
op: c.op,
|
|
1632
|
+
value,
|
|
1633
|
+
swap: true
|
|
1634
|
+
} : {
|
|
1635
|
+
field: c.field,
|
|
1636
|
+
op: c.op,
|
|
1637
|
+
value
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
out.push("or" in node ? { or: resolved } : resolved[0]);
|
|
1641
|
+
}
|
|
1642
|
+
return out;
|
|
1643
|
+
}
|
|
1644
|
+
/**
|
|
1645
|
+
* What a registered query can show: the rows of its own table that pass its
|
|
1646
|
+
* filter, and every row of the tables it reads through `.related()` (which
|
|
1647
|
+
* children it shows depends on the parents, not on the child row alone).
|
|
1648
|
+
* Order, limit and offset are ignored: a row inside the filter and outside
|
|
1649
|
+
* the window is sent and then not shown.
|
|
1650
|
+
*/
|
|
1651
|
+
function queryInterest(columnsOf, plan, params = {}) {
|
|
1652
|
+
const out = [{
|
|
1653
|
+
table: plan.table,
|
|
1654
|
+
where: plan.ids ? null : rowFilter(columnsOf(plan.table), plan.where ?? [], params)
|
|
1655
|
+
}];
|
|
1656
|
+
const walk = (relations) => {
|
|
1657
|
+
for (const r of relations ?? []) {
|
|
1658
|
+
out.push({
|
|
1659
|
+
table: r.table,
|
|
1660
|
+
where: null
|
|
1661
|
+
});
|
|
1662
|
+
walk(r.relations);
|
|
1663
|
+
}
|
|
1664
|
+
};
|
|
1665
|
+
walk(plan.relations);
|
|
1666
|
+
return out;
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* The interests of every open subscription as one, for the tables `shared`
|
|
1670
|
+
* names. `'all'` once one of them is unknown. Each filter once and in a fixed
|
|
1671
|
+
* order, so the same set of queries always reads the same.
|
|
1672
|
+
*/
|
|
1673
|
+
function mergeInterest(list, shared) {
|
|
1674
|
+
const tables = /* @__PURE__ */ new Map();
|
|
1675
|
+
for (const queries of list) {
|
|
1676
|
+
if (queries === null) return "all";
|
|
1677
|
+
for (const q of queries) {
|
|
1678
|
+
if (!shared(q.table)) continue;
|
|
1679
|
+
const cur = tables.get(q.table);
|
|
1680
|
+
if (cur === true) continue;
|
|
1681
|
+
if (q.where === null || q.where.length === 0) {
|
|
1682
|
+
tables.set(q.table, true);
|
|
1683
|
+
continue;
|
|
1684
|
+
}
|
|
1685
|
+
const filters = cur ?? /* @__PURE__ */ new Map();
|
|
1686
|
+
filters.set(JSON.stringify(encodeWhere(q.where)), q.where);
|
|
1687
|
+
tables.set(q.table, filters.size > MAX_INTEREST_FILTERS ? true : filters);
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
const out = {};
|
|
1691
|
+
for (const [table, filters] of [...tables].sort(([a], [b]) => a < b ? -1 : 1)) out[table] = filters === true ? true : [...filters].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, where]) => where);
|
|
1692
|
+
return out;
|
|
1693
|
+
}
|
|
1694
|
+
const encodeComparison = (c) => c.swap ? {
|
|
1695
|
+
field: c.field,
|
|
1696
|
+
op: c.op,
|
|
1697
|
+
value: encodeValue(c.value),
|
|
1698
|
+
swap: true
|
|
1699
|
+
} : {
|
|
1700
|
+
field: c.field,
|
|
1701
|
+
op: c.op,
|
|
1702
|
+
value: encodeValue(c.value)
|
|
1703
|
+
};
|
|
1704
|
+
function encodeWhere(where) {
|
|
1705
|
+
return where.map((n) => "or" in n ? { or: n.or.map(encodeComparison) } : encodeComparison(n));
|
|
1706
|
+
}
|
|
1707
|
+
function encodeInterest(interest) {
|
|
1708
|
+
if (interest === "all") return {
|
|
1709
|
+
t: "interest",
|
|
1710
|
+
all: true
|
|
1711
|
+
};
|
|
1712
|
+
const v = {};
|
|
1713
|
+
for (const [table, filters] of Object.entries(interest)) v[table] = filters === true ? true : filters.map(encodeWhere);
|
|
1714
|
+
return {
|
|
1715
|
+
t: "interest",
|
|
1716
|
+
v
|
|
1717
|
+
};
|
|
1718
|
+
}
|
|
1719
|
+
function decodeComparison(raw) {
|
|
1720
|
+
if (raw === null || typeof raw !== "object") return null;
|
|
1721
|
+
const c = raw;
|
|
1722
|
+
if (typeof c.field !== "string" || !knownOp(c.op)) return null;
|
|
1723
|
+
return c.swap === true ? {
|
|
1724
|
+
field: c.field,
|
|
1725
|
+
op: c.op,
|
|
1726
|
+
value: decodeValue(c.value),
|
|
1727
|
+
swap: true
|
|
1728
|
+
} : {
|
|
1729
|
+
field: c.field,
|
|
1730
|
+
op: c.op,
|
|
1731
|
+
value: decodeValue(c.value)
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
/**
|
|
1735
|
+
* A peer's interest message, or `null` when it is not one. A filter this
|
|
1736
|
+
* side cannot read turns its table into "all of it": never into less than
|
|
1737
|
+
* the peer asked for.
|
|
1738
|
+
*/
|
|
1739
|
+
function decodeInterest(raw) {
|
|
1740
|
+
if (raw === null || typeof raw !== "object" || raw.t !== "interest") return null;
|
|
1741
|
+
const m = raw;
|
|
1742
|
+
if (m.all === true) return "all";
|
|
1743
|
+
if (m.v === null || typeof m.v !== "object" || Array.isArray(m.v)) return null;
|
|
1744
|
+
const out = {};
|
|
1745
|
+
for (const [table, filters] of Object.entries(m.v)) {
|
|
1746
|
+
if (!Array.isArray(filters)) {
|
|
1747
|
+
if (filters === true) out[table] = true;
|
|
1748
|
+
continue;
|
|
1749
|
+
}
|
|
1750
|
+
const decoded = [];
|
|
1751
|
+
let readable = filters.length <= MAX_INTEREST_FILTERS;
|
|
1752
|
+
for (const where of readable ? filters : []) {
|
|
1753
|
+
if (!Array.isArray(where)) {
|
|
1754
|
+
readable = false;
|
|
1755
|
+
break;
|
|
1756
|
+
}
|
|
1757
|
+
const nodes = [];
|
|
1758
|
+
for (const n of where) {
|
|
1759
|
+
const group = n !== null && typeof n === "object" && Array.isArray(n.or) ? n.or : null;
|
|
1760
|
+
const list = (group ?? [n]).map(decodeComparison);
|
|
1761
|
+
if (list.includes(null) || list.length === 0) {
|
|
1762
|
+
readable = false;
|
|
1763
|
+
break;
|
|
1764
|
+
}
|
|
1765
|
+
nodes.push(group ? { or: list } : list[0]);
|
|
1766
|
+
}
|
|
1767
|
+
if (!readable) break;
|
|
1768
|
+
decoded.push(nodes);
|
|
1769
|
+
}
|
|
1770
|
+
out[table] = readable ? decoded : true;
|
|
1771
|
+
}
|
|
1772
|
+
return out;
|
|
1773
|
+
}
|
|
1774
|
+
/** Whether a device with this interest can show one of `rows` (a row before and after a write) of `table`. */
|
|
1775
|
+
function showsRow(interest, table, rows) {
|
|
1776
|
+
if (interest === "all") return true;
|
|
1777
|
+
const filters = interest[table];
|
|
1778
|
+
if (filters === void 0) return false;
|
|
1779
|
+
return filters === true || filters.some((where) => rows.some((r) => matchesWhere(where, r)));
|
|
1780
|
+
}
|
|
1608
1781
|
const SWEEP_MS = 1e3;
|
|
1609
1782
|
const randomPeerId = () => {
|
|
1610
1783
|
const bytes = new Uint8Array(8);
|
|
@@ -1623,6 +1796,14 @@ var ChannelManager = class {
|
|
|
1623
1796
|
/** Unused-argument warnings already given, so a reactive query does not repeat them. */
|
|
1624
1797
|
warnedUnused = /* @__PURE__ */ new Set();
|
|
1625
1798
|
peerId = randomPeerId();
|
|
1799
|
+
/** `channels.share`: the rule per shared table, and the channel that carries them to the user's own devices. */
|
|
1800
|
+
shared = /* @__PURE__ */ new Map();
|
|
1801
|
+
ownChannel = null;
|
|
1802
|
+
/** What each of the user's other tabs said it shows, by `peerKey`. A tab that said nothing gets everything. */
|
|
1803
|
+
interest = /* @__PURE__ */ new Map();
|
|
1804
|
+
/** The interest message last sent, so an unchanged one is not sent again. */
|
|
1805
|
+
announced = null;
|
|
1806
|
+
announcing = false;
|
|
1626
1807
|
user = null;
|
|
1627
1808
|
clock;
|
|
1628
1809
|
transport = null;
|
|
@@ -1633,9 +1814,20 @@ var ChannelManager = class {
|
|
|
1633
1814
|
constructor(schema, deps = {}) {
|
|
1634
1815
|
this.deps = deps;
|
|
1635
1816
|
this.schema = schema;
|
|
1817
|
+
for (const [table, rule] of Object.entries(deps.config?.share?.tables ?? {})) {
|
|
1818
|
+
if (rule === false || rule === void 0) continue;
|
|
1819
|
+
if (!schema.tables.some((t) => t.name === table)) {
|
|
1820
|
+
deps.logger?.warn({
|
|
1821
|
+
table,
|
|
1822
|
+
Category: "sp00ky-client::channel"
|
|
1823
|
+
}, `channels.share names '${table}', which is not a table of the schema`);
|
|
1824
|
+
continue;
|
|
1825
|
+
}
|
|
1826
|
+
this.shared.set(table, rule);
|
|
1827
|
+
}
|
|
1636
1828
|
this.tables = new Map(schema.tables.map((t) => [t.name, {
|
|
1637
1829
|
columns: t.columns,
|
|
1638
|
-
channel: t.channel === true
|
|
1830
|
+
channel: t.channel === true || this.shared.has(t.name)
|
|
1639
1831
|
}]));
|
|
1640
1832
|
this.now = deps.now ?? Date.now;
|
|
1641
1833
|
this.confirmMs = Math.max(0, deps.config?.confirmTimeoutMs ?? 5e3);
|
|
@@ -1644,12 +1836,57 @@ var ChannelManager = class {
|
|
|
1644
1836
|
0,
|
|
1645
1837
|
this.peerId
|
|
1646
1838
|
];
|
|
1839
|
+
if (this.shared.size > 0) {
|
|
1840
|
+
this.ownChannel = {
|
|
1841
|
+
scopes: [...this.shared].map(([table, rule]) => typeof rule === "function" ? {
|
|
1842
|
+
table,
|
|
1843
|
+
where: [],
|
|
1844
|
+
test: safeTest(rule)
|
|
1845
|
+
} : {
|
|
1846
|
+
table,
|
|
1847
|
+
where: []
|
|
1848
|
+
}),
|
|
1849
|
+
listed: [],
|
|
1850
|
+
users: /* @__PURE__ */ new Set(),
|
|
1851
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
1852
|
+
state: {
|
|
1853
|
+
status: "idle",
|
|
1854
|
+
peers: []
|
|
1855
|
+
},
|
|
1856
|
+
closed: false,
|
|
1857
|
+
own: true
|
|
1858
|
+
};
|
|
1859
|
+
this.channels.add(this.ownChannel);
|
|
1860
|
+
}
|
|
1647
1861
|
}
|
|
1648
|
-
/** True when any table is a channel table; otherwise the client skips all of this. */
|
|
1862
|
+
/** True when any table is a channel table or shared; otherwise the client skips all of this. */
|
|
1649
1863
|
get enabled() {
|
|
1650
1864
|
for (const t of this.tables.values()) if (t.channel) return true;
|
|
1651
1865
|
return false;
|
|
1652
1866
|
}
|
|
1867
|
+
/** Whether the user's own devices are part of this (`channels.share` names a table). */
|
|
1868
|
+
get sharing() {
|
|
1869
|
+
return this.ownChannel !== null;
|
|
1870
|
+
}
|
|
1871
|
+
/** How the user's own devices are doing (`channels.share`): `idle` when nothing is shared or nobody is signed in. */
|
|
1872
|
+
ownState() {
|
|
1873
|
+
return this.ownChannel?.state ?? {
|
|
1874
|
+
status: "idle",
|
|
1875
|
+
peers: []
|
|
1876
|
+
};
|
|
1877
|
+
}
|
|
1878
|
+
/** Called at once with the state of the link to the user's own devices, then on every change. */
|
|
1879
|
+
subscribeOwn(cb) {
|
|
1880
|
+
const ch = this.ownChannel;
|
|
1881
|
+
cb(this.ownState());
|
|
1882
|
+
if (!ch) return () => {};
|
|
1883
|
+
ch.listeners.add(cb);
|
|
1884
|
+
return () => void ch.listeners.delete(cb);
|
|
1885
|
+
}
|
|
1886
|
+
/** What a registered query can show, as `tap` takes it. */
|
|
1887
|
+
interestOf(plan, params) {
|
|
1888
|
+
return plan ? queryInterest((table) => this.tables.get(table)?.columns, plan, params) : null;
|
|
1889
|
+
}
|
|
1653
1890
|
/** The signed-in user changed: peers, their values and the transport start over. */
|
|
1654
1891
|
setUser(user) {
|
|
1655
1892
|
if (user === this.user) return;
|
|
@@ -1658,9 +1895,11 @@ var ChannelManager = class {
|
|
|
1658
1895
|
this.transport = null;
|
|
1659
1896
|
this.connected.clear();
|
|
1660
1897
|
this.userStatus.clear();
|
|
1898
|
+
this.interest.clear();
|
|
1899
|
+
this.announced = null;
|
|
1661
1900
|
const touched = new Set(this.overlay.keys());
|
|
1662
1901
|
this.overlay.clear();
|
|
1663
|
-
for (const ch of this.channels) ch.users = peerUsers(ch.listed, user);
|
|
1902
|
+
for (const ch of this.channels) ch.users = ch.own ? new Set(user ? [user] : []) : peerUsers(ch.listed, user);
|
|
1664
1903
|
this.syncWanted();
|
|
1665
1904
|
this.emitFor(touched);
|
|
1666
1905
|
this.notifyAll();
|
|
@@ -1745,13 +1984,15 @@ var ChannelManager = class {
|
|
|
1745
1984
|
* Follow a subscription: `feed` it the raw rows, and `cb` gets them with
|
|
1746
1985
|
* the overlay folded in, again whenever the overlay changes for its rows.
|
|
1747
1986
|
*/
|
|
1748
|
-
tap(cb) {
|
|
1987
|
+
tap(cb, interest = null) {
|
|
1749
1988
|
const tap = {
|
|
1750
1989
|
cb,
|
|
1751
1990
|
raw: null,
|
|
1752
|
-
ids: null
|
|
1991
|
+
ids: null,
|
|
1992
|
+
interest
|
|
1753
1993
|
};
|
|
1754
1994
|
this.taps.add(tap);
|
|
1995
|
+
this.announceSoon();
|
|
1755
1996
|
return {
|
|
1756
1997
|
feed: (rows) => {
|
|
1757
1998
|
tap.raw = rows;
|
|
@@ -1759,7 +2000,7 @@ var ChannelManager = class {
|
|
|
1759
2000
|
this.emit(tap);
|
|
1760
2001
|
},
|
|
1761
2002
|
stop: () => {
|
|
1762
|
-
this.taps.delete(tap);
|
|
2003
|
+
if (this.taps.delete(tap)) this.announceSoon();
|
|
1763
2004
|
}
|
|
1764
2005
|
};
|
|
1765
2006
|
}
|
|
@@ -1809,7 +2050,8 @@ var ChannelManager = class {
|
|
|
1809
2050
|
...row ?? { id: rid },
|
|
1810
2051
|
...patch
|
|
1811
2052
|
};
|
|
1812
|
-
|
|
2053
|
+
const rows = row ? [row, after] : [after];
|
|
2054
|
+
this.send(this.targets(table, rows, scope), table, rid, patch, hlc, "update", rows);
|
|
1813
2055
|
});
|
|
1814
2056
|
}
|
|
1815
2057
|
/**
|
|
@@ -1835,10 +2077,11 @@ var ChannelManager = class {
|
|
|
1835
2077
|
this.overlay.set(rid, map);
|
|
1836
2078
|
this.emitFor(new Set([rid]));
|
|
1837
2079
|
}
|
|
1838
|
-
|
|
2080
|
+
const rows = [{
|
|
1839
2081
|
...full,
|
|
1840
2082
|
id: rid
|
|
1841
|
-
}]
|
|
2083
|
+
}];
|
|
2084
|
+
this.send(this.targets(table, rows, scope), table, rid, full, hlc, "create", rows);
|
|
1842
2085
|
}
|
|
1843
2086
|
/**
|
|
1844
2087
|
* An own delete: the peers hide the row at once. Resolves once it is sent;
|
|
@@ -1849,12 +2092,13 @@ var ChannelManager = class {
|
|
|
1849
2092
|
const rid = normalizeId(table, id);
|
|
1850
2093
|
const hlc = this.tick();
|
|
1851
2094
|
const row = await this.rowFor(rid);
|
|
1852
|
-
if (row) this.send(this.targets(table, [row], scope), table, rid, {}, hlc, "delete");
|
|
2095
|
+
if (row) this.send(this.targets(table, [row], scope), table, rid, {}, hlc, "delete", [row]);
|
|
1853
2096
|
if (this.overlay.delete(rid)) this.emitFor(new Set([rid]));
|
|
1854
2097
|
}
|
|
1855
2098
|
/** A transport delivered a message from `from`. */
|
|
1856
2099
|
receive(from, raw) {
|
|
1857
2100
|
if (this.closed) return;
|
|
2101
|
+
if (raw !== null && typeof raw === "object" && raw.t === "interest") return this.receiveInterest(from, raw);
|
|
1858
2102
|
const msg = parseMessage(raw);
|
|
1859
2103
|
if (!msg) return this.drop(from, "malformed message");
|
|
1860
2104
|
this.observe(msg.hlc);
|
|
@@ -1972,6 +2216,13 @@ var ChannelManager = class {
|
|
|
1972
2216
|
Category: "sp00ky-client::channel"
|
|
1973
2217
|
}, "peer delete failed"));
|
|
1974
2218
|
}
|
|
2219
|
+
/** One of the user's own tabs said what it shows. Anybody else's word on that is ignored. */
|
|
2220
|
+
receiveInterest(from, raw) {
|
|
2221
|
+
if (from.user !== this.user || !this.ownChannel) return this.drop(from, "interest from another user");
|
|
2222
|
+
const interest = decodeInterest(raw);
|
|
2223
|
+
if (!interest) return this.drop(from, "malformed interest");
|
|
2224
|
+
this.interest.set(peerKey(from), interest);
|
|
2225
|
+
}
|
|
1975
2226
|
accepts(op) {
|
|
1976
2227
|
const rule = this.deps.config?.accept?.[op.table];
|
|
1977
2228
|
if (!rule) return true;
|
|
@@ -1991,9 +2242,11 @@ var ChannelManager = class {
|
|
|
1991
2242
|
if (up) {
|
|
1992
2243
|
this.connected.set(key, peer);
|
|
1993
2244
|
this.userStatus.set(peer.user, "connected");
|
|
2245
|
+
if (this.ownChannel && peer.user === this.user) this.transport?.send(peer, encodeInterest(this.ownInterest()));
|
|
1994
2246
|
this.sendSnapshot(peer);
|
|
1995
2247
|
} else {
|
|
1996
2248
|
this.connected.delete(key);
|
|
2249
|
+
this.interest.delete(key);
|
|
1997
2250
|
const touched = /* @__PURE__ */ new Set();
|
|
1998
2251
|
for (const [rid, fields] of this.overlay) {
|
|
1999
2252
|
for (const [f, e] of fields) if (e.from === key && e.ephemeral) {
|
|
@@ -2058,7 +2311,7 @@ var ChannelManager = class {
|
|
|
2058
2311
|
targets(table, rows, scope) {
|
|
2059
2312
|
const users = /* @__PURE__ */ new Set();
|
|
2060
2313
|
const pick = scope ? this.handles.get(scope) : void 0;
|
|
2061
|
-
for (const ch of pick ? [pick] : this.channels) {
|
|
2314
|
+
for (const ch of pick ? this.ownChannel ? [pick, this.ownChannel] : [pick] : this.channels) {
|
|
2062
2315
|
if (ch.closed || !carries(ch, table, rows)) continue;
|
|
2063
2316
|
for (const u of ch.users) users.add(u);
|
|
2064
2317
|
}
|
|
@@ -2071,7 +2324,7 @@ var ChannelManager = class {
|
|
|
2071
2324
|
const stored = await this.deps.rows?.read(rid).catch(() => null);
|
|
2072
2325
|
return stored ? applyOverlay([stored], this.overlay)[0] : null;
|
|
2073
2326
|
}
|
|
2074
|
-
send(users, table, rid, patch, hlc, kind) {
|
|
2327
|
+
send(users, table, rid, patch, hlc, kind, rows) {
|
|
2075
2328
|
const transport = this.transport;
|
|
2076
2329
|
if (!transport || users.size === 0) return;
|
|
2077
2330
|
const encoded = {};
|
|
@@ -2090,7 +2343,31 @@ var ChannelManager = class {
|
|
|
2090
2343
|
patch: encoded,
|
|
2091
2344
|
hlc
|
|
2092
2345
|
};
|
|
2093
|
-
for (const peer of this.connected
|
|
2346
|
+
for (const [key, peer] of this.connected) {
|
|
2347
|
+
if (!users.has(peer.user)) continue;
|
|
2348
|
+
const interest = peer.user === this.user ? this.interest.get(key) : void 0;
|
|
2349
|
+
if (interest !== void 0 && !showsRow(interest, table, rows)) continue;
|
|
2350
|
+
transport.send(peer, message);
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
/** What this tab's subscriptions show of the shared tables. */
|
|
2354
|
+
ownInterest() {
|
|
2355
|
+
return mergeInterest([...this.taps].map((t) => t.interest), (table) => this.shared.has(table));
|
|
2356
|
+
}
|
|
2357
|
+
/** Tell the user's other tabs what this one shows, once the subscriptions of this turn are all in. */
|
|
2358
|
+
announceSoon() {
|
|
2359
|
+
if (!this.ownChannel || this.announcing || this.closed) return;
|
|
2360
|
+
this.announcing = true;
|
|
2361
|
+
Promise.resolve().then(() => {
|
|
2362
|
+
this.announcing = false;
|
|
2363
|
+
const transport = this.transport;
|
|
2364
|
+
if (this.closed || !transport || !this.user) return;
|
|
2365
|
+
const message = encodeInterest(this.ownInterest());
|
|
2366
|
+
const text = JSON.stringify(message);
|
|
2367
|
+
if (text === this.announced) return;
|
|
2368
|
+
this.announced = text;
|
|
2369
|
+
for (const peer of this.connected.values()) if (peer.user === this.user) transport.send(peer, message);
|
|
2370
|
+
});
|
|
2094
2371
|
}
|
|
2095
2372
|
/** Own ephemeral values of rows inside a channel a newly connected peer is listed on. */
|
|
2096
2373
|
sendSnapshot(peer) {
|
|
@@ -2241,8 +2518,16 @@ var ChannelManager = class {
|
|
|
2241
2518
|
};
|
|
2242
2519
|
/** Whether a channel has a query on `table` that one of `rows` matches. */
|
|
2243
2520
|
function carries(ch, table, rows) {
|
|
2244
|
-
return ch.scopes.some((sc) => sc.table === table && rows.some((r) => matchesWhere(sc.where, r)));
|
|
2521
|
+
return ch.scopes.some((sc) => sc.table === table && rows.some((r) => matchesWhere(sc.where, r) && (!sc.test || sc.test(r))));
|
|
2245
2522
|
}
|
|
2523
|
+
/** A share rule that never throws: a rule that does shares nothing. */
|
|
2524
|
+
const safeTest = (rule) => (row) => {
|
|
2525
|
+
try {
|
|
2526
|
+
return rule(row) === true;
|
|
2527
|
+
} catch {
|
|
2528
|
+
return false;
|
|
2529
|
+
}
|
|
2530
|
+
};
|
|
2246
2531
|
/** The fields of `row` the table has as plain columns (no id, no `@crdt`). */
|
|
2247
2532
|
function pickColumns(columns, row) {
|
|
2248
2533
|
const out = {};
|
|
@@ -2284,8 +2569,8 @@ function findRow(rows, rid, depth) {
|
|
|
2284
2569
|
//#region src/modules/channel/webrtc.ts
|
|
2285
2570
|
const DEFAULT_ICE = [{ urls: "stun:stun.cloudflare.com:3478" }];
|
|
2286
2571
|
const ICE_FLUSH_MS = 20;
|
|
2287
|
-
const RETRY_BASE_MS$
|
|
2288
|
-
const RETRY_MAX_MS$
|
|
2572
|
+
const RETRY_BASE_MS$2 = 2e3;
|
|
2573
|
+
const RETRY_MAX_MS$2 = 3e4;
|
|
2289
2574
|
const randomSid = () => Math.random().toString(36).slice(2, 10);
|
|
2290
2575
|
function webrtcTransport(hooks, opts) {
|
|
2291
2576
|
const PC = opts.RTCPeerConnection ?? globalThis.RTCPeerConnection;
|
|
@@ -2344,7 +2629,7 @@ function webrtcTransport(hooks, opts) {
|
|
|
2344
2629
|
timer: null
|
|
2345
2630
|
};
|
|
2346
2631
|
if (r.timer) return;
|
|
2347
|
-
const delay = Math.min(RETRY_MAX_MS$
|
|
2632
|
+
const delay = Math.min(RETRY_MAX_MS$2, RETRY_BASE_MS$2 * 2 ** r.attempts);
|
|
2348
2633
|
r.attempts++;
|
|
2349
2634
|
r.timer = setTimeout(() => {
|
|
2350
2635
|
r.timer = null;
|
|
@@ -2683,6 +2968,608 @@ function surrealSignal(remote, connection, logger) {
|
|
|
2683
2968
|
};
|
|
2684
2969
|
}
|
|
2685
2970
|
|
|
2971
|
+
//#endregion
|
|
2972
|
+
//#region src/modules/channel/room.ts
|
|
2973
|
+
const PROTOCOL = 1;
|
|
2974
|
+
const RETRY_BASE_MS$1 = 500;
|
|
2975
|
+
const RETRY_MAX_MS$1 = 3e4;
|
|
2976
|
+
/** After a refusal that a retry will not fix soon (not signed in at the relay, room full). */
|
|
2977
|
+
const RETRY_REFUSED_MS = 3e4;
|
|
2978
|
+
const BEAT_MS = 2e4;
|
|
2979
|
+
const SIGNAL_KINDS = new Set([
|
|
2980
|
+
"hello",
|
|
2981
|
+
"offer",
|
|
2982
|
+
"answer",
|
|
2983
|
+
"ice"
|
|
2984
|
+
]);
|
|
2985
|
+
/**
|
|
2986
|
+
* Two spellings of one record id. The database prints a key the way it would
|
|
2987
|
+
* have to be written (`user:⟨a-b⟩`, backticks, or `user:u'0190…'` for a
|
|
2988
|
+
* uuid), the client keeps it bare (`user:a-b`): the wrapping is not part of
|
|
2989
|
+
* who it is. Verified against SurrealDB 4.0.1.
|
|
2990
|
+
*/
|
|
2991
|
+
const bareId = (id) => {
|
|
2992
|
+
const at = id.indexOf(":");
|
|
2993
|
+
return id.slice(0, at + 1) + id.slice(at + 1).replace(/^u(?=['"])/, "").replace(/[⟨⟩`'"]/g, "");
|
|
2994
|
+
};
|
|
2995
|
+
const sameUser = (a, b) => bareId(a) === bareId(b);
|
|
2996
|
+
/** Whether this runtime can hold a room link at all. */
|
|
2997
|
+
const roomSupported = (ws) => (ws ?? globalThis.WebSocket) !== void 0;
|
|
2998
|
+
function roomLink(hooks, opts) {
|
|
2999
|
+
const WS = opts.WebSocket ?? globalThis.WebSocket;
|
|
3000
|
+
const log = opts.logger;
|
|
3001
|
+
const peers = /* @__PURE__ */ new Set();
|
|
3002
|
+
/** Members the data channel to is open: they get their messages there. */
|
|
3003
|
+
const directOpen = /* @__PURE__ */ new Set();
|
|
3004
|
+
let socket = null;
|
|
3005
|
+
let welcomed = false;
|
|
3006
|
+
let closed = false;
|
|
3007
|
+
let attempts = 0;
|
|
3008
|
+
let retry = null;
|
|
3009
|
+
let beat = null;
|
|
3010
|
+
let awaitingPong = false;
|
|
3011
|
+
let onSignal = null;
|
|
3012
|
+
const relay = (to, d) => {
|
|
3013
|
+
const ws = socket;
|
|
3014
|
+
if (!ws || !welcomed || ws.readyState !== 1) return;
|
|
3015
|
+
try {
|
|
3016
|
+
ws.send(JSON.stringify(to === null ? {
|
|
3017
|
+
t: "msg",
|
|
3018
|
+
d
|
|
3019
|
+
} : {
|
|
3020
|
+
t: "msg",
|
|
3021
|
+
to,
|
|
3022
|
+
d
|
|
3023
|
+
}));
|
|
3024
|
+
} catch (error) {
|
|
3025
|
+
log?.debug({
|
|
3026
|
+
error,
|
|
3027
|
+
Category: "sp00ky-client::channel"
|
|
3028
|
+
}, "room send failed");
|
|
3029
|
+
}
|
|
3030
|
+
};
|
|
3031
|
+
const direct = opts.direct === false ? null : webrtcTransport({
|
|
3032
|
+
self: () => hooks.self(),
|
|
3033
|
+
onPeer: (ref, up) => {
|
|
3034
|
+
if (up) directOpen.add(ref.peer);
|
|
3035
|
+
else directOpen.delete(ref.peer);
|
|
3036
|
+
},
|
|
3037
|
+
onMessage: (ref, message) => {
|
|
3038
|
+
if (peers.has(ref.peer)) hooks.onMessage(ref.peer, message);
|
|
3039
|
+
},
|
|
3040
|
+
onStatus: () => {}
|
|
3041
|
+
}, {
|
|
3042
|
+
signal: {
|
|
3043
|
+
send: async (s) => relay(s.toPeer === null ? null : [s.toPeer], { s: {
|
|
3044
|
+
kind: s.kind,
|
|
3045
|
+
payload: s.payload,
|
|
3046
|
+
toPeer: s.toPeer
|
|
3047
|
+
} }),
|
|
3048
|
+
listen: (_self, cb) => {
|
|
3049
|
+
onSignal = cb;
|
|
3050
|
+
return () => {
|
|
3051
|
+
if (onSignal === cb) onSignal = null;
|
|
3052
|
+
};
|
|
3053
|
+
}
|
|
3054
|
+
},
|
|
3055
|
+
iceServers: opts.iceServers,
|
|
3056
|
+
logger: log,
|
|
3057
|
+
RTCPeerConnection: opts.RTCPeerConnection
|
|
3058
|
+
});
|
|
3059
|
+
/** The direct link is for two: wanted while there is exactly one other member. */
|
|
3060
|
+
const syncDirect = () => {
|
|
3061
|
+
const self = hooks.self();
|
|
3062
|
+
direct?.want(new Set(self && welcomed && peers.size === 1 ? [self.user] : []));
|
|
3063
|
+
};
|
|
3064
|
+
const stopBeat = () => {
|
|
3065
|
+
if (beat) clearInterval(beat);
|
|
3066
|
+
beat = null;
|
|
3067
|
+
awaitingPong = false;
|
|
3068
|
+
};
|
|
3069
|
+
const scheduleRetry = (delay) => {
|
|
3070
|
+
if (closed || retry) return;
|
|
3071
|
+
retry = setTimeout(() => {
|
|
3072
|
+
retry = null;
|
|
3073
|
+
connect();
|
|
3074
|
+
}, delay);
|
|
3075
|
+
};
|
|
3076
|
+
/** The socket is gone: every member with it, and the direct link (it has nobody to prove its peer anymore). */
|
|
3077
|
+
const dropped = (delay) => {
|
|
3078
|
+
socket = null;
|
|
3079
|
+
stopBeat();
|
|
3080
|
+
const was = [...peers];
|
|
3081
|
+
peers.clear();
|
|
3082
|
+
welcomed = false;
|
|
3083
|
+
syncDirect();
|
|
3084
|
+
for (const p of was) hooks.onPeer(p, false);
|
|
3085
|
+
if (closed) return;
|
|
3086
|
+
attempts++;
|
|
3087
|
+
hooks.onStatus(attempts > 2 || delay !== void 0 ? "failed" : "connecting");
|
|
3088
|
+
scheduleRetry(delay ?? Math.min(RETRY_MAX_MS$1, RETRY_BASE_MS$1 * 2 ** (attempts - 1)) * (.75 + Math.random() * .5));
|
|
3089
|
+
};
|
|
3090
|
+
const onFrame = (ws, text, self) => {
|
|
3091
|
+
let f;
|
|
3092
|
+
try {
|
|
3093
|
+
const parsed = JSON.parse(text);
|
|
3094
|
+
if (parsed === null || typeof parsed !== "object") return;
|
|
3095
|
+
f = parsed;
|
|
3096
|
+
} catch {
|
|
3097
|
+
return;
|
|
3098
|
+
}
|
|
3099
|
+
switch (f.t) {
|
|
3100
|
+
case "welcome":
|
|
3101
|
+
if (welcomed) return;
|
|
3102
|
+
if (typeof f.user !== "string" || !sameUser(f.user, self.user)) {
|
|
3103
|
+
log?.warn({ Category: "sp00ky-client::channel" }, "the room relay answered for another user; not joining");
|
|
3104
|
+
socket = null;
|
|
3105
|
+
ws.close();
|
|
3106
|
+
dropped(RETRY_REFUSED_MS);
|
|
3107
|
+
return;
|
|
3108
|
+
}
|
|
3109
|
+
welcomed = true;
|
|
3110
|
+
attempts = 0;
|
|
3111
|
+
awaitingPong = false;
|
|
3112
|
+
beat = setInterval(() => {
|
|
3113
|
+
if (awaitingPong) return ws.close();
|
|
3114
|
+
awaitingPong = true;
|
|
3115
|
+
try {
|
|
3116
|
+
ws.send("{\"t\":\"ping\"}");
|
|
3117
|
+
} catch {}
|
|
3118
|
+
}, BEAT_MS);
|
|
3119
|
+
hooks.onStatus("connected");
|
|
3120
|
+
for (const p of Array.isArray(f.peers) ? f.peers : []) {
|
|
3121
|
+
if (typeof p !== "string" || p === self.peer || peers.has(p)) continue;
|
|
3122
|
+
peers.add(p);
|
|
3123
|
+
hooks.onPeer(p, true);
|
|
3124
|
+
}
|
|
3125
|
+
syncDirect();
|
|
3126
|
+
return;
|
|
3127
|
+
case "join":
|
|
3128
|
+
if (!welcomed || typeof f.peer !== "string" || f.peer === self.peer || peers.has(f.peer)) return;
|
|
3129
|
+
peers.add(f.peer);
|
|
3130
|
+
hooks.onPeer(f.peer, true);
|
|
3131
|
+
syncDirect();
|
|
3132
|
+
return;
|
|
3133
|
+
case "leave":
|
|
3134
|
+
if (typeof f.peer !== "string" || !peers.delete(f.peer)) return;
|
|
3135
|
+
hooks.onPeer(f.peer, false);
|
|
3136
|
+
syncDirect();
|
|
3137
|
+
return;
|
|
3138
|
+
case "msg": {
|
|
3139
|
+
if (typeof f.from !== "string" || !peers.has(f.from) || f.d === null || typeof f.d !== "object") return;
|
|
3140
|
+
const d = f.d;
|
|
3141
|
+
if (d.s !== void 0) {
|
|
3142
|
+
const s = d.s;
|
|
3143
|
+
if (!s || typeof s.kind !== "string" || !SIGNAL_KINDS.has(s.kind)) return;
|
|
3144
|
+
onSignal?.({
|
|
3145
|
+
from: self.user,
|
|
3146
|
+
fromPeer: f.from,
|
|
3147
|
+
toPeer: typeof s.toPeer === "string" ? s.toPeer : null,
|
|
3148
|
+
kind: s.kind,
|
|
3149
|
+
payload: typeof s.payload === "string" ? s.payload : null
|
|
3150
|
+
});
|
|
3151
|
+
return;
|
|
3152
|
+
}
|
|
3153
|
+
if ("m" in d) hooks.onMessage(f.from, d.m);
|
|
3154
|
+
return;
|
|
3155
|
+
}
|
|
3156
|
+
case "pong":
|
|
3157
|
+
awaitingPong = false;
|
|
3158
|
+
return;
|
|
3159
|
+
case "error": {
|
|
3160
|
+
const code = typeof f.code === "string" ? f.code : "unknown";
|
|
3161
|
+
log?.debug({
|
|
3162
|
+
code,
|
|
3163
|
+
Category: "sp00ky-client::channel"
|
|
3164
|
+
}, "room relay refused");
|
|
3165
|
+
socket = null;
|
|
3166
|
+
ws.close();
|
|
3167
|
+
if (code === "reauth") {
|
|
3168
|
+
attempts = 0;
|
|
3169
|
+
dropped();
|
|
3170
|
+
} else dropped(RETRY_REFUSED_MS);
|
|
3171
|
+
return;
|
|
3172
|
+
}
|
|
3173
|
+
}
|
|
3174
|
+
};
|
|
3175
|
+
function connect() {
|
|
3176
|
+
if (closed || socket || !WS) return;
|
|
3177
|
+
const self = hooks.self();
|
|
3178
|
+
if (!self) return;
|
|
3179
|
+
const token = opts.token();
|
|
3180
|
+
if (!token) {
|
|
3181
|
+
scheduleRetry(RETRY_BASE_MS$1);
|
|
3182
|
+
return;
|
|
3183
|
+
}
|
|
3184
|
+
let ws;
|
|
3185
|
+
try {
|
|
3186
|
+
ws = new WS(opts.url);
|
|
3187
|
+
} catch (error) {
|
|
3188
|
+
log?.warn({
|
|
3189
|
+
error,
|
|
3190
|
+
Category: "sp00ky-client::channel"
|
|
3191
|
+
}, "the room relay address cannot be opened");
|
|
3192
|
+
hooks.onStatus("failed");
|
|
3193
|
+
return;
|
|
3194
|
+
}
|
|
3195
|
+
socket = ws;
|
|
3196
|
+
ws.onopen = () => {
|
|
3197
|
+
if (socket === ws) ws.send(JSON.stringify({
|
|
3198
|
+
t: "hello",
|
|
3199
|
+
v: PROTOCOL,
|
|
3200
|
+
token,
|
|
3201
|
+
peer: self.peer
|
|
3202
|
+
}));
|
|
3203
|
+
};
|
|
3204
|
+
ws.onmessage = (event) => {
|
|
3205
|
+
if (socket === ws && typeof event.data === "string") onFrame(ws, event.data, self);
|
|
3206
|
+
};
|
|
3207
|
+
ws.onclose = () => {
|
|
3208
|
+
if (socket === ws) dropped();
|
|
3209
|
+
};
|
|
3210
|
+
ws.onerror = () => {};
|
|
3211
|
+
}
|
|
3212
|
+
hooks.onStatus("connecting");
|
|
3213
|
+
connect();
|
|
3214
|
+
return {
|
|
3215
|
+
send(to, data) {
|
|
3216
|
+
if (closed || !welcomed) return;
|
|
3217
|
+
const self = hooks.self();
|
|
3218
|
+
const targets = to === null ? [...peers] : to.filter((p) => peers.has(p));
|
|
3219
|
+
const viaRelay = [];
|
|
3220
|
+
for (const p of targets) if (direct && self && directOpen.has(p)) direct.send({
|
|
3221
|
+
user: self.user,
|
|
3222
|
+
peer: p
|
|
3223
|
+
}, data);
|
|
3224
|
+
else viaRelay.push(p);
|
|
3225
|
+
if (viaRelay.length > 0) relay(viaRelay.length === peers.size ? null : viaRelay, { m: data });
|
|
3226
|
+
},
|
|
3227
|
+
close() {
|
|
3228
|
+
if (closed) return;
|
|
3229
|
+
closed = true;
|
|
3230
|
+
if (retry) clearTimeout(retry);
|
|
3231
|
+
retry = null;
|
|
3232
|
+
stopBeat();
|
|
3233
|
+
direct?.close();
|
|
3234
|
+
const ws = socket;
|
|
3235
|
+
socket = null;
|
|
3236
|
+
welcomed = false;
|
|
3237
|
+
peers.clear();
|
|
3238
|
+
directOpen.clear();
|
|
3239
|
+
try {
|
|
3240
|
+
ws?.close();
|
|
3241
|
+
} catch {}
|
|
3242
|
+
}
|
|
3243
|
+
};
|
|
3244
|
+
}
|
|
3245
|
+
/**
|
|
3246
|
+
* One transport out of two: the user's own devices are reached through
|
|
3247
|
+
* `own` (the room), everybody else through `others` (the mesh between
|
|
3248
|
+
* users). Without `own`, the user's own devices are simply never reached.
|
|
3249
|
+
*/
|
|
3250
|
+
function splitTransport(own, others) {
|
|
3251
|
+
return (hooks) => {
|
|
3252
|
+
const mesh = others(hooks);
|
|
3253
|
+
const room = own ? own(hooks) : null;
|
|
3254
|
+
return {
|
|
3255
|
+
supported: mesh.supported || (room?.supported ?? false),
|
|
3256
|
+
want(users) {
|
|
3257
|
+
const self = hooks.self()?.user ?? null;
|
|
3258
|
+
const rest = new Set(users);
|
|
3259
|
+
const mine = self !== null && rest.delete(self);
|
|
3260
|
+
room?.want(new Set(mine && self !== null ? [self] : []));
|
|
3261
|
+
mesh.want(rest);
|
|
3262
|
+
},
|
|
3263
|
+
send(to, message) {
|
|
3264
|
+
(room && to.user === hooks.self()?.user ? room : mesh).send(to, message);
|
|
3265
|
+
},
|
|
3266
|
+
close() {
|
|
3267
|
+
room?.close();
|
|
3268
|
+
mesh.close();
|
|
3269
|
+
}
|
|
3270
|
+
};
|
|
3271
|
+
};
|
|
3272
|
+
}
|
|
3273
|
+
|
|
3274
|
+
//#endregion
|
|
3275
|
+
//#region src/modules/channel/hub.ts
|
|
3276
|
+
const MAX_TABS = 64;
|
|
3277
|
+
const isTabId = (v) => typeof v === "string" && v.length > 0 && v.length <= 64;
|
|
3278
|
+
const tabList = (v) => Array.isArray(v) && v.length <= MAX_TABS && v.every(isTabId) ? v : null;
|
|
3279
|
+
const defaultLocks = () => globalThis.navigator?.locks ?? null;
|
|
3280
|
+
const defaultBus = () => {
|
|
3281
|
+
const BC = globalThis.BroadcastChannel;
|
|
3282
|
+
return BC ? (name) => new BC(name) : null;
|
|
3283
|
+
};
|
|
3284
|
+
function hubTransport(hooks, opts) {
|
|
3285
|
+
const locks = opts.locks === void 0 ? defaultLocks() : opts.locks;
|
|
3286
|
+
const openBus = opts.bus === void 0 ? defaultBus() : opts.bus;
|
|
3287
|
+
const log = opts.logger;
|
|
3288
|
+
/** This tab while it takes part, else null. */
|
|
3289
|
+
let me = null;
|
|
3290
|
+
/** Counts starts, so a lock granted for an earlier one does nothing. */
|
|
3291
|
+
let run = 0;
|
|
3292
|
+
let bus = null;
|
|
3293
|
+
let isHub = false;
|
|
3294
|
+
let link = null;
|
|
3295
|
+
let releaseHub = null;
|
|
3296
|
+
let releaseTab = null;
|
|
3297
|
+
/** The hub's: the other tabs of this browser. */
|
|
3298
|
+
const localTabs = /* @__PURE__ */ new Set();
|
|
3299
|
+
/** The other browsers and the tabs each speaks for. The hub's is the truth, the other tabs hold a copy. */
|
|
3300
|
+
const browsers = /* @__PURE__ */ new Map();
|
|
3301
|
+
/** The tabs of other browsers this tab has reported as up. */
|
|
3302
|
+
const up = /* @__PURE__ */ new Set();
|
|
3303
|
+
let status = "connecting";
|
|
3304
|
+
let reported = null;
|
|
3305
|
+
/** Messages of this turn, each with the tabs it goes to: one frame per message, not one per tab. */
|
|
3306
|
+
const pending = /* @__PURE__ */ new Map();
|
|
3307
|
+
let flushing = false;
|
|
3308
|
+
const post = (message) => {
|
|
3309
|
+
try {
|
|
3310
|
+
bus?.postMessage(message);
|
|
3311
|
+
} catch (error) {
|
|
3312
|
+
log?.debug({
|
|
3313
|
+
error,
|
|
3314
|
+
Category: "sp00ky-client::channel"
|
|
3315
|
+
}, "channel bus post failed");
|
|
3316
|
+
}
|
|
3317
|
+
};
|
|
3318
|
+
/** Tell the manager which tabs of other browsers came and went, and how the link is doing. */
|
|
3319
|
+
const apply = () => {
|
|
3320
|
+
const self = me;
|
|
3321
|
+
if (!self) return;
|
|
3322
|
+
const now = /* @__PURE__ */ new Set();
|
|
3323
|
+
for (const tabs of browsers.values()) for (const t of tabs) if (t !== self.peer) now.add(t);
|
|
3324
|
+
for (const t of [...up]) {
|
|
3325
|
+
if (now.has(t)) continue;
|
|
3326
|
+
up.delete(t);
|
|
3327
|
+
hooks.onPeer({
|
|
3328
|
+
user: self.user,
|
|
3329
|
+
peer: t
|
|
3330
|
+
}, false);
|
|
3331
|
+
}
|
|
3332
|
+
for (const t of now) {
|
|
3333
|
+
if (up.has(t)) continue;
|
|
3334
|
+
up.add(t);
|
|
3335
|
+
hooks.onPeer({
|
|
3336
|
+
user: self.user,
|
|
3337
|
+
peer: t
|
|
3338
|
+
}, true);
|
|
3339
|
+
}
|
|
3340
|
+
if (status !== reported) {
|
|
3341
|
+
reported = status;
|
|
3342
|
+
hooks.onStatus(self.user, status);
|
|
3343
|
+
}
|
|
3344
|
+
};
|
|
3345
|
+
const publish = () => {
|
|
3346
|
+
apply();
|
|
3347
|
+
const out = {};
|
|
3348
|
+
for (const [b, tabs] of browsers) out[b] = [...tabs];
|
|
3349
|
+
post({
|
|
3350
|
+
k: "remote",
|
|
3351
|
+
browsers: out,
|
|
3352
|
+
status
|
|
3353
|
+
});
|
|
3354
|
+
};
|
|
3355
|
+
/** The tabs this browser speaks for changed: the other hubs hear it. */
|
|
3356
|
+
const announceTabs = (to) => {
|
|
3357
|
+
if (me) link?.send(to, {
|
|
3358
|
+
h: "tabs",
|
|
3359
|
+
tabs: [me.peer, ...localTabs]
|
|
3360
|
+
});
|
|
3361
|
+
};
|
|
3362
|
+
const hubSend = (from, to, m) => {
|
|
3363
|
+
const dest = [];
|
|
3364
|
+
for (const [b, tabs] of browsers) if (to.some((t) => tabs.has(t))) dest.push(b);
|
|
3365
|
+
if (dest.length > 0) link?.send(dest.length === browsers.size ? null : dest, {
|
|
3366
|
+
h: "m",
|
|
3367
|
+
from,
|
|
3368
|
+
to,
|
|
3369
|
+
m
|
|
3370
|
+
});
|
|
3371
|
+
};
|
|
3372
|
+
/** A message of another browser's tab: to this tab, and on to the others it names. */
|
|
3373
|
+
const deliver = (from, to, m) => {
|
|
3374
|
+
const self = me;
|
|
3375
|
+
if (!self) return;
|
|
3376
|
+
if (localTabs.size > 0 && (to === null || to.some((t) => localTabs.has(t)))) post({
|
|
3377
|
+
k: "in",
|
|
3378
|
+
from,
|
|
3379
|
+
to,
|
|
3380
|
+
m
|
|
3381
|
+
});
|
|
3382
|
+
if (to === null || to.includes(self.peer)) hooks.onMessage({
|
|
3383
|
+
user: self.user,
|
|
3384
|
+
peer: from
|
|
3385
|
+
}, m);
|
|
3386
|
+
};
|
|
3387
|
+
/** Hold on to a tab of this browser until it is gone, however it goes. */
|
|
3388
|
+
const watch = (tab, at) => {
|
|
3389
|
+
if (!locks) return;
|
|
3390
|
+
locks.request(tabLock(tab), { mode: "shared" }, () => {
|
|
3391
|
+
if (at === run && isHub && localTabs.delete(tab)) announceTabs(null);
|
|
3392
|
+
}).catch(() => {});
|
|
3393
|
+
};
|
|
3394
|
+
const becomeHub = (self) => {
|
|
3395
|
+
isHub = true;
|
|
3396
|
+
browsers.clear();
|
|
3397
|
+
status = "connecting";
|
|
3398
|
+
link = opts.link({
|
|
3399
|
+
self: () => me ? {
|
|
3400
|
+
user: me.user,
|
|
3401
|
+
peer: me.peer
|
|
3402
|
+
} : null,
|
|
3403
|
+
onPeer: (browser, isUp) => {
|
|
3404
|
+
if (isUp) {
|
|
3405
|
+
browsers.set(browser, /* @__PURE__ */ new Set());
|
|
3406
|
+
announceTabs([browser]);
|
|
3407
|
+
} else if (!browsers.delete(browser)) return;
|
|
3408
|
+
publish();
|
|
3409
|
+
},
|
|
3410
|
+
onMessage: (browser, data) => {
|
|
3411
|
+
const tabs = browsers.get(browser);
|
|
3412
|
+
if (!tabs || data === null || typeof data !== "object") return;
|
|
3413
|
+
const d = data;
|
|
3414
|
+
if (d.h === "tabs") {
|
|
3415
|
+
const list = tabList(d.tabs);
|
|
3416
|
+
if (!list) return;
|
|
3417
|
+
browsers.set(browser, new Set(list));
|
|
3418
|
+
publish();
|
|
3419
|
+
} else if (d.h === "m") {
|
|
3420
|
+
const to = d.to === null ? null : tabList(d.to);
|
|
3421
|
+
if (!isTabId(d.from) || !tabs.has(d.from) || d.to !== null && to === null) return;
|
|
3422
|
+
deliver(d.from, to, d.m);
|
|
3423
|
+
}
|
|
3424
|
+
},
|
|
3425
|
+
onStatus: (next) => {
|
|
3426
|
+
status = next;
|
|
3427
|
+
publish();
|
|
3428
|
+
}
|
|
3429
|
+
});
|
|
3430
|
+
post({
|
|
3431
|
+
k: "hub",
|
|
3432
|
+
tab: self.peer
|
|
3433
|
+
});
|
|
3434
|
+
publish();
|
|
3435
|
+
};
|
|
3436
|
+
const hubLock = () => `sp00ky-channels:${opts.scope(me?.user ?? "")}`;
|
|
3437
|
+
const tabLock = (tab) => `${hubLock()}:tab:${tab}`;
|
|
3438
|
+
const onBus = (data) => {
|
|
3439
|
+
const self = me;
|
|
3440
|
+
if (!self || data === null || typeof data !== "object") return;
|
|
3441
|
+
const msg = data;
|
|
3442
|
+
switch (msg.k) {
|
|
3443
|
+
case "here":
|
|
3444
|
+
if (!isHub || !isTabId(msg.tab) || msg.tab === self.peer) return;
|
|
3445
|
+
if (!localTabs.has(msg.tab)) {
|
|
3446
|
+
localTabs.add(msg.tab);
|
|
3447
|
+
watch(msg.tab, run);
|
|
3448
|
+
announceTabs(null);
|
|
3449
|
+
}
|
|
3450
|
+
publish();
|
|
3451
|
+
return;
|
|
3452
|
+
case "bye":
|
|
3453
|
+
if (isHub && localTabs.delete(msg.tab)) announceTabs(null);
|
|
3454
|
+
return;
|
|
3455
|
+
case "hub":
|
|
3456
|
+
if (!isHub) post({
|
|
3457
|
+
k: "here",
|
|
3458
|
+
tab: self.peer
|
|
3459
|
+
});
|
|
3460
|
+
return;
|
|
3461
|
+
case "remote":
|
|
3462
|
+
if (isHub || msg.browsers === null || typeof msg.browsers !== "object") return;
|
|
3463
|
+
browsers.clear();
|
|
3464
|
+
for (const [b, tabs] of Object.entries(msg.browsers)) {
|
|
3465
|
+
const list = tabList(tabs);
|
|
3466
|
+
if (list) browsers.set(b, new Set(list));
|
|
3467
|
+
}
|
|
3468
|
+
status = msg.status;
|
|
3469
|
+
apply();
|
|
3470
|
+
return;
|
|
3471
|
+
case "out":
|
|
3472
|
+
if (isHub && localTabs.has(msg.tab) && tabList(msg.to)) hubSend(msg.tab, msg.to, msg.m);
|
|
3473
|
+
return;
|
|
3474
|
+
case "in":
|
|
3475
|
+
if (!isHub && (msg.to === null || Array.isArray(msg.to) && msg.to.includes(self.peer))) hooks.onMessage({
|
|
3476
|
+
user: self.user,
|
|
3477
|
+
peer: msg.from
|
|
3478
|
+
}, msg.m);
|
|
3479
|
+
return;
|
|
3480
|
+
}
|
|
3481
|
+
};
|
|
3482
|
+
const flush = () => {
|
|
3483
|
+
flushing = false;
|
|
3484
|
+
const self = me;
|
|
3485
|
+
const batch = [...pending];
|
|
3486
|
+
pending.clear();
|
|
3487
|
+
if (!self) return;
|
|
3488
|
+
for (const [m, to] of batch) if (isHub) hubSend(self.peer, to, m);
|
|
3489
|
+
else post({
|
|
3490
|
+
k: "out",
|
|
3491
|
+
tab: self.peer,
|
|
3492
|
+
to,
|
|
3493
|
+
m
|
|
3494
|
+
});
|
|
3495
|
+
};
|
|
3496
|
+
const start = (self) => {
|
|
3497
|
+
me = self;
|
|
3498
|
+
const at = ++run;
|
|
3499
|
+
status = "connecting";
|
|
3500
|
+
reported = null;
|
|
3501
|
+
if (!locks || !openBus) {
|
|
3502
|
+
becomeHub(self);
|
|
3503
|
+
return;
|
|
3504
|
+
}
|
|
3505
|
+
bus = openBus(hubLock());
|
|
3506
|
+
bus.onmessage = (event) => onBus(event.data);
|
|
3507
|
+
locks.request(tabLock(self.peer), () => new Promise((resolve) => {
|
|
3508
|
+
if (at !== run) return resolve();
|
|
3509
|
+
releaseTab = resolve;
|
|
3510
|
+
if (!isHub) post({
|
|
3511
|
+
k: "here",
|
|
3512
|
+
tab: self.peer
|
|
3513
|
+
});
|
|
3514
|
+
})).catch(() => {});
|
|
3515
|
+
locks.request(hubLock(), () => new Promise((resolve) => {
|
|
3516
|
+
if (at !== run) return resolve();
|
|
3517
|
+
releaseHub = resolve;
|
|
3518
|
+
becomeHub(self);
|
|
3519
|
+
})).catch(() => {});
|
|
3520
|
+
};
|
|
3521
|
+
const stop = () => {
|
|
3522
|
+
const self = me;
|
|
3523
|
+
if (!self) return;
|
|
3524
|
+
if (!isHub) post({
|
|
3525
|
+
k: "bye",
|
|
3526
|
+
tab: self.peer
|
|
3527
|
+
});
|
|
3528
|
+
run++;
|
|
3529
|
+
link?.close();
|
|
3530
|
+
link = null;
|
|
3531
|
+
isHub = false;
|
|
3532
|
+
releaseHub?.();
|
|
3533
|
+
releaseTab?.();
|
|
3534
|
+
releaseHub = null;
|
|
3535
|
+
releaseTab = null;
|
|
3536
|
+
try {
|
|
3537
|
+
bus?.close();
|
|
3538
|
+
} catch {}
|
|
3539
|
+
bus = null;
|
|
3540
|
+
localTabs.clear();
|
|
3541
|
+
browsers.clear();
|
|
3542
|
+
pending.clear();
|
|
3543
|
+
for (const t of [...up]) hooks.onPeer({
|
|
3544
|
+
user: self.user,
|
|
3545
|
+
peer: t
|
|
3546
|
+
}, false);
|
|
3547
|
+
up.clear();
|
|
3548
|
+
me = null;
|
|
3549
|
+
};
|
|
3550
|
+
return {
|
|
3551
|
+
supported: opts.supported ?? roomSupported(),
|
|
3552
|
+
want(users) {
|
|
3553
|
+
const self = hooks.self();
|
|
3554
|
+
const wanted = self !== null && users.has(self.user);
|
|
3555
|
+
if (me && (!wanted || !self || self.user !== me.user || self.peer !== me.peer)) stop();
|
|
3556
|
+
if (wanted && self && !me) start(self);
|
|
3557
|
+
},
|
|
3558
|
+
send(to, message) {
|
|
3559
|
+
if (!me || to.user !== me.user) return;
|
|
3560
|
+
const list = pending.get(message);
|
|
3561
|
+
if (list) list.push(to.peer);
|
|
3562
|
+
else pending.set(message, [to.peer]);
|
|
3563
|
+
if (flushing) return;
|
|
3564
|
+
flushing = true;
|
|
3565
|
+
Promise.resolve().then(flush);
|
|
3566
|
+
},
|
|
3567
|
+
close() {
|
|
3568
|
+
stop();
|
|
3569
|
+
}
|
|
3570
|
+
};
|
|
3571
|
+
}
|
|
3572
|
+
|
|
2686
3573
|
//#endregion
|
|
2687
3574
|
//#region src/mutation/rows.ts
|
|
2688
3575
|
const PENDING_TABLE = "_00_pending_mutations";
|
|
@@ -3659,8 +4546,8 @@ function trimHistory(history, cap) {
|
|
|
3659
4546
|
|
|
3660
4547
|
//#endregion
|
|
3661
4548
|
//#region src/modules/devtools/index.ts
|
|
3662
|
-
const CORE_VERSION = "1.0.0-beta.
|
|
3663
|
-
const WASM_VERSION = "1.0.0-beta.
|
|
4549
|
+
const CORE_VERSION = "1.0.0-beta.9";
|
|
4550
|
+
const WASM_VERSION = "1.0.0-beta.9";
|
|
3664
4551
|
const SURREAL_VERSION = "3.1.0";
|
|
3665
4552
|
var DevToolsService = class DevToolsService {
|
|
3666
4553
|
version = CORE_VERSION;
|
|
@@ -17619,7 +18506,7 @@ function createTabsCoordinator(config, s, host) {
|
|
|
17619
18506
|
return new TabsCoordinator({
|
|
17620
18507
|
tabId: s.tabId,
|
|
17621
18508
|
fingerprint: computeTabsFingerprint({
|
|
17622
|
-
coreVersion: "1.0.0-beta.
|
|
18509
|
+
coreVersion: "1.0.0-beta.9",
|
|
17623
18510
|
schemaHash: hash53(config.schemaSurql),
|
|
17624
18511
|
endpoint: config.database.endpoint ?? "",
|
|
17625
18512
|
namespace: config.database.namespace,
|
|
@@ -18340,6 +19227,23 @@ var Sp00kyClient = class {
|
|
|
18340
19227
|
});
|
|
18341
19228
|
this.disposers.push(this.webPush.attach());
|
|
18342
19229
|
const channelsConfig = config.channels;
|
|
19230
|
+
const relay = typeof channelsConfig?.relay === "string" ? { url: channelsConfig.relay } : channelsConfig?.relay;
|
|
19231
|
+
const mesh = (hooks) => webrtcTransport(hooks, {
|
|
19232
|
+
signal: surrealSignal(s.remote, s.connectionSupervisor, s.logger),
|
|
19233
|
+
iceServers: channelsConfig?.iceServers,
|
|
19234
|
+
logger: s.logger
|
|
19235
|
+
});
|
|
19236
|
+
const room = relay ? (hooks) => hubTransport(hooks, {
|
|
19237
|
+
scope: (user) => `${config.database.namespace}/${config.database.database}/${user}`,
|
|
19238
|
+
link: (linkHooks) => roomLink(linkHooks, {
|
|
19239
|
+
url: relay.url,
|
|
19240
|
+
direct: relay.direct,
|
|
19241
|
+
token: () => s.remote.getAuthToken(),
|
|
19242
|
+
iceServers: channelsConfig?.iceServers,
|
|
19243
|
+
logger: s.logger
|
|
19244
|
+
}),
|
|
19245
|
+
logger: s.logger
|
|
19246
|
+
}) : null;
|
|
18343
19247
|
this.channels = new ChannelManager(config.schema, {
|
|
18344
19248
|
config: channelsConfig,
|
|
18345
19249
|
logger: s.logger,
|
|
@@ -18355,12 +19259,9 @@ var Sp00kyClient = class {
|
|
|
18355
19259
|
})),
|
|
18356
19260
|
read: (id) => this.runtime.run(readRow(id))
|
|
18357
19261
|
},
|
|
18358
|
-
transport: channelsConfig?.transport ?? (
|
|
18359
|
-
signal: surrealSignal(s.remote, s.connectionSupervisor, s.logger),
|
|
18360
|
-
iceServers: channelsConfig?.iceServers,
|
|
18361
|
-
logger: s.logger
|
|
18362
|
-
}))
|
|
19262
|
+
transport: channelsConfig?.transport ?? splitTransport(room, mesh)
|
|
18363
19263
|
});
|
|
19264
|
+
if (this.channels.sharing && !relay && !channelsConfig?.transport) s.logger.warn({ Category: "sp00ky-client::channel" }, "channels.share is set without channels.relay: nothing reaches your other devices until a relay address is given");
|
|
18364
19265
|
if (this.channels.enabled) this.disposers.push(s.auth.subscribe((userId) => this.channels.setUser(userId)));
|
|
18365
19266
|
this.devTools = new DevToolsService(s.local, s.remote, s.logger, config.schema, s.auth, {
|
|
18366
19267
|
getActiveQueries: () => [...this.runtime.state.queries.values()].map(toQueryState),
|
|
@@ -18580,7 +19481,8 @@ var Sp00kyClient = class {
|
|
|
18580
19481
|
}
|
|
18581
19482
|
async subscribe(queryHash, callback, options) {
|
|
18582
19483
|
if (!this.channels.enabled) return this.runtime.subscribe(queryHash, callback, options);
|
|
18583
|
-
const
|
|
19484
|
+
const def = this.channels.sharing ? this.runtime.state.queries.get(queryHash)?.def : void 0;
|
|
19485
|
+
const tap = this.channels.tap(callback, def ? this.channels.interestOf(def.plan, def.params) : null);
|
|
18584
19486
|
const stop = this.runtime.subscribe(queryHash, tap.feed, options);
|
|
18585
19487
|
return () => {
|
|
18586
19488
|
stop();
|
|
@@ -18613,6 +19515,19 @@ var Sp00kyClient = class {
|
|
|
18613
19515
|
delete: (table, id) => this.writeDelete(table, id, scoped(table))
|
|
18614
19516
|
};
|
|
18615
19517
|
}
|
|
19518
|
+
/**
|
|
19519
|
+
* The link to this user's other devices (`channels.share`): `connected`
|
|
19520
|
+
* with the user's id in `peers` while at least one other tab of theirs, in
|
|
19521
|
+
* another browser, is in the room. `idle` when nothing is shared or nobody
|
|
19522
|
+
* is signed in.
|
|
19523
|
+
*/
|
|
19524
|
+
shareState() {
|
|
19525
|
+
return this.channels.ownState();
|
|
19526
|
+
}
|
|
19527
|
+
/** Called at once with `shareState()`, then on every change. */
|
|
19528
|
+
subscribeShareState(callback) {
|
|
19529
|
+
return this.channels.subscribeOwn(callback);
|
|
19530
|
+
}
|
|
18616
19531
|
channelScopes(queries) {
|
|
18617
19532
|
return (Array.isArray(queries) ? queries : [queries]).map((q) => {
|
|
18618
19533
|
const final = "build" in q && typeof q.build === "function" ? q.build() : q;
|
|
@@ -18833,4 +19748,4 @@ var Sp00kyClient = class {
|
|
|
18833
19748
|
};
|
|
18834
19749
|
|
|
18835
19750
|
//#endregion
|
|
18836
|
-
export { AppReleaseHandle, AppReleaseModule, AuthEventTypes, AuthService, BLURHASH_IMAGE_EXTENSIONS, BucketHandle, CURSOR_COLORS, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, FeatureFlagHandle, FeatureFlagModule, IMPERSONATION_ACCESS, ImpersonationTimers, LocalOpTimeoutError, MATERIALIZATION_SAMPLE_WINDOW, ORIGIN_TOKEN_KEY, PUSH_ENDPOINT_KEY, PUSH_PAYLOAD_VERSION, REFUSAL_RECHECK_MIN_MS, SESSION_POLL_MS, SIGN_OUT_HOOK_TIMEOUT_MS, Sp00kyClient, WebPushError, WebPushModule, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, decodeTokenClaims, detectWebPushSupport, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, impersonationFromToken, isBlurhashValid, isImagePath, isPushPayload, matchesWhere, renewDelayMs, sameImpersonation, semverGt, surrealSignal, textToHtml, unusedArgs, webrtcTransport };
|
|
19751
|
+
export { AppReleaseHandle, AppReleaseModule, AuthEventTypes, AuthService, BLURHASH_IMAGE_EXTENSIONS, BucketHandle, CURSOR_COLORS, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, FeatureFlagHandle, FeatureFlagModule, IMPERSONATION_ACCESS, ImpersonationTimers, LocalOpTimeoutError, MATERIALIZATION_SAMPLE_WINDOW, ORIGIN_TOKEN_KEY, PUSH_ENDPOINT_KEY, PUSH_PAYLOAD_VERSION, REFUSAL_RECHECK_MIN_MS, SESSION_POLL_MS, SIGN_OUT_HOOK_TIMEOUT_MS, Sp00kyClient, WebPushError, WebPushModule, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, decodeTokenClaims, detectWebPushSupport, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, hubTransport, impersonationFromToken, isBlurhashValid, isImagePath, isPushPayload, matchesWhere, renewDelayMs, roomLink, sameImpersonation, semverGt, splitTransport, surrealSignal, textToHtml, unusedArgs, webrtcTransport };
|