@dovetail-ts/supabase 0.0.0-stage → 1.0.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,28 @@
1
+ # @dovetail-ts/supabase
2
+
3
+ ## 1.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 21b3dbf: Publish through OIDC trusted publishing only, with the Ember Workbench release kit. Each version from this release on has npm provenance.
8
+ - Updated dependencies [21b3dbf]
9
+ - @dovetail-ts/protocol@1.0.1
10
+
11
+ ## 1.0.0
12
+
13
+ ### Major Changes
14
+
15
+ - 480744b: First release of Dovetail: real-time and offline sync for Ember.
16
+
17
+ - `@dovetail-ts/core`: the connection life cycle, live store subscriptions, the optimistic ledger with rebase and rollback, the offline write queue in IndexedDB with a leader tab and dead letters, `DocSession` and `PresenceRoom`.
18
+ - `@dovetail-ts/warp-drive`: the store feed into WarpDrive.
19
+ - `@dovetail-ts/crdt`, `crdt-yjs`, `crdt-loro` and `crdt-automerge`: one `DocEngine` interface with three engines.
20
+ - `@dovetail-ts/tiptap`: co-editing in Tiptap 3 with carets, per-user undo, versions and comment threads.
21
+ - `@dovetail-ts/ember`, `notifications` and `inspector`: presence and status components, the inbox, toasts and activity feeds, and a dev panel.
22
+ - `@dovetail-ts/server`, the transports (`transport-ws`, `transport-sse`, `transport-cable`) and `conformance`: a Node server and one wire protocol that the Rails gems also pass.
23
+ - Adapters for Hocuspocus, Liveblocks, PartyKit and Supabase, and integrations for Switchyard, Millwork, Benchdog and Lattice. The Neon adapter is not in 1.0: it waits for a stable Neon Realtime client (1.1).
24
+
25
+ ### Patch Changes
26
+
27
+ - Updated dependencies [480744b]
28
+ - @dovetail-ts/protocol@1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joe Gaudet
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # @dovetail-ts/supabase
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Supabase Realtime adapter: the store feed and presence.
4
+
5
+ Part of [Dovetail](https://joegaudet.com/dovetail/). Not released yet.
6
+
7
+ | Kind | Supported | How |
8
+ | ----------- | --------- | ------------------------------------------------------ |
9
+ | `StoreFeed` | Yes | `supabaseStoreFeed`: Postgres changes, as JSON:API ops |
10
+ | `DocSync` | No | |
11
+ | `Presence` | Yes | `supabasePresence`: channel presence, as the awareness |
12
+
13
+ `kinds` has the same list: `['StoreFeed', 'Presence']`.
14
+
15
+ ## Store feed
16
+
17
+ ```ts
18
+ import { createClient } from '@supabase/supabase-js'
19
+ import { supabaseStoreFeed } from '@dovetail-ts/supabase'
20
+
21
+ const supabase = createClient(url, anonKey)
22
+ const stop = supabaseStoreFeed(
23
+ supabase,
24
+ { apply: op => ledger.receive(op) },
25
+ {
26
+ tables: [
27
+ { table: 'todos', type: 'todo', filter: 'list_id=eq.42' },
28
+ {
29
+ table: 'lists',
30
+ type: 'list',
31
+ resource: row => ({ attributes: { name: row['name'] ?? null } }),
32
+ },
33
+ ],
34
+ },
35
+ )
36
+ ```
37
+
38
+ `supabaseStoreFeed(client, sink, { tables, channel? })` listens to the Postgres changes of each
39
+ table on one channel. An insert or an update upserts the resource of the row. A delete removes
40
+ the record. The function gives back a function that stops it and removes the channel.
41
+
42
+ A `TableMapper` tells how a row becomes a resource:
43
+
44
+ | Field | Default | What it does |
45
+ | ---------- | ------------------------------------ | ---------------------------------- |
46
+ | `schema` | `public` | The schema of the table. |
47
+ | `table` | (required) | The table. |
48
+ | `filter` | none | A Postgres changes filter. |
49
+ | `type` | the table name | The resource type. |
50
+ | `id` | `String(row.id)` | The resource id of a row. |
51
+ | `resource` | each column but `id` in `attributes` | The other members of the resource. |
52
+
53
+ - Without `REPLICA IDENTITY FULL`, the old row of a delete has only the primary key. The
54
+ delete uses the same `id` function, so let `id` read only the primary key columns.
55
+ - A row without an id gives no op. Each op goes through `parseMessage`, so an op that is not
56
+ valid JSON:API does not get to the store.
57
+ - Supabase does not replay the changes that a client did not get while it was offline. Load
58
+ the records over HTTP when a client joins the channel, and when it joins again.
59
+ - The feed does not write. Write with the Supabase client, and the feed brings the change
60
+ back.
61
+ - `sink` is a `StoreSink` (`apply(op)`), as the one of `@dovetail-ts/core`. With the optimistic
62
+ ledger, give `{ apply: op => ledger.receive(op) }`, so the feed does not overwrite the
63
+ pending local changes (ADR 0011).
64
+ - Turn on the Realtime publication of each table in Supabase. Row level security applies to
65
+ the changes that a client gets.
66
+
67
+ ## Presence
68
+
69
+ ```ts
70
+ import { supabasePresence } from '@dovetail-ts/supabase'
71
+
72
+ const stop = supabasePresence(supabase, handle.awareness, { channel: 'room:notes-42' })
73
+ ```
74
+
75
+ `supabasePresence(client, awareness, { channel })` uses the client id of the awareness as the
76
+ presence key. After the channel joins, it tracks the local awareness state, and it tracks each
77
+ local change again. It applies the presence of each other key to the awareness, without
78
+ `presence_ref`. A key can have one state for each tab: the adapter uses the last one. It works
79
+ with the awareness of each engine. The function gives back a function that stops it, removes
80
+ the remote states and removes the channel.
81
+
82
+ ## Tests
83
+
84
+ The unit tests use a fake client with the parts of a `SupabaseClient` that the adapter uses
85
+ (`SupabaseLike`). The payloads have the types of `@supabase/supabase-js`. A compile-time check
86
+ makes sure that a real `SupabaseClient` has these parts. The live test uses presence only, and
87
+ runs only when `SUPABASE_URL` and `SUPABASE_ANON_KEY` name a Supabase project.
@@ -0,0 +1,92 @@
1
+ import type { RealtimePostgresChangesPayload, RealtimePresenceState } from '@supabase/supabase-js';
2
+ import type { JsonObject, JsonValue, Resource, StoreOp } from '@dovetail-ts/protocol';
3
+ /** The name of this package. */
4
+ export declare const PACKAGE_NAME = "@dovetail-ts/supabase";
5
+ /** A kind of adapter (ADR 0003). */
6
+ export type AdapterKind = 'StoreFeed' | 'DocSync' | 'Presence';
7
+ /** The kinds that this adapter supports. */
8
+ export declare const kinds: readonly ["StoreFeed", "Presence"];
9
+ /**
10
+ * Where the store feed puts each op. The `StoreSink` of `@dovetail-ts/core` is one. With the
11
+ * optimistic ledger, give `{ apply: op => ledger.receive(op) }` (ADR 0011).
12
+ */
13
+ export interface StoreSink {
14
+ apply(op: StoreOp): void;
15
+ }
16
+ /** The awareness of a document, as `DocAwareness` of `@dovetail-ts/crdt` has it. */
17
+ export interface AwarenessLike {
18
+ readonly clientId: string;
19
+ getLocalState(): JsonObject | null;
20
+ applyRemoteState(clientId: string, state: JsonObject | null): void;
21
+ onChange(listener: (change: {
22
+ local: boolean;
23
+ }) => void): () => void;
24
+ }
25
+ /** The options of a channel that the adapter gives. */
26
+ export interface ChannelOptions {
27
+ config: {
28
+ presence?: {
29
+ key?: string;
30
+ };
31
+ };
32
+ }
33
+ /** The parts of a Supabase `RealtimeChannel` that the adapter uses. */
34
+ export interface RealtimeChannelLike {
35
+ on(type: 'postgres_changes', filter: {
36
+ event: '*';
37
+ schema: string;
38
+ table: string;
39
+ filter?: string;
40
+ }, callback: (payload: RealtimePostgresChangesPayload<JsonObject>) => void): RealtimeChannelLike;
41
+ on(type: 'presence', filter: {
42
+ event: 'sync';
43
+ }, callback: () => void): RealtimeChannelLike;
44
+ subscribe(callback?: (status: string) => void): RealtimeChannelLike;
45
+ track(payload: JsonObject): Promise<unknown>;
46
+ untrack(): Promise<unknown>;
47
+ presenceState(): RealtimePresenceState<JsonObject>;
48
+ }
49
+ /** The parts of a `SupabaseClient` that the adapter uses. */
50
+ export interface SupabaseLike {
51
+ channel(name: string, options?: ChannelOptions): RealtimeChannelLike;
52
+ removeChannel(channel: RealtimeChannelLike): Promise<unknown>;
53
+ }
54
+ /** A row of a table. The old row of an update or a delete can have some columns only. */
55
+ export type Row = {
56
+ [column: string]: JsonValue | undefined;
57
+ };
58
+ /** How the rows of one table become resources. */
59
+ export interface TableMapper {
60
+ /** The default is `public`. */
61
+ schema?: string;
62
+ table: string;
63
+ /** A Postgres changes filter, as `list_id=eq.42`. */
64
+ filter?: string;
65
+ /** The resource type. The default is the table name. */
66
+ type?: string;
67
+ /**
68
+ * The resource id of a row. The default is `String(row.id)`. A delete gives only the primary
69
+ * key without `REPLICA IDENTITY FULL`, so use only the primary key columns here.
70
+ */
71
+ id?: (row: Row) => string;
72
+ /** The other members of the resource. The default puts each column but `id` in `attributes`. */
73
+ resource?: (row: JsonObject) => Omit<Resource, 'type' | 'id'>;
74
+ }
75
+ /**
76
+ * Puts the Postgres changes of the tables in the sink, on one channel: an insert or an update
77
+ * upserts the resource of the row, and a delete removes the record. Each op goes through
78
+ * `parseMessage`, so an op that is not valid JSON:API does not get to the store. Returns a
79
+ * function that stops it.
80
+ */
81
+ export declare function supabaseStoreFeed(client: SupabaseLike, sink: StoreSink, options: {
82
+ tables: TableMapper[];
83
+ channel?: string;
84
+ }): () => void;
85
+ /**
86
+ * Puts the local awareness state in the presence of a Supabase channel, and the presence of
87
+ * the others in the awareness. The presence key is the client id of the awareness. Returns a
88
+ * function that stops it.
89
+ */
90
+ export declare function supabasePresence(client: SupabaseLike, awareness: AwarenessLike, options: {
91
+ channel: string;
92
+ }): () => void;
package/dist/index.js ADDED
@@ -0,0 +1,79 @@
1
+ import { parseMessage } from '@dovetail-ts/protocol';
2
+
3
+ // src/index.ts
4
+ var PACKAGE_NAME = "@dovetail-ts/supabase";
5
+ var kinds = ["StoreFeed", "Presence"];
6
+ function supabaseStoreFeed(client, sink, options) {
7
+ const channel = client.channel(options.channel ?? "dovetail:store-feed");
8
+ for (const mapper of options.tables) {
9
+ const { schema = "public", table, filter } = mapper;
10
+ channel.on("postgres_changes", { event: "*", schema, table, filter }, (payload) => {
11
+ const op = toOp(mapper, payload);
12
+ const checked = op && parseMessage({ type: "feed", room: "supabase", cursor: "0", ops: [op] });
13
+ if (checked?.ok && checked.message.type === "feed") sink.apply(checked.message.ops[0]);
14
+ });
15
+ }
16
+ channel.subscribe();
17
+ return () => void client.removeChannel(channel);
18
+ }
19
+ function toOp(mapper, payload) {
20
+ const type = mapper.type ?? mapper.table;
21
+ const idOf = mapper.id ?? defaultId;
22
+ if (payload.eventType === "DELETE") {
23
+ const id2 = idOf(payload.old);
24
+ return id2 ? { op: "delete", ref: { type, id: id2 } } : null;
25
+ }
26
+ const row = payload.new;
27
+ const id = idOf(row);
28
+ if (!id) return null;
29
+ const rest = (mapper.resource ?? defaultResource)(row);
30
+ return { op: "upsert", document: { data: { ...rest, type, id } } };
31
+ }
32
+ function defaultId(row) {
33
+ const id = row["id"];
34
+ return typeof id === "string" || typeof id === "number" && Number.isFinite(id) ? String(id) : "";
35
+ }
36
+ function defaultResource(row) {
37
+ const { id: _id, ...attributes } = row;
38
+ return { attributes };
39
+ }
40
+ function supabasePresence(client, awareness, options) {
41
+ const self = awareness.clientId;
42
+ const channel = client.channel(options.channel, { config: { presence: { key: self } } });
43
+ let joined = false;
44
+ let remote = /* @__PURE__ */ new Set();
45
+ const send = () => {
46
+ if (!joined) return;
47
+ const state = awareness.getLocalState();
48
+ void (state ? channel.track(state) : channel.untrack());
49
+ };
50
+ const stopLocal = awareness.onChange((change) => {
51
+ if (change.local) send();
52
+ });
53
+ channel.on("presence", { event: "sync" }, () => {
54
+ const now = /* @__PURE__ */ new Set();
55
+ for (const [key, metas] of Object.entries(channel.presenceState())) {
56
+ const last = metas.at(-1);
57
+ if (key === self || !last) continue;
58
+ const { presence_ref: _ref, ...state } = last;
59
+ now.add(key);
60
+ awareness.applyRemoteState(key, state);
61
+ }
62
+ for (const key of remote) if (!now.has(key)) awareness.applyRemoteState(key, null);
63
+ remote = now;
64
+ });
65
+ channel.subscribe((status) => {
66
+ joined = status === "SUBSCRIBED";
67
+ send();
68
+ });
69
+ return () => {
70
+ stopLocal();
71
+ for (const key of remote) awareness.applyRemoteState(key, null);
72
+ remote = /* @__PURE__ */ new Set();
73
+ void client.removeChannel(channel);
74
+ };
75
+ }
76
+
77
+ export { PACKAGE_NAME, kinds, supabasePresence, supabaseStoreFeed };
78
+ //# sourceMappingURL=index.js.map
79
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":["id"],"mappings":";;;AAQO,IAAM,YAAA,GAAe;AAMrB,IAAM,KAAA,GAAQ,CAAC,WAAA,EAAa,UAAU;AAsEtC,SAAS,iBAAA,CACd,MAAA,EACA,IAAA,EACA,OAAA,EACY;AACZ,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,OAAA,CAAQ,WAAW,qBAAqB,CAAA;AACvE,EAAA,KAAA,MAAW,MAAA,IAAU,QAAQ,MAAA,EAAQ;AACnC,IAAA,MAAM,EAAE,MAAA,GAAS,QAAA,EAAU,KAAA,EAAO,QAAO,GAAI,MAAA;AAC7C,IAAA,OAAA,CAAQ,EAAA,CAAG,oBAAoB,EAAE,KAAA,EAAO,KAAK,MAAA,EAAQ,KAAA,EAAO,MAAA,EAAO,EAAG,CAAA,OAA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AAA,OAAA,CAAQ,GAAG,UAAA,EAAY,EAAE,KAAA,EAAO,MAAA,IAAU,MAAM;AAC9C,IAAA,MAAM,GAAA,uBAAU,GAAA,EAAY;AAC5B,IAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,OAAA,CAAQ,aAAA,EAAe,CAAA,EAAG;AAElE,MAAA,MAAM,IAAA,GAAO,KAAA,CAAM,EAAA,CAAG,EAAE,CAAA;AACxB,MAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,CAAC,IAAA,EAAM;AAC3B,MAAA,MAAM,EAAE,YAAA,EAAc,IAAA,EAAM,GAAG,OAAM,GAAI,IAAA;AACzC,MAAA,GAAA,CAAI,IAAI,GAAG,CAAA;AACX,MAAA,SAAA,CAAU,gBAAA,CAAiB,KAAK,KAAK,CAAA;AAAA,IACvC;AACA,IAAA,KAAA,MAAW,GAAA,IAAO,MAAA,EAAQ,IAAI,CAAC,GAAA,CAAI,GAAA,CAAI,GAAG,CAAA,EAAG,SAAA,CAAU,gBAAA,CAAiB,GAAA,EAAK,IAAI,CAAA;AACjF,IAAA,MAAA,GAAS,GAAA;AAAA,EACX,CAAC,CAAA;AACD,EAAA,OAAA,CAAQ,UAAU,CAAA,MAAA,KAAU;AAC1B,IAAA,MAAA,GAAS,MAAA,KAAW,YAAA;AACpB,IAAA,IAAA,EAAK;AAAA,EACP,CAAC,CAAA;AAED,EAAA,OAAO,MAAM;AACX,IAAA,SAAA,EAAU;AACV,IAAA,KAAA,MAAW,GAAA,IAAO,MAAA,EAAQ,SAAA,CAAU,gBAAA,CAAiB,KAAK,IAAI,CAAA;AAC9D,IAAA,MAAA,uBAAa,GAAA,EAAI;AACjB,IAAA,KAAK,MAAA,CAAO,cAAc,OAAO,CAAA;AAAA,EACnC,CAAA;AACF","file":"index.js","sourcesContent":["// The Supabase Realtime adapter (ADR 0003, ADR 0017).\n// - Store feed: the Postgres changes of some tables, as JSON:API upserts and deletes.\n// - Presence: the presence of a channel, as the awareness of a document.\nimport type { RealtimePostgresChangesPayload, RealtimePresenceState } from '@supabase/supabase-js'\nimport { parseMessage } from '@dovetail-ts/protocol'\nimport type { JsonObject, JsonValue, Resource, StoreOp } from '@dovetail-ts/protocol'\n\n/** The name of this package. */\nexport const PACKAGE_NAME = '@dovetail-ts/supabase'\n\n/** A kind of adapter (ADR 0003). */\nexport type AdapterKind = 'StoreFeed' | 'DocSync' | 'Presence'\n\n/** The kinds that this adapter supports. */\nexport const kinds = ['StoreFeed', 'Presence'] as const satisfies readonly AdapterKind[]\n\n/**\n * Where the store feed puts each op. The `StoreSink` of `@dovetail-ts/core` is one. With the\n * optimistic ledger, give `{ apply: op => ledger.receive(op) }` (ADR 0011).\n */\nexport interface StoreSink {\n apply(op: StoreOp): void\n}\n\n/** The awareness of a document, as `DocAwareness` of `@dovetail-ts/crdt` has it. */\nexport interface AwarenessLike {\n readonly clientId: string\n getLocalState(): JsonObject | null\n applyRemoteState(clientId: string, state: JsonObject | null): void\n onChange(listener: (change: { local: boolean }) => void): () => void\n}\n\n/** The options of a channel that the adapter gives. */\nexport interface ChannelOptions {\n config: { presence?: { key?: string } }\n}\n\n/** The parts of a Supabase `RealtimeChannel` that the adapter uses. */\nexport interface RealtimeChannelLike {\n on(\n type: 'postgres_changes',\n filter: { event: '*'; schema: string; table: string; filter?: string },\n callback: (payload: RealtimePostgresChangesPayload<JsonObject>) => void,\n ): RealtimeChannelLike\n on(type: 'presence', filter: { event: 'sync' }, callback: () => void): RealtimeChannelLike\n subscribe(callback?: (status: string) => void): RealtimeChannelLike\n track(payload: JsonObject): Promise<unknown>\n untrack(): Promise<unknown>\n presenceState(): RealtimePresenceState<JsonObject>\n}\n\n/** The parts of a `SupabaseClient` that the adapter uses. */\nexport interface SupabaseLike {\n channel(name: string, options?: ChannelOptions): RealtimeChannelLike\n removeChannel(channel: RealtimeChannelLike): Promise<unknown>\n}\n\n/** A row of a table. The old row of an update or a delete can have some columns only. */\nexport type Row = { [column: string]: JsonValue | undefined }\n\n/** How the rows of one table become resources. */\nexport interface TableMapper {\n /** The default is `public`. */\n schema?: string\n table: string\n /** A Postgres changes filter, as `list_id=eq.42`. */\n filter?: string\n /** The resource type. The default is the table name. */\n type?: string\n /**\n * The resource id of a row. The default is `String(row.id)`. A delete gives only the primary\n * key without `REPLICA IDENTITY FULL`, so use only the primary key columns here.\n */\n id?: (row: Row) => string\n /** The other members of the resource. The default puts each column but `id` in `attributes`. */\n resource?: (row: JsonObject) => Omit<Resource, 'type' | 'id'>\n}\n\n/**\n * Puts the Postgres changes of the tables in the sink, on one channel: an insert or an update\n * upserts the resource of the row, and a delete removes the record. Each op goes through\n * `parseMessage`, so an op that is not valid JSON:API does not get to the store. Returns a\n * function that stops it.\n */\nexport function supabaseStoreFeed(\n client: SupabaseLike,\n sink: StoreSink,\n options: { tables: TableMapper[]; channel?: string },\n): () => void {\n const channel = client.channel(options.channel ?? 'dovetail:store-feed')\n for (const mapper of options.tables) {\n const { schema = 'public', table, filter } = mapper\n channel.on('postgres_changes', { event: '*', schema, table, filter }, payload => {\n const op = toOp(mapper, payload)\n // The cursor is not used: the check is only for the op.\n const checked = op && parseMessage({ type: 'feed', room: 'supabase', cursor: '0', ops: [op] })\n if (checked?.ok && checked.message.type === 'feed') sink.apply(checked.message.ops[0]!)\n })\n }\n channel.subscribe()\n return () => void client.removeChannel(channel)\n}\n\nfunction toOp(\n mapper: TableMapper,\n payload: RealtimePostgresChangesPayload<JsonObject>,\n): StoreOp | null {\n const type = mapper.type ?? mapper.table\n const idOf = mapper.id ?? defaultId\n if (payload.eventType === 'DELETE') {\n const id = idOf(payload.old)\n return id ? { op: 'delete', ref: { type, id } } : null\n }\n const row = payload.new\n const id = idOf(row)\n if (!id) return null\n const rest = (mapper.resource ?? defaultResource)(row)\n return { op: 'upsert', document: { data: { ...rest, type, id } } }\n}\n\nfunction defaultId(row: Row): string {\n const id = row['id']\n return typeof id === 'string' || (typeof id === 'number' && Number.isFinite(id)) ? String(id) : ''\n}\n\nfunction defaultResource(row: JsonObject): Omit<Resource, 'type' | 'id'> {\n const { id: _id, ...attributes } = row\n return { attributes }\n}\n\n/**\n * Puts the local awareness state in the presence of a Supabase channel, and the presence of\n * the others in the awareness. The presence key is the client id of the awareness. Returns a\n * function that stops it.\n */\nexport function supabasePresence(\n client: SupabaseLike,\n awareness: AwarenessLike,\n options: { channel: string },\n): () => void {\n const self = awareness.clientId\n const channel = client.channel(options.channel, { config: { presence: { key: self } } })\n let joined = false\n let remote = new Set<string>()\n\n const send = () => {\n if (!joined) return\n const state = awareness.getLocalState()\n void (state ? channel.track(state) : channel.untrack())\n }\n const stopLocal = awareness.onChange(change => {\n if (change.local) send()\n })\n channel.on('presence', { event: 'sync' }, () => {\n const now = new Set<string>()\n for (const [key, metas] of Object.entries(channel.presenceState())) {\n // One key can have more than one meta (one for each tab). The last one is the newest.\n const last = metas.at(-1)\n if (key === self || !last) continue\n const { presence_ref: _ref, ...state } = last\n now.add(key)\n awareness.applyRemoteState(key, state)\n }\n for (const key of remote) if (!now.has(key)) awareness.applyRemoteState(key, null)\n remote = now\n })\n channel.subscribe(status => {\n joined = status === 'SUBSCRIBED'\n send()\n })\n\n return () => {\n stopLocal()\n for (const key of remote) awareness.applyRemoteState(key, null)\n remote = new Set()\n void client.removeChannel(channel)\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@dovetail-ts/supabase",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.1",
4
+ "description": "The Supabase Realtime adapter: the store feed and presence.",
5
+ "license": "MIT",
6
+ "author": "Joe Gaudet <joe@joegaudet.com>",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/joegaudet/dovetail.git",
10
+ "directory": "packages/supabase"
11
+ },
12
+ "homepage": "https://joegaudet.com/dovetail/",
13
+ "bugs": "https://github.com/joegaudet/dovetail/issues",
14
+ "keywords": [
15
+ "realtime",
16
+ "offline",
17
+ "sync",
18
+ "crdt"
19
+ ],
20
+ "type": "module",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "CHANGELOG.md",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "sideEffects": false,
36
+ "dependencies": {
37
+ "@dovetail-ts/protocol": "1.0.1",
38
+ "@supabase/supabase-js": "^2.120.0"
39
+ },
40
+ "devDependencies": {
41
+ "@dovetail-ts/crdt": "1.0.1",
42
+ "@dovetail-ts/crdt-yjs": "1.0.1",
43
+ "tsup": "^8.5.1"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "engines": {
49
+ "node": ">=22.12.0"
50
+ },
51
+ "scripts": {
52
+ "build": "tsc --build --force && tsup"
53
+ }
6
54
  }