@tinycloud/sdk-services 2.0.1 → 2.0.2

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.
Files changed (139) hide show
  1. package/dist/{types.d.ts → BaseService-D9BFm_rV.d.cts} +179 -27
  2. package/dist/BaseService-D9BFm_rV.d.ts +440 -0
  3. package/dist/index.cjs +3221 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +1843 -0
  6. package/dist/index.d.ts +1826 -41
  7. package/dist/index.js +3136 -58
  8. package/dist/index.js.map +1 -1
  9. package/dist/kv/index.cjs +909 -0
  10. package/dist/kv/index.cjs.map +1 -0
  11. package/dist/kv/index.d.cts +748 -0
  12. package/dist/kv/index.d.ts +745 -7
  13. package/dist/kv/index.js +877 -9
  14. package/dist/kv/index.js.map +1 -1
  15. package/dist/sql/index.cjs +596 -0
  16. package/dist/sql/index.cjs.map +1 -0
  17. package/dist/sql/index.d.cts +228 -0
  18. package/dist/sql/index.d.ts +225 -7
  19. package/dist/sql/index.js +566 -8
  20. package/dist/sql/index.js.map +1 -1
  21. package/package.json +7 -6
  22. package/dist/base/BaseService.d.ts +0 -151
  23. package/dist/base/BaseService.d.ts.map +0 -1
  24. package/dist/base/BaseService.js +0 -221
  25. package/dist/base/BaseService.js.map +0 -1
  26. package/dist/base/index.d.ts +0 -6
  27. package/dist/base/index.d.ts.map +0 -1
  28. package/dist/base/index.js +0 -6
  29. package/dist/base/index.js.map +0 -1
  30. package/dist/base/types.d.ts +0 -36
  31. package/dist/base/types.d.ts.map +0 -1
  32. package/dist/base/types.js +0 -7
  33. package/dist/base/types.js.map +0 -1
  34. package/dist/context.d.ts +0 -142
  35. package/dist/context.d.ts.map +0 -1
  36. package/dist/context.js +0 -218
  37. package/dist/context.js.map +0 -1
  38. package/dist/duckdb/DuckDbDatabaseHandle.d.ts +0 -23
  39. package/dist/duckdb/DuckDbDatabaseHandle.d.ts.map +0 -1
  40. package/dist/duckdb/DuckDbDatabaseHandle.js +0 -36
  41. package/dist/duckdb/DuckDbDatabaseHandle.js.map +0 -1
  42. package/dist/duckdb/DuckDbService.d.ts +0 -50
  43. package/dist/duckdb/DuckDbService.d.ts.map +0 -1
  44. package/dist/duckdb/DuckDbService.js +0 -285
  45. package/dist/duckdb/DuckDbService.js.map +0 -1
  46. package/dist/duckdb/IDuckDbService.d.ts +0 -84
  47. package/dist/duckdb/IDuckDbService.d.ts.map +0 -1
  48. package/dist/duckdb/IDuckDbService.js +0 -7
  49. package/dist/duckdb/IDuckDbService.js.map +0 -1
  50. package/dist/duckdb/index.d.ts +0 -10
  51. package/dist/duckdb/index.d.ts.map +0 -1
  52. package/dist/duckdb/index.js +0 -9
  53. package/dist/duckdb/index.js.map +0 -1
  54. package/dist/duckdb/types.d.ts +0 -148
  55. package/dist/duckdb/types.d.ts.map +0 -1
  56. package/dist/duckdb/types.js +0 -19
  57. package/dist/duckdb/types.js.map +0 -1
  58. package/dist/errors.d.ts +0 -62
  59. package/dist/errors.d.ts.map +0 -1
  60. package/dist/errors.js +0 -149
  61. package/dist/errors.js.map +0 -1
  62. package/dist/index.d.ts.map +0 -1
  63. package/dist/kv/IKVService.d.ts +0 -148
  64. package/dist/kv/IKVService.d.ts.map +0 -1
  65. package/dist/kv/IKVService.js +0 -8
  66. package/dist/kv/IKVService.js.map +0 -1
  67. package/dist/kv/KVService.d.ts +0 -155
  68. package/dist/kv/KVService.d.ts.map +0 -1
  69. package/dist/kv/KVService.js +0 -419
  70. package/dist/kv/KVService.js.map +0 -1
  71. package/dist/kv/PrefixedKVService.d.ts +0 -246
  72. package/dist/kv/PrefixedKVService.d.ts.map +0 -1
  73. package/dist/kv/PrefixedKVService.js +0 -145
  74. package/dist/kv/PrefixedKVService.js.map +0 -1
  75. package/dist/kv/index.d.ts.map +0 -1
  76. package/dist/kv/types.d.ts +0 -204
  77. package/dist/kv/types.d.ts.map +0 -1
  78. package/dist/kv/types.js +0 -16
  79. package/dist/kv/types.js.map +0 -1
  80. package/dist/quota/TinyCloudQuota.d.ts +0 -27
  81. package/dist/quota/TinyCloudQuota.d.ts.map +0 -1
  82. package/dist/quota/TinyCloudQuota.js +0 -31
  83. package/dist/quota/TinyCloudQuota.js.map +0 -1
  84. package/dist/quota/index.d.ts +0 -3
  85. package/dist/quota/index.d.ts.map +0 -1
  86. package/dist/quota/index.js +0 -2
  87. package/dist/quota/index.js.map +0 -1
  88. package/dist/sql/DatabaseHandle.d.ts +0 -20
  89. package/dist/sql/DatabaseHandle.d.ts.map +0 -1
  90. package/dist/sql/DatabaseHandle.js +0 -27
  91. package/dist/sql/DatabaseHandle.js.map +0 -1
  92. package/dist/sql/ISQLService.d.ts +0 -67
  93. package/dist/sql/ISQLService.d.ts.map +0 -1
  94. package/dist/sql/ISQLService.js +0 -7
  95. package/dist/sql/ISQLService.js.map +0 -1
  96. package/dist/sql/SQLService.d.ts +0 -44
  97. package/dist/sql/SQLService.d.ts.map +0 -1
  98. package/dist/sql/SQLService.js +0 -216
  99. package/dist/sql/SQLService.js.map +0 -1
  100. package/dist/sql/index.d.ts.map +0 -1
  101. package/dist/sql/types.d.ts +0 -102
  102. package/dist/sql/types.d.ts.map +0 -1
  103. package/dist/sql/types.js +0 -21
  104. package/dist/sql/types.js.map +0 -1
  105. package/dist/types.d.ts.map +0 -1
  106. package/dist/types.js +0 -94
  107. package/dist/types.js.map +0 -1
  108. package/dist/types.schema.d.ts +0 -712
  109. package/dist/types.schema.d.ts.map +0 -1
  110. package/dist/types.schema.js +0 -342
  111. package/dist/types.schema.js.map +0 -1
  112. package/dist/types.schema.test.d.ts +0 -5
  113. package/dist/types.schema.test.d.ts.map +0 -1
  114. package/dist/types.schema.test.js +0 -677
  115. package/dist/types.schema.test.js.map +0 -1
  116. package/dist/vault/DataVaultService.d.ts +0 -267
  117. package/dist/vault/DataVaultService.d.ts.map +0 -1
  118. package/dist/vault/DataVaultService.js +0 -1040
  119. package/dist/vault/DataVaultService.js.map +0 -1
  120. package/dist/vault/IDataVaultService.d.ts +0 -158
  121. package/dist/vault/IDataVaultService.d.ts.map +0 -1
  122. package/dist/vault/IDataVaultService.js +0 -8
  123. package/dist/vault/IDataVaultService.js.map +0 -1
  124. package/dist/vault/SignatureCache.d.ts +0 -20
  125. package/dist/vault/SignatureCache.d.ts.map +0 -1
  126. package/dist/vault/SignatureCache.js +0 -167
  127. package/dist/vault/SignatureCache.js.map +0 -1
  128. package/dist/vault/createVaultCrypto.d.ts +0 -16
  129. package/dist/vault/createVaultCrypto.d.ts.map +0 -1
  130. package/dist/vault/createVaultCrypto.js +0 -12
  131. package/dist/vault/createVaultCrypto.js.map +0 -1
  132. package/dist/vault/index.d.ts +0 -11
  133. package/dist/vault/index.d.ts.map +0 -1
  134. package/dist/vault/index.js +0 -12
  135. package/dist/vault/index.js.map +0 -1
  136. package/dist/vault/types.d.ts +0 -141
  137. package/dist/vault/types.d.ts.map +0 -1
  138. package/dist/vault/types.js +0 -31
  139. package/dist/vault/types.js.map +0 -1
