@koolbase/core 10.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/README.md +19 -0
- package/dist/cjs/analytics.d.ts +24 -0
- package/dist/cjs/analytics.js +110 -0
- package/dist/cjs/auth-errors.d.ts +117 -0
- package/dist/cjs/auth-errors.js +250 -0
- package/dist/cjs/auth.d.ts +213 -0
- package/dist/cjs/auth.js +813 -0
- package/dist/cjs/cache-store.d.ts +50 -0
- package/dist/cjs/cache-store.js +194 -0
- package/dist/cjs/conflict.d.ts +80 -0
- package/dist/cjs/conflict.js +84 -0
- package/dist/cjs/database-errors.d.ts +101 -0
- package/dist/cjs/database-errors.js +200 -0
- package/dist/cjs/database.d.ts +298 -0
- package/dist/cjs/database.js +852 -0
- package/dist/cjs/device-id.d.ts +1 -0
- package/dist/cjs/device-id.js +57 -0
- package/dist/cjs/device-metadata.d.ts +36 -0
- package/dist/cjs/device-metadata.js +94 -0
- package/dist/cjs/errors.d.ts +64 -0
- package/dist/cjs/errors.js +85 -0
- package/dist/cjs/flags.d.ts +15 -0
- package/dist/cjs/flags.js +76 -0
- package/dist/cjs/function-errors.d.ts +51 -0
- package/dist/cjs/function-errors.js +103 -0
- package/dist/cjs/functions.d.ts +15 -0
- package/dist/cjs/functions.js +83 -0
- package/dist/cjs/index.d.ts +22 -0
- package/dist/cjs/index.js +56 -0
- package/dist/cjs/messaging.d.ts +13 -0
- package/dist/cjs/messaging.js +36 -0
- package/dist/cjs/offline-state.d.ts +97 -0
- package/dist/cjs/offline-state.js +198 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/pending-write.d.ts +47 -0
- package/dist/cjs/pending-write.js +22 -0
- package/dist/cjs/platform.d.ts +51 -0
- package/dist/cjs/platform.js +41 -0
- package/dist/cjs/realtime.d.ts +44 -0
- package/dist/cjs/realtime.js +195 -0
- package/dist/cjs/record.d.ts +2 -0
- package/dist/cjs/record.js +23 -0
- package/dist/cjs/shared.d.ts +9 -0
- package/dist/cjs/shared.js +43 -0
- package/dist/cjs/storage-errors.d.ts +163 -0
- package/dist/cjs/storage-errors.js +253 -0
- package/dist/cjs/storage.d.ts +198 -0
- package/dist/cjs/storage.js +451 -0
- package/dist/cjs/sync-engine.d.ts +30 -0
- package/dist/cjs/sync-engine.js +286 -0
- package/dist/cjs/types.d.ts +487 -0
- package/dist/cjs/types.js +40 -0
- package/dist/esm/analytics.d.ts +24 -0
- package/dist/esm/analytics.js +106 -0
- package/dist/esm/auth-errors.d.ts +117 -0
- package/dist/esm/auth-errors.js +222 -0
- package/dist/esm/auth.d.ts +213 -0
- package/dist/esm/auth.js +809 -0
- package/dist/esm/cache-store.d.ts +50 -0
- package/dist/esm/cache-store.js +179 -0
- package/dist/esm/conflict.d.ts +80 -0
- package/dist/esm/conflict.js +80 -0
- package/dist/esm/database-errors.d.ts +101 -0
- package/dist/esm/database-errors.js +189 -0
- package/dist/esm/database.d.ts +298 -0
- package/dist/esm/database.js +848 -0
- package/dist/esm/device-id.d.ts +1 -0
- package/dist/esm/device-id.js +54 -0
- package/dist/esm/device-metadata.d.ts +36 -0
- package/dist/esm/device-metadata.js +90 -0
- package/dist/esm/errors.d.ts +64 -0
- package/dist/esm/errors.js +79 -0
- package/dist/esm/flags.d.ts +15 -0
- package/dist/esm/flags.js +72 -0
- package/dist/esm/function-errors.d.ts +51 -0
- package/dist/esm/function-errors.js +93 -0
- package/dist/esm/functions.d.ts +15 -0
- package/dist/esm/functions.js +79 -0
- package/dist/esm/index.d.ts +22 -0
- package/dist/esm/index.js +25 -0
- package/dist/esm/messaging.d.ts +13 -0
- package/dist/esm/messaging.js +32 -0
- package/dist/esm/offline-state.d.ts +97 -0
- package/dist/esm/offline-state.js +189 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/pending-write.d.ts +47 -0
- package/dist/esm/pending-write.js +19 -0
- package/dist/esm/platform.d.ts +51 -0
- package/dist/esm/platform.js +36 -0
- package/dist/esm/realtime.d.ts +44 -0
- package/dist/esm/realtime.js +191 -0
- package/dist/esm/record.d.ts +2 -0
- package/dist/esm/record.js +20 -0
- package/dist/esm/shared.d.ts +9 -0
- package/dist/esm/shared.js +39 -0
- package/dist/esm/storage-errors.d.ts +163 -0
- package/dist/esm/storage-errors.js +239 -0
- package/dist/esm/storage.d.ts +198 -0
- package/dist/esm/storage.js +447 -0
- package/dist/esm/sync-engine.d.ts +30 -0
- package/dist/esm/sync-engine.js +282 -0
- package/dist/esm/types.d.ts +487 -0
- package/dist/esm/types.js +37 -0
- package/package.json +45 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.memoryPlatform = memoryPlatform;
|
|
4
|
+
exports.setPlatform = setPlatform;
|
|
5
|
+
exports.getPlatform = getPlatform;
|
|
6
|
+
// Shared across module instances; see shared.ts for why.
|
|
7
|
+
const shared_js_1 = require("./shared.js");
|
|
8
|
+
/**
|
|
9
|
+
* An adapter that persists nothing beyond the process and reports the
|
|
10
|
+
* network as always up. The default until a platform sets its own — which
|
|
11
|
+
* makes tests run without a module mapper, and makes forgetting to call
|
|
12
|
+
* setPlatform an obvious failure (nothing survives a restart) rather than a
|
|
13
|
+
* crash.
|
|
14
|
+
*/
|
|
15
|
+
function memoryPlatform() {
|
|
16
|
+
const store = new Map();
|
|
17
|
+
return {
|
|
18
|
+
storage: {
|
|
19
|
+
getItem: async (k) => store.get(k) ?? null,
|
|
20
|
+
setItem: async (k, v) => { store.set(k, v); },
|
|
21
|
+
removeItem: async (k) => { store.delete(k); },
|
|
22
|
+
getAllKeys: async () => Array.from(store.keys()),
|
|
23
|
+
},
|
|
24
|
+
network: {
|
|
25
|
+
onChange: () => () => { },
|
|
26
|
+
},
|
|
27
|
+
lifecycle: {
|
|
28
|
+
onBackground: () => () => { },
|
|
29
|
+
},
|
|
30
|
+
info: { os: 'memory', version: '' },
|
|
31
|
+
authStorage: () => null,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Install the host platform. Called once by the platform package's initialize. */
|
|
35
|
+
function setPlatform(adapter) {
|
|
36
|
+
(0, shared_js_1.setShared)('platform', adapter);
|
|
37
|
+
}
|
|
38
|
+
/** The installed platform. Always returns something; see memoryPlatform. */
|
|
39
|
+
function getPlatform() {
|
|
40
|
+
return (0, shared_js_1.shared)('platform', memoryPlatform);
|
|
41
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { KoolbaseConfig, RealtimeCallback } from './types.js';
|
|
2
|
+
type TokenProvider = () => Promise<string | null>;
|
|
3
|
+
export declare class KoolbaseRealtime {
|
|
4
|
+
private config;
|
|
5
|
+
private getToken;
|
|
6
|
+
private ws;
|
|
7
|
+
private projectId;
|
|
8
|
+
private listeners;
|
|
9
|
+
private reconnectAttempts;
|
|
10
|
+
private reconnectTimer;
|
|
11
|
+
private connecting;
|
|
12
|
+
/**
|
|
13
|
+
* Identifies whose cache a seen record belongs in.
|
|
14
|
+
*
|
|
15
|
+
* The record cache is keyed by user, so without this a watched record would
|
|
16
|
+
* be filed under the wrong key — or under 'anonymous', which is worse than
|
|
17
|
+
* not caching at all: a baseline stored where it will never be read.
|
|
18
|
+
*/
|
|
19
|
+
private getUserId?;
|
|
20
|
+
constructor(config: KoolbaseConfig, getToken: TokenProvider, getUserId?: () => string | null);
|
|
21
|
+
/** Files a record seen over the socket, if we know whose it is. */
|
|
22
|
+
private cacheSeenRecord;
|
|
23
|
+
private forgetSeenRecord;
|
|
24
|
+
subscribe(collection: string, callback: RealtimeCallback): () => void;
|
|
25
|
+
private connect;
|
|
26
|
+
private sendSubscribe;
|
|
27
|
+
private sendUnsubscribe;
|
|
28
|
+
/**
|
|
29
|
+
* Reconnects with backoff, rather than every three seconds forever.
|
|
30
|
+
*
|
|
31
|
+
* A fixed interval is fine while a connection is merely interrupted and
|
|
32
|
+
* costly when it is not: a device with no network, a wrong URL, or a session
|
|
33
|
+
* the server will not accept retried indefinitely, draining battery and data
|
|
34
|
+
* the user cannot see or stop.
|
|
35
|
+
*
|
|
36
|
+
* Doubling from three seconds to a minute keeps a brief interruption
|
|
37
|
+
* recovering quickly while a lasting one settles into an interval that costs
|
|
38
|
+
* almost nothing. The counter resets when a connection opens, so a flaky link
|
|
39
|
+
* does not accumulate delay.
|
|
40
|
+
*/
|
|
41
|
+
private scheduleReconnect;
|
|
42
|
+
disconnect(): void;
|
|
43
|
+
}
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.KoolbaseRealtime = void 0;
|
|
4
|
+
const cache_store_js_1 = require("./cache-store.js");
|
|
5
|
+
const record_js_1 = require("./record.js");
|
|
6
|
+
const EVENT_TYPE_MAP = {
|
|
7
|
+
'db.record.created': 'created',
|
|
8
|
+
'db.record.updated': 'updated',
|
|
9
|
+
'db.record.deleted': 'deleted',
|
|
10
|
+
};
|
|
11
|
+
function projectIdFromToken(token) {
|
|
12
|
+
try {
|
|
13
|
+
const part = token.split('.')[1];
|
|
14
|
+
if (!part)
|
|
15
|
+
return null;
|
|
16
|
+
const b64 = part.replace(/-/g, '+').replace(/_/g, '/');
|
|
17
|
+
const g = globalThis;
|
|
18
|
+
let json;
|
|
19
|
+
if (typeof g.atob === 'function') {
|
|
20
|
+
const bin = g.atob(b64);
|
|
21
|
+
json = decodeURIComponent(bin.split('').map((c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0')).join(''));
|
|
22
|
+
}
|
|
23
|
+
else if (g.Buffer) {
|
|
24
|
+
json = g.Buffer.from(b64, 'base64').toString('utf8');
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
return JSON.parse(json).project_id ?? null;
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
class KoolbaseRealtime {
|
|
36
|
+
constructor(config, getToken, getUserId) {
|
|
37
|
+
this.ws = null;
|
|
38
|
+
this.projectId = null;
|
|
39
|
+
this.listeners = new Map();
|
|
40
|
+
this.reconnectAttempts = 0;
|
|
41
|
+
this.reconnectTimer = null;
|
|
42
|
+
this.connecting = false;
|
|
43
|
+
this.config = config;
|
|
44
|
+
this.getToken = getToken;
|
|
45
|
+
this.getUserId = getUserId;
|
|
46
|
+
}
|
|
47
|
+
/** Files a record seen over the socket, if we know whose it is. */
|
|
48
|
+
async cacheSeenRecord(collection, record) {
|
|
49
|
+
const userId = this.getUserId?.();
|
|
50
|
+
if (!userId)
|
|
51
|
+
return;
|
|
52
|
+
await (0, cache_store_js_1.cacheRecord)(userId, collection, record.id, record.data, record.revision);
|
|
53
|
+
}
|
|
54
|
+
async forgetSeenRecord(recordId) {
|
|
55
|
+
const userId = this.getUserId?.();
|
|
56
|
+
if (!userId)
|
|
57
|
+
return;
|
|
58
|
+
await (0, cache_store_js_1.removeCachedRecord)(userId, recordId);
|
|
59
|
+
}
|
|
60
|
+
subscribe(collection, callback) {
|
|
61
|
+
if (!this.listeners.has(collection))
|
|
62
|
+
this.listeners.set(collection, []);
|
|
63
|
+
this.listeners.get(collection).push(callback);
|
|
64
|
+
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
65
|
+
this.sendSubscribe(collection);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
void this.connect();
|
|
69
|
+
}
|
|
70
|
+
return () => {
|
|
71
|
+
const callbacks = this.listeners.get(collection) ?? [];
|
|
72
|
+
const i = callbacks.indexOf(callback);
|
|
73
|
+
if (i > -1)
|
|
74
|
+
callbacks.splice(i, 1);
|
|
75
|
+
if (callbacks.length === 0) {
|
|
76
|
+
this.listeners.delete(collection);
|
|
77
|
+
this.sendUnsubscribe(collection);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
async connect() {
|
|
82
|
+
if (this.connecting)
|
|
83
|
+
return;
|
|
84
|
+
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING))
|
|
85
|
+
return;
|
|
86
|
+
const token = await this.getToken();
|
|
87
|
+
if (!token) {
|
|
88
|
+
this.scheduleReconnect(); // sign-in may be in flight
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
this.projectId = projectIdFromToken(token);
|
|
92
|
+
this.connecting = true;
|
|
93
|
+
const wsUrl = this.config.baseUrl.replace('https://', 'wss://').replace('http://', 'ws://');
|
|
94
|
+
const ws = new WebSocket(`${wsUrl}/v1/realtime/ws?token=${encodeURIComponent(token)}`);
|
|
95
|
+
this.ws = ws;
|
|
96
|
+
ws.onopen = () => {
|
|
97
|
+
this.connecting = false;
|
|
98
|
+
// A connection that opened is the only proof the endpoint and the
|
|
99
|
+
// credentials are usable, so the backoff resets here rather than on a
|
|
100
|
+
// close — a flaky link should not accumulate delay.
|
|
101
|
+
this.reconnectAttempts = 0;
|
|
102
|
+
for (const collection of this.listeners.keys())
|
|
103
|
+
this.sendSubscribe(collection); // (re)subscribe all
|
|
104
|
+
};
|
|
105
|
+
ws.onmessage = (event) => {
|
|
106
|
+
let raw;
|
|
107
|
+
try {
|
|
108
|
+
raw = JSON.parse(event.data);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const mapped = EVENT_TYPE_MAP[raw?.type];
|
|
114
|
+
if (!mapped)
|
|
115
|
+
return; // ignore subscribed / unsubscribed / error / unknown
|
|
116
|
+
const payload = raw.payload;
|
|
117
|
+
if (!payload || !payload.collection)
|
|
118
|
+
return;
|
|
119
|
+
let msg;
|
|
120
|
+
if (mapped === 'deleted') {
|
|
121
|
+
msg = { type: 'deleted', collection: payload.collection, recordId: payload.record_id };
|
|
122
|
+
// Gone for everyone, so the cached copy is no longer a baseline for
|
|
123
|
+
// anything. An edit composed against it would be refused at replay
|
|
124
|
+
// regardless; removing it makes that a local refusal rather than a
|
|
125
|
+
// round trip.
|
|
126
|
+
void this.forgetSeenRecord(payload.record_id);
|
|
127
|
+
}
|
|
128
|
+
else if (payload.record) {
|
|
129
|
+
const record = (0, record_js_1.recordFromWire)(payload.record);
|
|
130
|
+
msg = { type: mapped, collection: payload.collection, record };
|
|
131
|
+
// A record seen over the socket is as freshly seen as one fetched, and
|
|
132
|
+
// a client watching a collection would otherwise hold a stale baseline
|
|
133
|
+
// while looking at the change. Writes already queued are unaffected:
|
|
134
|
+
// their baseline was copied in when they were made, so this cannot move
|
|
135
|
+
// ground beneath them.
|
|
136
|
+
void this.cacheSeenRecord(payload.collection, record);
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
(this.listeners.get(payload.collection) ?? []).forEach((cb) => cb(msg));
|
|
142
|
+
};
|
|
143
|
+
ws.onclose = () => {
|
|
144
|
+
this.connecting = false;
|
|
145
|
+
if (this.ws === ws)
|
|
146
|
+
this.ws = null;
|
|
147
|
+
this.scheduleReconnect();
|
|
148
|
+
};
|
|
149
|
+
ws.onerror = () => { };
|
|
150
|
+
}
|
|
151
|
+
sendSubscribe(collection) {
|
|
152
|
+
if (!this.projectId || !this.ws || this.ws.readyState !== WebSocket.OPEN)
|
|
153
|
+
return;
|
|
154
|
+
this.ws.send(JSON.stringify({ action: 'subscribe', project_id: this.projectId, collection }));
|
|
155
|
+
}
|
|
156
|
+
sendUnsubscribe(collection) {
|
|
157
|
+
if (!this.projectId || !this.ws || this.ws.readyState !== WebSocket.OPEN)
|
|
158
|
+
return;
|
|
159
|
+
this.ws.send(JSON.stringify({ action: 'unsubscribe', project_id: this.projectId, collection }));
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Reconnects with backoff, rather than every three seconds forever.
|
|
163
|
+
*
|
|
164
|
+
* A fixed interval is fine while a connection is merely interrupted and
|
|
165
|
+
* costly when it is not: a device with no network, a wrong URL, or a session
|
|
166
|
+
* the server will not accept retried indefinitely, draining battery and data
|
|
167
|
+
* the user cannot see or stop.
|
|
168
|
+
*
|
|
169
|
+
* Doubling from three seconds to a minute keeps a brief interruption
|
|
170
|
+
* recovering quickly while a lasting one settles into an interval that costs
|
|
171
|
+
* almost nothing. The counter resets when a connection opens, so a flaky link
|
|
172
|
+
* does not accumulate delay.
|
|
173
|
+
*/
|
|
174
|
+
scheduleReconnect() {
|
|
175
|
+
if (this.listeners.size === 0 || this.reconnectTimer)
|
|
176
|
+
return;
|
|
177
|
+
const delay = Math.min(3000 * Math.pow(2, this.reconnectAttempts), 60000);
|
|
178
|
+
this.reconnectAttempts += 1;
|
|
179
|
+
this.reconnectTimer = setTimeout(() => {
|
|
180
|
+
this.reconnectTimer = null;
|
|
181
|
+
void this.connect();
|
|
182
|
+
}, delay);
|
|
183
|
+
}
|
|
184
|
+
disconnect() {
|
|
185
|
+
if (this.reconnectTimer) {
|
|
186
|
+
clearTimeout(this.reconnectTimer);
|
|
187
|
+
this.reconnectTimer = null;
|
|
188
|
+
}
|
|
189
|
+
this.ws?.close();
|
|
190
|
+
this.ws = null;
|
|
191
|
+
this.projectId = null;
|
|
192
|
+
this.listeners.clear();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
exports.KoolbaseRealtime = KoolbaseRealtime;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.recordFromWire = recordFromWire;
|
|
4
|
+
// Converts the flat public wire shape into a KoolbaseRecord.
|
|
5
|
+
// Server sends: { $id, $createdAt, $updatedAt, $collection, $createdBy?, ...fields }
|
|
6
|
+
function recordFromWire(raw) {
|
|
7
|
+
const data = {};
|
|
8
|
+
for (const key of Object.keys(raw)) {
|
|
9
|
+
if (!key.startsWith('$'))
|
|
10
|
+
data[key] = raw[key];
|
|
11
|
+
}
|
|
12
|
+
return {
|
|
13
|
+
id: raw['$id'],
|
|
14
|
+
collection: raw['$collection'],
|
|
15
|
+
createdBy: raw['$createdBy'],
|
|
16
|
+
data,
|
|
17
|
+
createdAt: raw['$createdAt'],
|
|
18
|
+
updatedAt: raw['$updatedAt'],
|
|
19
|
+
revision: typeof raw['$revision'] === 'number'
|
|
20
|
+
? raw['$revision']
|
|
21
|
+
: undefined,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
interface Slot {
|
|
2
|
+
platform?: unknown;
|
|
3
|
+
locks?: Map<string, Promise<unknown>>;
|
|
4
|
+
}
|
|
5
|
+
/** Read a shared value, initialising it on first use. */
|
|
6
|
+
export declare function shared<K extends keyof Slot>(key: K, create: () => NonNullable<Slot[K]>): NonNullable<Slot[K]>;
|
|
7
|
+
/** Replace a shared value. */
|
|
8
|
+
export declare function setShared<K extends keyof Slot>(key: K, value: Slot[K]): void;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// State that must be singular, even when this package is loaded twice.
|
|
3
|
+
//
|
|
4
|
+
// A dual-published package can end up in one application twice: the app's own
|
|
5
|
+
// code resolves the ESM build while a dependency resolves the CommonJS one.
|
|
6
|
+
// Module-level variables are then duplicated, and anything that assumes it is
|
|
7
|
+
// the only copy quietly stops being true.
|
|
8
|
+
//
|
|
9
|
+
// Two things here cannot tolerate that:
|
|
10
|
+
//
|
|
11
|
+
// - the platform adapter, which a platform package installs once at
|
|
12
|
+
// initialize. A second copy would keep the in-memory default, so sessions
|
|
13
|
+
// would not persist and the offline queue would read empty.
|
|
14
|
+
//
|
|
15
|
+
// - the offline-state lock table, which serialises read-modify-write on one
|
|
16
|
+
// storage key per user. A second copy means two chains over the same key:
|
|
17
|
+
// a queued write or a conflict can be lost. That is data, not a feature.
|
|
18
|
+
//
|
|
19
|
+
// Both live on a well-known globalThis key instead, so every copy of the
|
|
20
|
+
// module shares one instance. Keyed by a symbol registered in the global
|
|
21
|
+
// symbol registry, which is the same symbol across module instances and
|
|
22
|
+
// cannot collide with an application's own globals.
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.shared = shared;
|
|
25
|
+
exports.setShared = setShared;
|
|
26
|
+
const SLOT = Symbol.for('koolbase.sdk.shared.v1');
|
|
27
|
+
function slot() {
|
|
28
|
+
const g = globalThis;
|
|
29
|
+
if (!g[SLOT])
|
|
30
|
+
g[SLOT] = {};
|
|
31
|
+
return g[SLOT];
|
|
32
|
+
}
|
|
33
|
+
/** Read a shared value, initialising it on first use. */
|
|
34
|
+
function shared(key, create) {
|
|
35
|
+
const s = slot();
|
|
36
|
+
if (s[key] === undefined)
|
|
37
|
+
s[key] = create();
|
|
38
|
+
return s[key];
|
|
39
|
+
}
|
|
40
|
+
/** Replace a shared value. */
|
|
41
|
+
function setShared(key, value) {
|
|
42
|
+
slot()[key] = value;
|
|
43
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { KoolbaseError } from './errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Base error type for all Koolbase storage errors. Catchable via
|
|
4
|
+
* `instanceof KoolbaseStorageError` to handle any storage-related failure
|
|
5
|
+
* generically; subclasses let you handle specific cases.
|
|
6
|
+
*/
|
|
7
|
+
export declare class KoolbaseStorageError extends KoolbaseError {
|
|
8
|
+
constructor(message: string, code?: string);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Thrown when an upload is rejected because an object already exists at
|
|
12
|
+
* the requested path — the server responds with 409 Conflict and code
|
|
13
|
+
* `path_conflict`. Catch it to give the user an "overwrite this file?"
|
|
14
|
+
* prompt, then retry the upload with `overwrite: true`.
|
|
15
|
+
*
|
|
16
|
+
* `path` is the colliding path the server rejected, surfaced from the
|
|
17
|
+
* response body for diagnostics and UI.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* try {
|
|
21
|
+
* await Koolbase.storage.upload({
|
|
22
|
+
* bucket: 'avatars',
|
|
23
|
+
* path: 'me.png',
|
|
24
|
+
* file: { uri, name, type: 'image/png' },
|
|
25
|
+
* });
|
|
26
|
+
* } catch (e) {
|
|
27
|
+
* if (e instanceof KoolbaseStorageConflictError) {
|
|
28
|
+
* const ok = await confirm(`${e.path} already exists. Overwrite?`);
|
|
29
|
+
* if (ok) {
|
|
30
|
+
* await Koolbase.storage.upload({
|
|
31
|
+
* bucket: 'avatars',
|
|
32
|
+
* path: 'me.png',
|
|
33
|
+
* file: { uri, name, type: 'image/png' },
|
|
34
|
+
* overwrite: true,
|
|
35
|
+
* });
|
|
36
|
+
* }
|
|
37
|
+
* }
|
|
38
|
+
* }
|
|
39
|
+
*/
|
|
40
|
+
export declare class KoolbaseStorageConflictError extends KoolbaseStorageError {
|
|
41
|
+
path?: string;
|
|
42
|
+
constructor(message?: string, path?: string);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Thrown when the requested bucket or object does not exist — the server
|
|
46
|
+
* responds with 404. Also surfaced for cross-tenant access attempts
|
|
47
|
+
* (Koolbase's 404-over-403 convention prevents enumeration in
|
|
48
|
+
* multi-tenant contexts).
|
|
49
|
+
*/
|
|
50
|
+
export declare class KoolbaseStorageNotFoundError extends KoolbaseStorageError {
|
|
51
|
+
constructor(message?: string);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Thrown when the request is rejected as invalid — the server responds
|
|
55
|
+
* with 400 (e.g. a malformed path, missing field, invalid bucket name).
|
|
56
|
+
*/
|
|
57
|
+
export declare class KoolbaseStorageValidationError extends KoolbaseStorageError {
|
|
58
|
+
constructor(message?: string);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Thrown when the caller is authenticated but not allowed to perform the
|
|
62
|
+
* storage operation — the server responds with 403.
|
|
63
|
+
*/
|
|
64
|
+
export declare class KoolbaseStoragePermissionError extends KoolbaseStorageError {
|
|
65
|
+
constructor(message?: string);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Thrown when an upload would push the bucket past its configured
|
|
69
|
+
* `max_size_bytes` quota — the server responds with 409 Conflict and code
|
|
70
|
+
* `quota_exceeded`. The server cleans up the underlying R2 object before
|
|
71
|
+
* returning; nothing leaks. Catch this to surface a "bucket is full"
|
|
72
|
+
* message or prompt the caller to delete older files. The per-bucket
|
|
73
|
+
* quota is set at bucket creation time and is currently immutable.
|
|
74
|
+
*
|
|
75
|
+
* Distinct from {@link KoolbaseStorageConflictError} (which also uses
|
|
76
|
+
* 409 but means "path collides"); branch on the error type via
|
|
77
|
+
* `instanceof`, not on status.
|
|
78
|
+
*/
|
|
79
|
+
export declare class KoolbaseStorageQuotaError extends KoolbaseStorageError {
|
|
80
|
+
constructor(message?: string);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Thrown when a single file exceeds the bucket's configured
|
|
84
|
+
* `max_file_size_bytes` — the server responds with 413 Payload Too Large
|
|
85
|
+
* and code `file_too_large`. The server cleans up the underlying R2
|
|
86
|
+
* object before returning. The configured per-file limit lives on the
|
|
87
|
+
* bucket record; check `Bucket.maxFileSizeBytes` to surface a clear
|
|
88
|
+
* "files must be under X MB" message at the call site.
|
|
89
|
+
*/
|
|
90
|
+
export declare class KoolbaseStorageFileTooLargeError extends KoolbaseStorageError {
|
|
91
|
+
constructor(message?: string);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Thrown when an upload's content-type isn't in the bucket's configured
|
|
95
|
+
* `allowed_mime_types` allowlist — the server responds with 415
|
|
96
|
+
* Unsupported Media Type and code `mime_not_allowed`. The check runs at
|
|
97
|
+
* presign time, so no bytes are transferred before rejection.
|
|
98
|
+
*
|
|
99
|
+
* Allowlists support `type/*` wildcards (e.g. `image/*` matches every
|
|
100
|
+
* image content-type). A bucket with no allowlist configured accepts
|
|
101
|
+
* every type.
|
|
102
|
+
*/
|
|
103
|
+
export declare class KoolbaseStorageMimeTypeError extends KoolbaseStorageError {
|
|
104
|
+
constructor(message?: string);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Thrown when an object metadata payload (either at upload-confirm time
|
|
108
|
+
* or via `updateMetadata`) fails server-side validation — the server
|
|
109
|
+
* responds with 400 and code `metadata_invalid`.
|
|
110
|
+
*
|
|
111
|
+
* The `detail` field carries the specific reason from the server — e.g.
|
|
112
|
+
* `'key "foo bar": must match [a-z0-9_]+'`, `'exceeds 50 keys (got 53)'`,
|
|
113
|
+
* or `'exceeds 8192 bytes total (sum of all key + value lengths)'`. The
|
|
114
|
+
* detail names the failing key and rule so callers can fix the offending
|
|
115
|
+
* entry without guessing what shape rule was violated.
|
|
116
|
+
*
|
|
117
|
+
* Validation rules (enforced server-side):
|
|
118
|
+
* - At most 50 keys per object.
|
|
119
|
+
* - At most 8KB total (sum of byte lengths across all keys + values).
|
|
120
|
+
* - Keys: 1–64 chars, must match `[a-z0-9_]+`.
|
|
121
|
+
* - Keys with a leading underscore are reserved for system use.
|
|
122
|
+
* - Values: at most 1024 chars each.
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* try {
|
|
126
|
+
* await Koolbase.storage.updateMetadata('photos', 'sunset.jpg', {
|
|
127
|
+
* tag: 'sunset',
|
|
128
|
+
* 'BAD KEY': 'oops',
|
|
129
|
+
* });
|
|
130
|
+
* } catch (e) {
|
|
131
|
+
* if (e instanceof KoolbaseStorageMetadataInvalidError) {
|
|
132
|
+
* console.warn('Metadata rejected:', e.detail);
|
|
133
|
+
* // -> 'Metadata rejected: key "BAD KEY": must match [a-z0-9_]+'
|
|
134
|
+
* }
|
|
135
|
+
* }
|
|
136
|
+
*/
|
|
137
|
+
export declare class KoolbaseStorageMetadataInvalidError extends KoolbaseStorageError {
|
|
138
|
+
/**
|
|
139
|
+
* The specific validation failure reported by the server. Names the
|
|
140
|
+
* failing key (when applicable) and the rule that was violated.
|
|
141
|
+
* Surface this directly to developer logs or user-facing UI.
|
|
142
|
+
*/
|
|
143
|
+
detail?: string;
|
|
144
|
+
constructor(message?: string, detail?: string);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Maps a non-2xx storage-layer response to a typed
|
|
148
|
+
* {@link KoolbaseStorageError}, preferring the server's stable `code` and
|
|
149
|
+
* falling back to the HTTP status for older or uncoded responses. Always
|
|
150
|
+
* returns an error to throw.
|
|
151
|
+
*
|
|
152
|
+
* Status-fallback note: HTTP 409 covers both path_conflict and
|
|
153
|
+
* quota_exceeded. Without a `code` field, the mapper defaults 409 to
|
|
154
|
+
* {@link KoolbaseStorageConflictError} since path collisions are the more
|
|
155
|
+
* common case. Modern Koolbase servers always emit `code`, so this only
|
|
156
|
+
* matters for very old API responses or non-Koolbase 409s.
|
|
157
|
+
*/
|
|
158
|
+
export declare function koolbaseStorageError(status: number, body: any, fallbackMessage?: string): KoolbaseStorageError;
|
|
159
|
+
/**
|
|
160
|
+
* Convenience wrapper over {@link koolbaseStorageError} that decodes the
|
|
161
|
+
* response body for you. Use at call sites that have the raw `Response`.
|
|
162
|
+
*/
|
|
163
|
+
export declare function koolbaseStorageErrorFromResponse(res: Response, fallbackMessage?: string): Promise<KoolbaseStorageError>;
|