@ankhorage/db-supabase 0.0.0-stage → 2.0.0
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 +346 -0
- package/LICENSE +21 -0
- package/README.md +23 -2
- package/dist/adapter.d.ts +3 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/adapter.js +170 -0
- package/dist/adapter.js.map +1 -0
- package/dist/admin.d.ts +4 -0
- package/dist/admin.d.ts.map +1 -0
- package/dist/admin.js +145 -0
- package/dist/admin.js.map +1 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +37 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/query.d.ts +4 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +94 -0
- package/dist/query.js.map +1 -0
- package/dist/realtime.d.ts +10 -0
- package/dist/realtime.d.ts.map +1 -0
- package/dist/realtime.js +74 -0
- package/dist/realtime.js.map +1 -0
- package/dist/types.d.ts +53 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/validation.d.ts +7 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +43 -0
- package/dist/validation.js.map +1 -0
- package/package.json +79 -4
- package/src/adapter.test.ts +171 -0
- package/src/adapter.ts +237 -0
- package/src/admin.test.ts +106 -0
- package/src/admin.ts +204 -0
- package/src/errors.ts +66 -0
- package/src/index.ts +27 -0
- package/src/metadata/repository.json +42 -0
- package/src/query.ts +122 -0
- package/src/realtime.test.ts +174 -0
- package/src/realtime.ts +127 -0
- package/src/types.ts +69 -0
- package/src/validation.ts +57 -0
package/src/admin.ts
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DbAdminAdapter,
|
|
3
|
+
DbAdminResult,
|
|
4
|
+
DbCollectionDefinition,
|
|
5
|
+
DbCollectionReference,
|
|
6
|
+
DbFieldDefinition,
|
|
7
|
+
} from '@ankhorage/contracts/db';
|
|
8
|
+
|
|
9
|
+
import type { SupabaseDbAdminAdapterOptions } from './types.js';
|
|
10
|
+
import { quoteIdentifier, validateKey, validateUrl } from './validation.js';
|
|
11
|
+
|
|
12
|
+
interface NormalizedAdminConfig {
|
|
13
|
+
readonly url: string;
|
|
14
|
+
readonly schema: string;
|
|
15
|
+
readonly serviceRoleKey?: string;
|
|
16
|
+
readonly execute: boolean;
|
|
17
|
+
readonly executeSql?: SupabaseDbAdminAdapterOptions['executeSql'];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createSupabaseDbAdminAdapter(
|
|
21
|
+
options: SupabaseDbAdminAdapterOptions,
|
|
22
|
+
): DbAdminAdapter {
|
|
23
|
+
const config = normalizeAdminConfig(options);
|
|
24
|
+
|
|
25
|
+
return {
|
|
26
|
+
capabilities: {
|
|
27
|
+
schemaGeneration: true,
|
|
28
|
+
directExecution: config.execute && config.executeSql !== undefined,
|
|
29
|
+
},
|
|
30
|
+
|
|
31
|
+
async createCollection(input: DbCollectionDefinition): Promise<DbAdminResult> {
|
|
32
|
+
const generated = generateCreateCollectionSql(input, config.schema);
|
|
33
|
+
|
|
34
|
+
if (!generated.ok || !config.execute) {
|
|
35
|
+
return generated;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return executeSql(config, generated.sql ?? '');
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
async deleteCollection(input: DbCollectionReference): Promise<DbAdminResult> {
|
|
42
|
+
const generated = generateDeleteCollectionSql(input, config.schema);
|
|
43
|
+
|
|
44
|
+
if (!generated.ok || !config.execute) {
|
|
45
|
+
return generated;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return executeSql(config, generated.sql ?? '');
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
generateCreateCollectionSql(input: DbCollectionDefinition): DbAdminResult {
|
|
52
|
+
return generateCreateCollectionSql(input, config.schema);
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
generateDeleteCollectionSql(input: DbCollectionReference): DbAdminResult {
|
|
56
|
+
return generateDeleteCollectionSql(input, config.schema);
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function normalizeAdminConfig(options: SupabaseDbAdminAdapterOptions): NormalizedAdminConfig {
|
|
62
|
+
const normalized: NormalizedAdminConfig = {
|
|
63
|
+
url: validateUrl(options.url),
|
|
64
|
+
schema: options.schema ?? 'public',
|
|
65
|
+
execute: options.execute ?? false,
|
|
66
|
+
executeSql: options.executeSql,
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
if (options.serviceRoleKey === undefined) {
|
|
70
|
+
return normalized;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
...normalized,
|
|
75
|
+
serviceRoleKey: validateKey(options.serviceRoleKey, 'Supabase service role key'),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function generateCreateCollectionSql(
|
|
80
|
+
input: DbCollectionDefinition,
|
|
81
|
+
defaultSchema: string,
|
|
82
|
+
): DbAdminResult {
|
|
83
|
+
try {
|
|
84
|
+
const schema = quoteIdentifier(input.schema ?? defaultSchema);
|
|
85
|
+
const table = quoteIdentifier(input.name);
|
|
86
|
+
const primaryKey = input.primaryKey ?? 'id';
|
|
87
|
+
const fields = input.fields.map((field) => formatField(field));
|
|
88
|
+
const primaryKeyFieldExists = input.fields.some((field) => field.name === primaryKey);
|
|
89
|
+
const columns = primaryKeyFieldExists
|
|
90
|
+
? fields
|
|
91
|
+
: [`${quoteIdentifier(primaryKey)} uuid primary key default gen_random_uuid()`, ...fields];
|
|
92
|
+
|
|
93
|
+
if (columns.length === 0) {
|
|
94
|
+
return createAdminError('validation_error', 'A collection requires at least one field.');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
ok: true,
|
|
99
|
+
sql: `create schema if not exists ${schema};\ncreate table if not exists ${schema}.${table} (\n ${columns.join(',\n ')}\n);`,
|
|
100
|
+
executed: false,
|
|
101
|
+
};
|
|
102
|
+
} catch (error) {
|
|
103
|
+
return createAdminError('validation_error', 'Invalid collection definition.', error);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function generateDeleteCollectionSql(
|
|
108
|
+
input: DbCollectionReference,
|
|
109
|
+
defaultSchema: string,
|
|
110
|
+
): DbAdminResult {
|
|
111
|
+
try {
|
|
112
|
+
const schema = quoteIdentifier(input.schema ?? defaultSchema);
|
|
113
|
+
const table = quoteIdentifier(input.name);
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
ok: true,
|
|
117
|
+
sql: `drop table if exists ${schema}.${table};`,
|
|
118
|
+
executed: false,
|
|
119
|
+
};
|
|
120
|
+
} catch (error) {
|
|
121
|
+
return createAdminError('validation_error', 'Invalid collection name.', error);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function executeSql(config: NormalizedAdminConfig, sql: string): Promise<DbAdminResult> {
|
|
126
|
+
if (config.executeSql === undefined) {
|
|
127
|
+
return createAdminError(
|
|
128
|
+
'execution_not_configured',
|
|
129
|
+
'Schema execution requires an executeSql callback.',
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (config.serviceRoleKey === undefined) {
|
|
134
|
+
return createAdminError(
|
|
135
|
+
'missing_service_role_key',
|
|
136
|
+
'Schema execution requires a service role key in privileged environments only.',
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const result = await config.executeSql(sql);
|
|
141
|
+
|
|
142
|
+
if (!result.ok) {
|
|
143
|
+
return {
|
|
144
|
+
ok: false,
|
|
145
|
+
error: result.error,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
ok: true,
|
|
151
|
+
sql,
|
|
152
|
+
executed: true,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function formatField(field: DbFieldDefinition): string {
|
|
157
|
+
const name = quoteIdentifier(field.name);
|
|
158
|
+
const type = mapFieldType(field.type);
|
|
159
|
+
const required = field.required === true ? ' not null' : '';
|
|
160
|
+
const unique = field.unique === true ? ' unique' : '';
|
|
161
|
+
const defaultValue = formatDefaultValue(field.defaultValue);
|
|
162
|
+
|
|
163
|
+
return `${name} ${type}${required}${unique}${defaultValue}`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function mapFieldType(type: DbFieldDefinition['type']): string {
|
|
167
|
+
switch (type) {
|
|
168
|
+
case 'text':
|
|
169
|
+
return 'text';
|
|
170
|
+
case 'number':
|
|
171
|
+
return 'double precision';
|
|
172
|
+
case 'boolean':
|
|
173
|
+
return 'boolean';
|
|
174
|
+
case 'datetime':
|
|
175
|
+
return 'timestamptz';
|
|
176
|
+
case 'json':
|
|
177
|
+
return 'jsonb';
|
|
178
|
+
case 'uuid':
|
|
179
|
+
return 'uuid';
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function formatDefaultValue(value: DbFieldDefinition['defaultValue']): string {
|
|
184
|
+
if (value === undefined) {
|
|
185
|
+
return '';
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (value === null) {
|
|
189
|
+
return ' default null';
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (typeof value === 'string') {
|
|
193
|
+
return ` default '${value.replaceAll("'", "''")}'`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return ` default ${String(value)}`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function createAdminError(code: string, message: string, cause?: unknown): DbAdminResult {
|
|
200
|
+
return {
|
|
201
|
+
ok: false,
|
|
202
|
+
error: cause === undefined ? { code, message } : { code, message, cause },
|
|
203
|
+
};
|
|
204
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { DbAdapterError } from '@ankhorage/contracts/db';
|
|
2
|
+
|
|
3
|
+
export function createDbError(code: string, message: string, cause?: unknown): DbAdapterError {
|
|
4
|
+
return cause === undefined ? { code, message } : { code, message, cause };
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function mapNetworkError(error: unknown): DbAdapterError {
|
|
8
|
+
return createDbError('network_error', 'Supabase Database request failed.', error);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function mapHttpError(status: number, body: unknown): DbAdapterError {
|
|
12
|
+
const providerMessage = readProviderMessage(body);
|
|
13
|
+
|
|
14
|
+
if (status === 401 || status === 403) {
|
|
15
|
+
return createDbError(
|
|
16
|
+
'permission_denied',
|
|
17
|
+
providerMessage ?? 'Supabase Database denied the request.',
|
|
18
|
+
body,
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (status === 404) {
|
|
23
|
+
return createDbError(
|
|
24
|
+
'missing_table',
|
|
25
|
+
providerMessage ?? 'Supabase Database resource was not found.',
|
|
26
|
+
body,
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (status >= 400 && status < 500) {
|
|
31
|
+
return createDbError(
|
|
32
|
+
'invalid_query',
|
|
33
|
+
providerMessage ?? 'Supabase Database rejected the query.',
|
|
34
|
+
body,
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return createDbError(
|
|
39
|
+
'provider_error',
|
|
40
|
+
providerMessage ?? 'Supabase Database returned an unexpected error.',
|
|
41
|
+
body,
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function readProviderMessage(body: unknown): string | undefined {
|
|
46
|
+
if (!isRecord(body)) {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const { message } = body;
|
|
51
|
+
const { error } = body;
|
|
52
|
+
|
|
53
|
+
if (typeof message === 'string' && message.trim().length > 0) {
|
|
54
|
+
return message;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (typeof error === 'string' && error.trim().length > 0) {
|
|
58
|
+
return error;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
65
|
+
return typeof value === 'object' && value !== null;
|
|
66
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export { createSupabaseDbAdapter } from './adapter.js';
|
|
2
|
+
export { createSupabaseDbAdminAdapter } from './admin.js';
|
|
3
|
+
export { normalizeRealtimeEvent } from './realtime.js';
|
|
4
|
+
export type {
|
|
5
|
+
DbAdminSqlExecutionResult,
|
|
6
|
+
SupabaseDbAdapter,
|
|
7
|
+
SupabaseDbAdapterOptions,
|
|
8
|
+
SupabaseDbAdminAdapter,
|
|
9
|
+
SupabaseDbAdminAdapterOptions,
|
|
10
|
+
SupabaseRealtimeClient,
|
|
11
|
+
SupabaseRealtimePayload,
|
|
12
|
+
} from './types.js';
|
|
13
|
+
export type {
|
|
14
|
+
DbAdminAdapter,
|
|
15
|
+
DbAdminResult,
|
|
16
|
+
DbChangeEvent,
|
|
17
|
+
DbChangeKind,
|
|
18
|
+
DbChangeListener,
|
|
19
|
+
DbCollectionDefinition,
|
|
20
|
+
DbCollectionReference,
|
|
21
|
+
DbCollectionSubscriptionInput,
|
|
22
|
+
DbFieldDefinition,
|
|
23
|
+
DbFieldType,
|
|
24
|
+
DbRealtimeAdapter,
|
|
25
|
+
DbRecordSubscriptionInput,
|
|
26
|
+
DbSubscription,
|
|
27
|
+
} from '@ankhorage/contracts/db';
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"kind": "adapter",
|
|
4
|
+
"title": "Ankhorage Supabase Database Adapter",
|
|
5
|
+
"summary": "Adapts Supabase Postgres to portable Ankhorage database contracts with CRUD, administration, query, and optional realtime behavior.",
|
|
6
|
+
"purpose": "Provide a Supabase-backed database boundary without coupling consumers to provider-specific query and realtime details.",
|
|
7
|
+
"domain": "Supabase database adapter",
|
|
8
|
+
"responsibilities": [
|
|
9
|
+
"Implement portable CRUD and query operations through a Supabase client.",
|
|
10
|
+
"Expose schema administration behavior supported by the adapter.",
|
|
11
|
+
"Provide optional realtime subscriptions and validate adapter inputs.",
|
|
12
|
+
"Map provider failures into the adapter's public error boundary."
|
|
13
|
+
],
|
|
14
|
+
"boundaries": [
|
|
15
|
+
"Does not define portable database contracts.",
|
|
16
|
+
"Does not provision Supabase projects, databases, credentials, or network policy.",
|
|
17
|
+
"Does not replace provider-specific migrations or application domain repositories."
|
|
18
|
+
],
|
|
19
|
+
"audience": [
|
|
20
|
+
"Applications selecting Supabase as the backing database provider.",
|
|
21
|
+
"Composition code requiring portable database operations over a Supabase client."
|
|
22
|
+
],
|
|
23
|
+
"useCases": [
|
|
24
|
+
"Perform CRUD and filtered queries through the adapter.",
|
|
25
|
+
"Manage supported schema operations against Supabase Postgres.",
|
|
26
|
+
"Subscribe to supported realtime database changes."
|
|
27
|
+
],
|
|
28
|
+
"architecture": {
|
|
29
|
+
"role": "Outbound provider adapter translating portable database contracts to Supabase APIs.",
|
|
30
|
+
"invariants": [
|
|
31
|
+
"Portable operations remain independent of the concrete Supabase client type at consumer boundaries.",
|
|
32
|
+
"Provider inputs are validated before requests are executed.",
|
|
33
|
+
"Realtime behavior remains optional and separately owned."
|
|
34
|
+
]
|
|
35
|
+
},
|
|
36
|
+
"constraints": {
|
|
37
|
+
"limitations": [
|
|
38
|
+
"Requires a compatible Supabase JavaScript client and reachable project.",
|
|
39
|
+
"Administration and realtime capabilities are constrained by Supabase permissions and features."
|
|
40
|
+
]
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/query.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { DbFilter, DbPage, DbSelectInput, DbSort } from '@ankhorage/contracts/db';
|
|
2
|
+
|
|
3
|
+
import { validateIdentifier } from './validation.js';
|
|
4
|
+
|
|
5
|
+
export function buildSelectUrl(baseUrl: string, input: DbSelectInput): URL {
|
|
6
|
+
const table = validateIdentifier(input.table, 'Table');
|
|
7
|
+
const url = new URL(`${baseUrl}/rest/v1/${table}`);
|
|
8
|
+
|
|
9
|
+
url.searchParams.set('select', formatColumns(input.columns));
|
|
10
|
+
|
|
11
|
+
applyFilters(url, input.filters ?? []);
|
|
12
|
+
applySort(url, input.sort ?? []);
|
|
13
|
+
applyPage(url, input.page);
|
|
14
|
+
|
|
15
|
+
return url;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function buildMutationUrl(
|
|
19
|
+
baseUrl: string,
|
|
20
|
+
tableValue: string,
|
|
21
|
+
filters: readonly DbFilter[],
|
|
22
|
+
): URL {
|
|
23
|
+
const table = validateIdentifier(tableValue, 'Table');
|
|
24
|
+
const url = new URL(`${baseUrl}/rest/v1/${table}`);
|
|
25
|
+
|
|
26
|
+
applyFilters(url, filters);
|
|
27
|
+
|
|
28
|
+
return url;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function applyFilters(url: URL, filters: readonly DbFilter[]): void {
|
|
32
|
+
for (const filter of filters) {
|
|
33
|
+
const field = validateIdentifier(filter.field, 'Filter field');
|
|
34
|
+
url.searchParams.append(field, formatFilter(filter));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function applySort(url: URL, sort: readonly DbSort[]): void {
|
|
39
|
+
if (sort.length === 0) {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const order = sort
|
|
44
|
+
.map((item) => {
|
|
45
|
+
const field = validateIdentifier(item.field, 'Sort field');
|
|
46
|
+
return `${field}.${item.direction ?? 'asc'}`;
|
|
47
|
+
})
|
|
48
|
+
.join(',');
|
|
49
|
+
|
|
50
|
+
url.searchParams.set('order', order);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function applyPage(url: URL, page: DbPage | undefined): void {
|
|
54
|
+
if (page?.limit !== undefined) {
|
|
55
|
+
url.searchParams.set('limit', String(page.limit));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (page?.offset !== undefined) {
|
|
59
|
+
url.searchParams.set('offset', String(page.offset));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function formatColumns(columns: readonly string[] | undefined): string {
|
|
64
|
+
if (columns === undefined || columns.length === 0) {
|
|
65
|
+
return '*';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return columns.map((column) => validateIdentifier(column, 'Column')).join(',');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function formatFilter(filter: DbFilter): string {
|
|
72
|
+
switch (filter.operator) {
|
|
73
|
+
case 'eq':
|
|
74
|
+
return `eq.${formatValue(filter.value)}`;
|
|
75
|
+
case 'neq':
|
|
76
|
+
return `neq.${formatValue(filter.value)}`;
|
|
77
|
+
case 'gt':
|
|
78
|
+
return `gt.${formatValue(filter.value)}`;
|
|
79
|
+
case 'gte':
|
|
80
|
+
return `gte.${formatValue(filter.value)}`;
|
|
81
|
+
case 'lt':
|
|
82
|
+
return `lt.${formatValue(filter.value)}`;
|
|
83
|
+
case 'lte':
|
|
84
|
+
return `lte.${formatValue(filter.value)}`;
|
|
85
|
+
case 'in':
|
|
86
|
+
return `in.(${formatInValue(filter.value)})`;
|
|
87
|
+
case 'contains':
|
|
88
|
+
return `cs.${formatValue(filter.value)}`;
|
|
89
|
+
case 'startsWith':
|
|
90
|
+
return `like.${formatLikeValue(filter.value)}*`;
|
|
91
|
+
case 'endsWith':
|
|
92
|
+
return `like.*${formatLikeValue(filter.value)}`;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function formatInValue(value: unknown): string {
|
|
97
|
+
if (!Array.isArray(value)) {
|
|
98
|
+
return formatValue(value);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return value.map((item) => formatValue(item)).join(',');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function formatLikeValue(value: unknown): string {
|
|
105
|
+
return String(value).replaceAll('*', '\\*');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function formatValue(value: unknown): string {
|
|
109
|
+
if (value === null) {
|
|
110
|
+
return 'null';
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (typeof value === 'string') {
|
|
114
|
+
return value;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (typeof value === 'number' || typeof value === 'boolean') {
|
|
118
|
+
return String(value);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return JSON.stringify(value);
|
|
122
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test';
|
|
2
|
+
|
|
3
|
+
import { createSupabaseDbAdapter } from './adapter.js';
|
|
4
|
+
import { normalizeRealtimeEvent } from './realtime.js';
|
|
5
|
+
import type {
|
|
6
|
+
SupabaseRealtimeChannel,
|
|
7
|
+
SupabaseRealtimeClient,
|
|
8
|
+
SupabaseRealtimePayload,
|
|
9
|
+
} from './types.js';
|
|
10
|
+
|
|
11
|
+
interface PostRecord {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly title: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
test('normalizes insert payloads', () => {
|
|
17
|
+
const event = normalizeRealtimeEvent<PostRecord>(
|
|
18
|
+
{
|
|
19
|
+
eventType: 'INSERT',
|
|
20
|
+
schema: 'public',
|
|
21
|
+
table: 'posts',
|
|
22
|
+
commit_timestamp: '2026-05-12T10:00:00Z',
|
|
23
|
+
new: { id: 'post-1', title: 'Hello' },
|
|
24
|
+
},
|
|
25
|
+
'fallback',
|
|
26
|
+
'public',
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
expect(event).toEqual({
|
|
30
|
+
table: 'posts',
|
|
31
|
+
schema: 'public',
|
|
32
|
+
kind: 'insert',
|
|
33
|
+
record: { id: 'post-1', title: 'Hello' },
|
|
34
|
+
committedAt: '2026-05-12T10:00:00Z',
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('normalizes update payloads with previous record', () => {
|
|
39
|
+
const event = normalizeRealtimeEvent<PostRecord>(
|
|
40
|
+
{
|
|
41
|
+
eventType: 'UPDATE',
|
|
42
|
+
new: { id: 'post-1', title: 'Updated' },
|
|
43
|
+
old: { id: 'post-1', title: 'Old' },
|
|
44
|
+
},
|
|
45
|
+
'posts',
|
|
46
|
+
'public',
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
expect(event).toEqual({
|
|
50
|
+
table: 'posts',
|
|
51
|
+
schema: 'public',
|
|
52
|
+
kind: 'update',
|
|
53
|
+
record: { id: 'post-1', title: 'Updated' },
|
|
54
|
+
previousRecord: { id: 'post-1', title: 'Old' },
|
|
55
|
+
committedAt: undefined,
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('normalizes delete payloads to a null current record', () => {
|
|
60
|
+
const event = normalizeRealtimeEvent<PostRecord>(
|
|
61
|
+
{
|
|
62
|
+
eventType: 'DELETE',
|
|
63
|
+
old: { id: 'post-1', title: 'Deleted' },
|
|
64
|
+
},
|
|
65
|
+
'posts',
|
|
66
|
+
'public',
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
expect(event).toEqual({
|
|
70
|
+
table: 'posts',
|
|
71
|
+
schema: 'public',
|
|
72
|
+
kind: 'delete',
|
|
73
|
+
record: null,
|
|
74
|
+
previousRecord: { id: 'post-1', title: 'Deleted' },
|
|
75
|
+
committedAt: undefined,
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('ignores unknown realtime events', () => {
|
|
80
|
+
const event = normalizeRealtimeEvent<PostRecord>({ eventType: 'TRUNCATE' }, 'posts', 'public');
|
|
81
|
+
|
|
82
|
+
expect(event).toBeNull();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('subscribes and cleans up collection channels', async () => {
|
|
86
|
+
const client = createFakeRealtimeClient();
|
|
87
|
+
const adapter = createSupabaseDbAdapter({
|
|
88
|
+
url: 'https://example.supabase.co',
|
|
89
|
+
anonKey: 'anon',
|
|
90
|
+
realtime: true,
|
|
91
|
+
realtimeClient: client,
|
|
92
|
+
fetch: () => Promise.resolve(new Response('[]')),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
const received: unknown[] = [];
|
|
96
|
+
const subscription = adapter.realtime?.subscribeToCollection<PostRecord>(
|
|
97
|
+
{ table: 'posts' },
|
|
98
|
+
(event) => {
|
|
99
|
+
received.push(event);
|
|
100
|
+
},
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
client.emit({
|
|
104
|
+
eventType: 'INSERT',
|
|
105
|
+
table: 'posts',
|
|
106
|
+
schema: 'public',
|
|
107
|
+
new: { id: '1', title: 'A' },
|
|
108
|
+
});
|
|
109
|
+
await subscription?.unsubscribe();
|
|
110
|
+
|
|
111
|
+
expect(received).toHaveLength(1);
|
|
112
|
+
expect(client.removedChannels).toBe(1);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('subscribes to a specific record using a Supabase filter', () => {
|
|
116
|
+
const client = createFakeRealtimeClient();
|
|
117
|
+
const adapter = createSupabaseDbAdapter({
|
|
118
|
+
url: 'https://example.supabase.co',
|
|
119
|
+
anonKey: 'anon',
|
|
120
|
+
realtime: true,
|
|
121
|
+
realtimeClient: client,
|
|
122
|
+
fetch: () => Promise.resolve(new Response('[]')),
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
adapter.realtime?.subscribeToRecord<PostRecord>(
|
|
126
|
+
{ table: 'posts', id: 'post-1' },
|
|
127
|
+
() => undefined,
|
|
128
|
+
);
|
|
129
|
+
|
|
130
|
+
expect(client.lastFilter?.filter).toBe('id=eq.post-1');
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
function createFakeRealtimeClient(): SupabaseRealtimeClient & {
|
|
134
|
+
emit(payload: SupabaseRealtimePayload): void;
|
|
135
|
+
readonly removedChannels: number;
|
|
136
|
+
readonly lastFilter: { readonly filter?: string } | undefined;
|
|
137
|
+
} {
|
|
138
|
+
let callback: ((payload: SupabaseRealtimePayload) => void) | undefined;
|
|
139
|
+
let removedChannels = 0;
|
|
140
|
+
let lastFilter: { readonly filter?: string } | undefined;
|
|
141
|
+
|
|
142
|
+
const channel: SupabaseRealtimeChannel = {
|
|
143
|
+
on(_type, filter, nextCallback) {
|
|
144
|
+
lastFilter = { filter: filter.filter };
|
|
145
|
+
callback = nextCallback;
|
|
146
|
+
return channel;
|
|
147
|
+
},
|
|
148
|
+
subscribe() {
|
|
149
|
+
return channel;
|
|
150
|
+
},
|
|
151
|
+
unsubscribe() {
|
|
152
|
+
return Promise.resolve<'ok'>('ok');
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
channel() {
|
|
158
|
+
return channel;
|
|
159
|
+
},
|
|
160
|
+
removeChannel() {
|
|
161
|
+
removedChannels += 1;
|
|
162
|
+
return Promise.resolve<'ok'>('ok');
|
|
163
|
+
},
|
|
164
|
+
emit(payload: SupabaseRealtimePayload) {
|
|
165
|
+
callback?.(payload);
|
|
166
|
+
},
|
|
167
|
+
get removedChannels() {
|
|
168
|
+
return removedChannels;
|
|
169
|
+
},
|
|
170
|
+
get lastFilter() {
|
|
171
|
+
return lastFilter;
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|