@@ -0,0 +1,909 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/kv/index.ts
21
+ var kv_exports = {};
22
+ __export(kv_exports, {
23
+ KVAction: () => KVAction,
24
+ KVService: () => KVService,
25
+ PrefixedKVService: () => PrefixedKVService
26
+ });
27
+ module.exports = __toCommonJS(kv_exports);
28
+
29
+ // src/types.ts
30
+ var ErrorCodes = {
31
+ // Common errors
32
+ NOT_FOUND: "NOT_FOUND",
33
+ AUTH_EXPIRED: "AUTH_EXPIRED",
34
+ AUTH_REQUIRED: "AUTH_REQUIRED",
35
+ AUTH_UNAUTHORIZED: "AUTH_UNAUTHORIZED",
36
+ NETWORK_ERROR: "NETWORK_ERROR",
37
+ TIMEOUT: "TIMEOUT",
38
+ ABORTED: "ABORTED",
39
+ INVALID_INPUT: "INVALID_INPUT",
40
+ PERMISSION_DENIED: "PERMISSION_DENIED",
41
+ // KV-specific errors
42
+ KV_NOT_FOUND: "KV_NOT_FOUND",
43
+ KV_WRITE_FAILED: "KV_WRITE_FAILED",
44
+ // SQL-specific errors
45
+ SQL_ERROR: "SQL_ERROR",
46
+ SQL_PERMISSION_DENIED: "SQL_PERMISSION_DENIED",
47
+ SQL_DATABASE_NOT_FOUND: "SQL_DATABASE_NOT_FOUND",
48
+ SQL_RESPONSE_TOO_LARGE: "SQL_RESPONSE_TOO_LARGE",
49
+ SQL_QUOTA_EXCEEDED: "SQL_QUOTA_EXCEEDED",
50
+ SQL_INVALID_STATEMENT: "SQL_INVALID_STATEMENT",
51
+ SQL_SCHEMA_ERROR: "SQL_SCHEMA_ERROR",
52
+ SQL_READONLY_VIOLATION: "SQL_READONLY_VIOLATION",
53
+ // Storage quota errors
54
+ STORAGE_QUOTA_EXCEEDED: "STORAGE_QUOTA_EXCEEDED",
55
+ STORAGE_LIMIT_REACHED: "STORAGE_LIMIT_REACHED",
56
+ // DuckDB-specific errors
57
+ DUCKDB_ERROR: "DUCKDB_ERROR",
58
+ DUCKDB_PERMISSION_DENIED: "DUCKDB_PERMISSION_DENIED",
59
+ DUCKDB_DATABASE_NOT_FOUND: "DUCKDB_DATABASE_NOT_FOUND",
60
+ DUCKDB_RESPONSE_TOO_LARGE: "DUCKDB_RESPONSE_TOO_LARGE",
61
+ DUCKDB_QUOTA_EXCEEDED: "DUCKDB_QUOTA_EXCEEDED",
62
+ DUCKDB_INVALID_STATEMENT: "DUCKDB_INVALID_STATEMENT",
63
+ DUCKDB_SCHEMA_ERROR: "DUCKDB_SCHEMA_ERROR",
64
+ DUCKDB_READONLY_VIOLATION: "DUCKDB_READONLY_VIOLATION"
65
+ };
66
+ var defaultRetryPolicy = {
67
+ maxAttempts: 3,
68
+ backoff: "exponential",
69
+ baseDelayMs: 1e3,
70
+ maxDelayMs: 1e4,
71
+ retryableErrors: [ErrorCodes.NETWORK_ERROR, ErrorCodes.TIMEOUT]
72
+ };
73
+ var TelemetryEvents = {
74
+ SERVICE_REQUEST: "service.request",
75
+ SERVICE_RESPONSE: "service.response",
76
+ SERVICE_ERROR: "service.error",
77
+ SERVICE_RETRY: "service.retry",
78
+ SESSION_CHANGED: "session.changed",
79
+ SESSION_EXPIRED: "session.expired"
80
+ };
81
+ function ok(data) {
82
+ return { ok: true, data };
83
+ }
84
+ function err(error) {
85
+ return { ok: false, error };
86
+ }
87
+ function serviceError(code, message, service, options) {
88
+ return {
89
+ code,
90
+ message,
91
+ service,
92
+ cause: options?.cause,
93
+ meta: options?.meta
94
+ };
95
+ }
96
+
97
+ // src/errors.ts
98
+ function authRequiredError(service) {
99
+ return {
100
+ code: ErrorCodes.AUTH_REQUIRED,
101
+ message: "Authentication required. Please sign in first.",
102
+ service
103
+ };
104
+ }
105
+ function timeoutError(service) {
106
+ return {
107
+ code: ErrorCodes.TIMEOUT,
108
+ message: "Request timed out.",
109
+ service
110
+ };
111
+ }
112
+ function abortedError(service) {
113
+ return {
114
+ code: ErrorCodes.ABORTED,
115
+ message: "Request was aborted.",
116
+ service
117
+ };
118
+ }
119
+ function parseAuthError(responseText) {
120
+ const match = responseText.match(/^Unauthorized Action:\s*(.+?)\s*\/\s*(tinycloud\.\S+)$/m);
121
+ if (match) {
122
+ return { resource: match[1].trim(), action: match[2].trim() };
123
+ }
124
+ return {};
125
+ }
126
+ function authUnauthorizedError(service, message, meta) {
127
+ return serviceError(ErrorCodes.AUTH_UNAUTHORIZED, message, service, { meta });
128
+ }
129
+ function storageQuotaExceededError(service, message, meta) {
130
+ return {
131
+ code: ErrorCodes.STORAGE_QUOTA_EXCEEDED,
132
+ message,
133
+ service,
134
+ meta
135
+ };
136
+ }
137
+ function storageLimitReachedError(service, message, meta) {
138
+ return {
139
+ code: ErrorCodes.STORAGE_LIMIT_REACHED,
140
+ message,
141
+ service,
142
+ meta
143
+ };
144
+ }
145
+ function wrapError(service, error, defaultCode = ErrorCodes.NETWORK_ERROR) {
146
+ if (error instanceof Error) {
147
+ if (error.name === "AbortError") {
148
+ return abortedError(service);
149
+ }
150
+ if (error.name === "TimeoutError" || error.message.toLowerCase().includes("timeout")) {
151
+ return timeoutError(service);
152
+ }
153
+ return {
154
+ code: defaultCode,
155
+ message: error.message,
156
+ service,
157
+ cause: error
158
+ };
159
+ }
160
+ return {
161
+ code: defaultCode,
162
+ message: String(error),
163
+ service
164
+ };
165
+ }
166
+
167
+ // src/base/BaseService.ts
168
+ var BaseService = class {
169
+ constructor() {
170
+ /**
171
+ * Abort controller for this service's operations.
172
+ * Reset on sign-out.
173
+ */
174
+ this.abortController = new AbortController();
175
+ /**
176
+ * Service-specific configuration.
177
+ */
178
+ this._config = {};
179
+ }
180
+ /**
181
+ * Get the service configuration.
182
+ */
183
+ get config() {
184
+ return this._config;
185
+ }
186
+ /**
187
+ * Initialize the service with context.
188
+ * Called by the SDK after instantiation.
189
+ *
190
+ * @param context - The service context
191
+ */
192
+ initialize(context) {
193
+ this.context = context;
194
+ }
195
+ /**
196
+ * Called when session changes (sign-in, sign-out, refresh).
197
+ * Override in subclasses to handle session changes.
198
+ *
199
+ * @param session - The new session, or null if signed out
200
+ */
201
+ onSessionChange(session) {
202
+ }
203
+ /**
204
+ * Called when SDK signs out.
205
+ * Aborts all pending operations.
206
+ */
207
+ onSignOut() {
208
+ this.abortController.abort();
209
+ this.abortController = new AbortController();
210
+ }
211
+ /**
212
+ * Get the abort signal for this service.
213
+ * Combines the service-level abort with context-level abort.
214
+ */
215
+ get abortSignal() {
216
+ return this.abortController.signal;
217
+ }
218
+ /**
219
+ * Check if the service is authenticated.
220
+ */
221
+ get isAuthenticated() {
222
+ return this.context?.isAuthenticated ?? false;
223
+ }
224
+ /**
225
+ * Get the current session.
226
+ * Throws if not authenticated.
227
+ */
228
+ get session() {
229
+ if (!this.context?.session) {
230
+ throw new Error("Not authenticated");
231
+ }
232
+ return this.context.session;
233
+ }
234
+ /**
235
+ * Check authentication and return error result if not authenticated.
236
+ * Use this at the start of methods that require authentication.
237
+ *
238
+ * @returns true if authenticated, false otherwise
239
+ */
240
+ requireAuth() {
241
+ return this.isAuthenticated;
242
+ }
243
+ /**
244
+ * Emit a telemetry event.
245
+ *
246
+ * @param event - Event name
247
+ * @param data - Event data
248
+ */
249
+ emit(event, data) {
250
+ this.context?.emit(event, data);
251
+ }
252
+ /**
253
+ * Emit a service request event.
254
+ *
255
+ * @param action - The action being performed
256
+ * @param key - Optional key/path being accessed
257
+ */
258
+ emitRequest(action, key) {
259
+ this.emit(TelemetryEvents.SERVICE_REQUEST, {
260
+ service: this.getServiceName(),
261
+ action,
262
+ key,
263
+ timestamp: Date.now()
264
+ });
265
+ }
266
+ /**
267
+ * Emit a service response event.
268
+ *
269
+ * @param action - The action that was performed
270
+ * @param ok - Whether the request was successful
271
+ * @param startTime - Start time for duration calculation
272
+ * @param status - Optional HTTP status code
273
+ */
274
+ emitResponse(action, ok2, startTime, status) {
275
+ this.emit(TelemetryEvents.SERVICE_RESPONSE, {
276
+ service: this.getServiceName(),
277
+ action,
278
+ ok: ok2,
279
+ duration: Date.now() - startTime,
280
+ status
281
+ });
282
+ }
283
+ /**
284
+ * Emit a service error event.
285
+ *
286
+ * @param error - The service error
287
+ */
288
+ emitError(error) {
289
+ this.emit(TelemetryEvents.SERVICE_ERROR, {
290
+ service: this.getServiceName(),
291
+ error
292
+ });
293
+ }
294
+ /**
295
+ * Get the service name from the static property.
296
+ * Subclasses must define static serviceName.
297
+ */
298
+ getServiceName() {
299
+ return this.constructor.serviceName;
300
+ }
301
+ /**
302
+ * Create a combined abort signal from multiple sources.
303
+ *
304
+ * @param signals - Additional abort signals to combine
305
+ * @returns A combined abort signal
306
+ */
307
+ combineSignals(...signals) {
308
+ const controller = new AbortController();
309
+ const allSignals = [this.abortSignal, ...signals.filter(Boolean)];
310
+ for (const signal of allSignals) {
311
+ if (signal.aborted) {
312
+ controller.abort(signal.reason);
313
+ return controller.signal;
314
+ }
315
+ signal.addEventListener("abort", () => controller.abort(signal.reason), {
316
+ once: true
317
+ });
318
+ }
319
+ return controller.signal;
320
+ }
321
+ /**
322
+ * Wrap an operation with error handling and telemetry.
323
+ *
324
+ * @param action - The action name for telemetry
325
+ * @param key - Optional key for telemetry
326
+ * @param operation - The operation to execute
327
+ * @returns Result of the operation
328
+ */
329
+ async withTelemetry(action, key, operation) {
330
+ const startTime = Date.now();
331
+ this.emitRequest(action, key);
332
+ try {
333
+ const result = await operation();
334
+ if (result.ok) {
335
+ this.emitResponse(action, true, startTime);
336
+ } else {
337
+ this.emitResponse(action, false, startTime);
338
+ this.emitError(result.error);
339
+ }
340
+ return result;
341
+ } catch (error) {
342
+ const serviceError2 = wrapError(this.getServiceName(), error);
343
+ this.emitResponse(action, false, startTime);
344
+ this.emitError(serviceError2);
345
+ return err(serviceError2);
346
+ }
347
+ }
348
+ };
349
+
350
+ // src/kv/PrefixedKVService.ts
351
+ var PrefixedKVService = class _PrefixedKVService {
352
+ /**
353
+ * Create a new PrefixedKVService.
354
+ *
355
+ * @param kv - The underlying KV service to delegate to
356
+ * @param prefix - The prefix to apply to all operations
357
+ */
358
+ constructor(kv, prefix) {
359
+ this._kv = kv;
360
+ this._prefix = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
361
+ }
362
+ /**
363
+ * The current prefix for this scoped view.
364
+ */
365
+ get prefix() {
366
+ return this._prefix;
367
+ }
368
+ /**
369
+ * Compute the full key path by combining prefix and key.
370
+ *
371
+ * @param key - The key to prefix
372
+ * @returns The full path including prefix
373
+ */
374
+ getFullKey(key) {
375
+ const normalizedKey = key.startsWith("/") ? key : `/${key}`;
376
+ return `${this._prefix}${normalizedKey}`;
377
+ }
378
+ /**
379
+ * Get a value by key.
380
+ */
381
+ async get(key, options) {
382
+ const fullKey = this.getFullKey(key);
383
+ return this._kv.get(fullKey, { ...options, prefix: "" });
384
+ }
385
+ /**
386
+ * Store a value at a key.
387
+ */
388
+ async put(key, value, options) {
389
+ const fullKey = this.getFullKey(key);
390
+ return this._kv.put(fullKey, value, { ...options, prefix: "" });
391
+ }
392
+ /**
393
+ * List keys within this prefix.
394
+ */
395
+ async list(options) {
396
+ const removePrefix = options?.removePrefix ?? true;
397
+ return this._kv.list({
398
+ ...options,
399
+ prefix: this._prefix,
400
+ removePrefix
401
+ });
402
+ }
403
+ /**
404
+ * Delete a key.
405
+ */
406
+ async delete(key, options) {
407
+ const fullKey = this.getFullKey(key);
408
+ return this._kv.delete(fullKey, { ...options, prefix: "" });
409
+ }
410
+ /**
411
+ * Get metadata for a key without retrieving the value.
412
+ */
413
+ async head(key, options) {
414
+ const fullKey = this.getFullKey(key);
415
+ return this._kv.head(fullKey, { ...options, prefix: "" });
416
+ }
417
+ /**
418
+ * Create a nested prefix-scoped view.
419
+ */
420
+ withPrefix(subPrefix) {
421
+ const normalizedSubPrefix = subPrefix.startsWith("/") ? subPrefix : `/${subPrefix}`;
422
+ const combinedPrefix = `${this._prefix}${normalizedSubPrefix}`;
423
+ return new _PrefixedKVService(this._kv, combinedPrefix);
424
+ }
425
+ };
426
+
427
+ // src/kv/types.ts
428
+ var KVAction = {
429
+ GET: "tinycloud.kv/get",
430
+ PUT: "tinycloud.kv/put",
431
+ LIST: "tinycloud.kv/list",
432
+ DELETE: "tinycloud.kv/del",
433
+ HEAD: "tinycloud.kv/metadata"
434
+ };
435
+
436
+ // src/kv/KVService.ts
437
+ var KVService = class extends BaseService {
438
+ /**
439
+ * Create a new KVService instance.
440
+ *
441
+ * @param config - Service configuration
442
+ */
443
+ constructor(config = {}) {
444
+ super();
445
+ this._config = config;
446
+ }
447
+ /**
448
+ * Get the service configuration.
449
+ */
450
+ get config() {
451
+ return this._config;
452
+ }
453
+ // Parses "Used: X bytes, Limit: Y bytes" from tinycloud-node error responses
454
+ parseQuotaInfo(errorText) {
455
+ const match = errorText.match(
456
+ /Used:\s*(\d+)\s*bytes,\s*Limit:\s*(\d+)\s*bytes/i
457
+ );
458
+ if (match) {
459
+ return {
460
+ usedBytes: parseInt(match[1], 10),
461
+ limitBytes: parseInt(match[2], 10)
462
+ };
463
+ }
464
+ return void 0;
465
+ }
466
+ handleQuotaErrorResponse(response, errorText, key) {
467
+ if (response.status === 402) {
468
+ const quotaInfo = this.parseQuotaInfo(errorText);
469
+ return err(
470
+ storageQuotaExceededError(
471
+ "kv",
472
+ `Storage quota exceeded for key "${key}": ${errorText}`,
473
+ {
474
+ status: response.status,
475
+ ...quotaInfo ? { usedBytes: quotaInfo.usedBytes, limitBytes: quotaInfo.limitBytes } : {}
476
+ }
477
+ )
478
+ );
479
+ }
480
+ if (response.status === 413) {
481
+ const quotaInfo = this.parseQuotaInfo(errorText);
482
+ return err(
483
+ storageLimitReachedError(
484
+ "kv",
485
+ `Storage limit reached for key "${key}": ${errorText}`,
486
+ {
487
+ status: response.status,
488
+ ...quotaInfo ? { usedBytes: quotaInfo.usedBytes, limitBytes: quotaInfo.limitBytes } : {}
489
+ }
490
+ )
491
+ );
492
+ }
493
+ return void 0;
494
+ }
495
+ /**
496
+ * Get the full path with optional prefix.
497
+ *
498
+ * @param key - The key
499
+ * @param prefixOverride - Optional prefix override
500
+ * @returns The full path
501
+ */
502
+ getFullPath(key, prefixOverride) {
503
+ const prefix = prefixOverride ?? this._config.prefix ?? "";
504
+ return prefix ? `${prefix}/${key}` : key;
505
+ }
506
+ /**
507
+ * Get the host URL.
508
+ */
509
+ get host() {
510
+ return this.context.hosts[0];
511
+ }
512
+ /**
513
+ * Execute an invoke operation.
514
+ *
515
+ * @param path - Resource path
516
+ * @param action - KV action
517
+ * @param body - Optional request body
518
+ * @param signal - Optional abort signal
519
+ * @returns Fetch response
520
+ */
521
+ async invokeOperation(path, action, body, signal) {
522
+ const session = this.context.session;
523
+ const headers = this.context.invoke(
524
+ session,
525
+ "kv",
526
+ path,
527
+ action
528
+ );
529
+ return this.context.fetch(`${this.host}/invoke`, {
530
+ method: "POST",
531
+ headers,
532
+ body,
533
+ signal: this.combineSignals(signal)
534
+ });
535
+ }
536
+ /**
537
+ * Create KVResponseHeaders from fetch response headers.
538
+ *
539
+ * @param headers - Fetch response headers
540
+ * @returns KVResponseHeaders object
541
+ */
542
+ createResponseHeaders(headers) {
543
+ return {
544
+ etag: headers.get("etag") ?? void 0,
545
+ contentType: headers.get("content-type") ?? void 0,
546
+ lastModified: headers.get("last-modified") ?? void 0,
547
+ contentLength: headers.get("content-length") ? parseInt(headers.get("content-length"), 10) : void 0,
548
+ get: (name) => headers.get(name)
549
+ };
550
+ }
551
+ /**
552
+ * Parse response body based on content type.
553
+ *
554
+ * @param response - Fetch response
555
+ * @param raw - Whether to return raw text
556
+ * @returns Parsed data
557
+ */
558
+ async parseResponse(response, raw = false) {
559
+ if (!response.ok) {
560
+ return void 0;
561
+ }
562
+ if (raw) {
563
+ return await response.text();
564
+ }
565
+ const contentType = response.headers.get("content-type");
566
+ if (contentType?.includes("application/json")) {
567
+ return await response.json();
568
+ } else if (contentType?.startsWith("text/")) {
569
+ return await response.text();
570
+ }
571
+ const text = await response.text();
572
+ if (!text) {
573
+ return void 0;
574
+ }
575
+ try {
576
+ return JSON.parse(text);
577
+ } catch {
578
+ return text;
579
+ }
580
+ }
581
+ /**
582
+ * Get a value by key.
583
+ */
584
+ async get(key, options) {
585
+ return this.withTelemetry("get", key, async () => {
586
+ if (!this.requireAuth()) {
587
+ return err(authRequiredError("kv"));
588
+ }
589
+ const path = this.getFullPath(key, options?.prefix);
590
+ try {
591
+ const response = await this.invokeOperation(
592
+ path,
593
+ KVAction.GET,
594
+ void 0,
595
+ options?.signal
596
+ );
597
+ if (!response.ok) {
598
+ if (response.status === 401) {
599
+ const errorText2 = await response.text();
600
+ const { resource, action } = parseAuthError(errorText2);
601
+ return err(authUnauthorizedError("kv", errorText2, {
602
+ status: response.status,
603
+ ...action && { requiredAction: action },
604
+ ...resource && { resource }
605
+ }));
606
+ }
607
+ if (response.status === 404) {
608
+ return err(
609
+ serviceError(
610
+ ErrorCodes.KV_NOT_FOUND,
611
+ `Key not found: ${key}`,
612
+ "kv"
613
+ )
614
+ );
615
+ }
616
+ const errorText = await response.text();
617
+ return err(
618
+ serviceError(
619
+ ErrorCodes.NETWORK_ERROR,
620
+ `Failed to get key "${key}": ${response.status} - ${errorText}`,
621
+ "kv",
622
+ { meta: { status: response.status, statusText: response.statusText } }
623
+ )
624
+ );
625
+ }
626
+ const data = await this.parseResponse(response, options?.raw);
627
+ return ok({
628
+ data,
629
+ headers: this.createResponseHeaders(response.headers)
630
+ });
631
+ } catch (error) {
632
+ return err(wrapError("kv", error));
633
+ }
634
+ });
635
+ }
636
+ /**
637
+ * Store a value at a key.
638
+ */
639
+ async put(key, value, options) {
640
+ return this.withTelemetry("put", key, async () => {
641
+ if (!this.requireAuth()) {
642
+ return err(authRequiredError("kv"));
643
+ }
644
+ const path = this.getFullPath(key, options?.prefix);
645
+ let body;
646
+ if (typeof value === "string") {
647
+ body = value;
648
+ } else {
649
+ body = JSON.stringify(value);
650
+ }
651
+ try {
652
+ const response = await this.invokeOperation(
653
+ path,
654
+ KVAction.PUT,
655
+ body,
656
+ options?.signal
657
+ );
658
+ if (!response.ok) {
659
+ if (response.status === 401) {
660
+ const errorText2 = await response.text();
661
+ const { resource, action } = parseAuthError(errorText2);
662
+ return err(authUnauthorizedError("kv", errorText2, {
663
+ status: response.status,
664
+ ...action && { requiredAction: action },
665
+ ...resource && { resource }
666
+ }));
667
+ }
668
+ const errorText = await response.text();
669
+ const quotaError = this.handleQuotaErrorResponse(
670
+ response,
671
+ errorText,
672
+ key
673
+ );
674
+ if (quotaError) {
675
+ return quotaError;
676
+ }
677
+ return err(
678
+ serviceError(
679
+ ErrorCodes.KV_WRITE_FAILED,
680
+ `Failed to put key "${key}": ${response.status} - ${errorText}`,
681
+ "kv",
682
+ { meta: { status: response.status, statusText: response.statusText } }
683
+ )
684
+ );
685
+ }
686
+ return ok({
687
+ data: void 0,
688
+ headers: this.createResponseHeaders(response.headers)
689
+ });
690
+ } catch (error) {
691
+ return err(wrapError("kv", error));
692
+ }
693
+ });
694
+ }
695
+ /**
696
+ * List keys with optional prefix filtering.
697
+ */
698
+ async list(options) {
699
+ return this.withTelemetry("list", options?.prefix, async () => {
700
+ if (!this.requireAuth()) {
701
+ return err(authRequiredError("kv"));
702
+ }
703
+ let listPath = options?.prefix ?? this._config.prefix ?? "";
704
+ if (options?.path) {
705
+ listPath = listPath ? `${listPath}/${options.path}` : options.path;
706
+ }
707
+ try {
708
+ const response = await this.invokeOperation(
709
+ listPath,
710
+ KVAction.LIST,
711
+ void 0,
712
+ options?.signal
713
+ );
714
+ if (!response.ok) {
715
+ if (response.status === 401) {
716
+ const errorText2 = await response.text();
717
+ const { resource, action } = parseAuthError(errorText2);
718
+ return err(authUnauthorizedError("kv", errorText2, {
719
+ status: response.status,
720
+ ...action && { requiredAction: action },
721
+ ...resource && { resource }
722
+ }));
723
+ }
724
+ const errorText = await response.text();
725
+ return err(
726
+ serviceError(
727
+ ErrorCodes.NETWORK_ERROR,
728
+ `Failed to list keys: ${response.status} - ${errorText}`,
729
+ "kv",
730
+ { meta: { status: response.status, statusText: response.statusText } }
731
+ )
732
+ );
733
+ }
734
+ let keys = await this.parseResponse(response, options?.raw);
735
+ keys = keys ?? [];
736
+ if (options?.removePrefix && listPath) {
737
+ const prefixWithSlash = listPath.endsWith("/") ? listPath : `${listPath}/`;
738
+ keys = keys.map(
739
+ (key) => key.startsWith(prefixWithSlash) ? key.slice(prefixWithSlash.length) : key
740
+ );
741
+ }
742
+ return ok({ keys });
743
+ } catch (error) {
744
+ return err(wrapError("kv", error));
745
+ }
746
+ });
747
+ }
748
+ /**
749
+ * Delete a key.
750
+ */
751
+ async delete(key, options) {
752
+ return this.withTelemetry("delete", key, async () => {
753
+ if (!this.requireAuth()) {
754
+ return err(authRequiredError("kv"));
755
+ }
756
+ const path = this.getFullPath(key, options?.prefix);
757
+ try {
758
+ const response = await this.invokeOperation(
759
+ path,
760
+ KVAction.DELETE,
761
+ void 0,
762
+ options?.signal
763
+ );
764
+ if (!response.ok) {
765
+ if (response.status === 401) {
766
+ const errorText2 = await response.text();
767
+ const { resource, action } = parseAuthError(errorText2);
768
+ return err(authUnauthorizedError("kv", errorText2, {
769
+ status: response.status,
770
+ ...action && { requiredAction: action },
771
+ ...resource && { resource }
772
+ }));
773
+ }
774
+ if (response.status === 404) {
775
+ return err(
776
+ serviceError(
777
+ ErrorCodes.KV_NOT_FOUND,
778
+ `Key not found: ${key}`,
779
+ "kv"
780
+ )
781
+ );
782
+ }
783
+ const errorText = await response.text();
784
+ return err(
785
+ serviceError(
786
+ ErrorCodes.NETWORK_ERROR,
787
+ `Failed to delete key "${key}": ${response.status} - ${errorText}`,
788
+ "kv",
789
+ { meta: { status: response.status, statusText: response.statusText } }
790
+ )
791
+ );
792
+ }
793
+ return ok(void 0);
794
+ } catch (error) {
795
+ return err(wrapError("kv", error));
796
+ }
797
+ });
798
+ }
799
+ /**
800
+ * Get metadata for a key without retrieving the value.
801
+ */
802
+ async head(key, options) {
803
+ return this.withTelemetry("head", key, async () => {
804
+ if (!this.requireAuth()) {
805
+ return err(authRequiredError("kv"));
806
+ }
807
+ const path = this.getFullPath(key, options?.prefix);
808
+ try {
809
+ const response = await this.invokeOperation(
810
+ path,
811
+ KVAction.HEAD,
812
+ void 0,
813
+ options?.signal
814
+ );
815
+ if (!response.ok) {
816
+ if (response.status === 401) {
817
+ const errorText2 = await response.text();
818
+ const { resource, action } = parseAuthError(errorText2);
819
+ return err(authUnauthorizedError("kv", errorText2, {
820
+ status: response.status,
821
+ ...action && { requiredAction: action },
822
+ ...resource && { resource }
823
+ }));
824
+ }
825
+ if (response.status === 404) {
826
+ return err(
827
+ serviceError(
828
+ ErrorCodes.KV_NOT_FOUND,
829
+ `Key not found: ${key}`,
830
+ "kv"
831
+ )
832
+ );
833
+ }
834
+ const errorText = await response.text();
835
+ return err(
836
+ serviceError(
837
+ ErrorCodes.NETWORK_ERROR,
838
+ `Failed to get metadata for key "${key}": ${response.status} - ${errorText}`,
839
+ "kv",
840
+ { meta: { status: response.status, statusText: response.statusText } }
841
+ )
842
+ );
843
+ }
844
+ return ok({
845
+ data: void 0,
846
+ headers: this.createResponseHeaders(response.headers)
847
+ });
848
+ } catch (error) {
849
+ return err(wrapError("kv", error));
850
+ }
851
+ });
852
+ }
853
+ /**
854
+ * Create a prefix-scoped view of this KV service.
855
+ *
856
+ * Returns a PrefixedKVService that automatically prefixes all
857
+ * key operations with the specified prefix. This enables apps
858
+ * to isolate their data within a shared space.
859
+ *
860
+ * @param prefix - The prefix to apply to all operations
861
+ * @returns A PrefixedKVService scoped to the prefix
862
+ *
863
+ * ## Prefix Conventions
864
+ *
865
+ * | Pattern | Use Case | Example |
866
+ * | -- | -- | -- |
867
+ * | `/app.{domain}/` | App-private data | `/app.photos.xyz/settings.json` |
868
+ * | `/{type}/` | Shared data type | `/photos/vacation.jpg` |
869
+ * | `/.{name}/` | Hidden/system data | `/.cache/thumbnails/` |
870
+ * | `/public/` | Explicitly shareable | `/public/profile.json` |
871
+ *
872
+ * @example
873
+ * ```typescript
874
+ * const space = sdk.space('default');
875
+ *
876
+ * // Create prefix-scoped views
877
+ * const myApp = space.kv.withPrefix('/app.myapp.com');
878
+ * const sharedPhotos = space.kv.withPrefix('/photos');
879
+ *
880
+ * // Operations are automatically prefixed
881
+ * await myApp.put('settings.json', { theme: 'dark' });
882
+ * // -> Actually writes to: /app.myapp.com/settings.json
883
+ *
884
+ * await myApp.get('settings.json');
885
+ * // -> Actually reads from: /app.myapp.com/settings.json
886
+ *
887
+ * await sharedPhotos.list();
888
+ * // -> Lists: /photos/*
889
+ *
890
+ * // Nested prefixes
891
+ * const settings = myApp.withPrefix('/settings');
892
+ * await settings.get('theme.json'); // -> /app.myapp.com/settings/theme.json
893
+ * ```
894
+ */
895
+ withPrefix(prefix) {
896
+ return new PrefixedKVService(this, prefix);
897
+ }
898
+ };
899
+ /**
900
+ * Service identifier for registration.
901
+ */
902
+ KVService.serviceName = "kv";
903
+ // Annotate the CommonJS export names for ESM import in node:
904
+ 0 && (module.exports = {
905
+ KVAction,
906
+ KVService,
907
+ PrefixedKVService
908
+ });
909
+ //# sourceMappingURL=index.cjs.map