@tinycloud/web-sdk 1.7.1 → 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.
Files changed (45) hide show
  1. package/dist/adapters/BrowserENSResolver.d.ts +10 -0
  2. package/dist/adapters/BrowserENSResolver.d.ts.map +1 -0
  3. package/dist/adapters/BrowserNotificationHandler.d.ts +11 -0
  4. package/dist/adapters/BrowserNotificationHandler.d.ts.map +1 -0
  5. package/dist/adapters/BrowserSessionStorage.d.ts +9 -0
  6. package/dist/adapters/BrowserSessionStorage.d.ts.map +1 -0
  7. package/dist/adapters/BrowserWalletSigner.d.ts +22 -0
  8. package/dist/adapters/BrowserWalletSigner.d.ts.map +1 -0
  9. package/dist/adapters/BrowserWasmBindings.d.ts +23 -0
  10. package/dist/adapters/BrowserWasmBindings.d.ts.map +1 -0
  11. package/dist/adapters/index.d.ts +6 -0
  12. package/dist/adapters/index.d.ts.map +1 -0
  13. package/dist/authorization/index.d.ts +1 -3
  14. package/dist/authorization/index.d.ts.map +1 -1
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.ts +6 -6
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.mjs +1 -1
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/modules/Storage/tinycloud/types.schema.d.ts +6 -6
  22. package/dist/modules/index.d.ts +1 -1
  23. package/dist/modules/index.d.ts.map +1 -1
  24. package/dist/modules/keys/index.d.ts +0 -1
  25. package/dist/modules/keys/index.d.ts.map +1 -1
  26. package/dist/modules/tcw.d.ts +69 -651
  27. package/dist/modules/tcw.d.ts.map +1 -1
  28. package/dist/notifications/types.schema.d.ts +2 -2
  29. package/dist/providers/config.d.ts +44 -0
  30. package/dist/providers/config.d.ts.map +1 -0
  31. package/dist/providers/extension.d.ts +64 -0
  32. package/dist/providers/extension.d.ts.map +1 -0
  33. package/dist/providers/index.d.ts +10 -0
  34. package/dist/providers/index.d.ts.map +1 -0
  35. package/dist/providers/types.d.ts +657 -0
  36. package/dist/providers/types.d.ts.map +1 -0
  37. package/dist/providers/utils.d.ts +20 -0
  38. package/dist/providers/utils.d.ts.map +1 -0
  39. package/package.json +3 -3
  40. package/dist/authorization/WebUserAuthorization.d.ts +0 -297
  41. package/dist/authorization/WebUserAuthorization.d.ts.map +0 -1
  42. package/dist/delegation.d.ts +0 -84
  43. package/dist/delegation.d.ts.map +0 -1
  44. package/dist/modules/keys/WasmKeyProvider.d.ts +0 -126
  45. package/dist/modules/keys/WasmKeyProvider.d.ts.map +0 -1
@@ -1,10 +1,19 @@
1
- import { RPCProviders } from '@tinycloud/web-core';
2
- import { WebUserAuthorization, WebSignStrategy } from '../authorization';
3
- import { ClientConfig, ClientSession, Extension } from '@tinycloud/web-core/client';
4
- import type { providers } from 'ethers';
5
- import type { NotificationConfig } from '../notifications/types';
6
- import { IKVService, ICapabilityKeyRegistry, DelegationManager, ISpaceService, ISpace, Delegation, Result, DelegationError, ISharingService, CreateDelegationParams, ISpaceCreationHandler, type IDataVaultService } from '@tinycloud/sdk-core';
7
- import { PortableDelegation, DelegatedAccess } from '../delegation';
1
+ /**
2
+ * TinyCloudWeb thin browser wrapper around TinyCloudNode.
3
+ *
4
+ * All core logic (auth, services, delegations) is handled by TinyCloudNode.
5
+ * This wrapper provides:
6
+ * - Browser-specific adapters (wallet signer, notifications, WASM bindings)
7
+ * - The familiar TinyCloudWeb public API surface
8
+ * - Static receiveShare() using browser WASM
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ import { IKVService, ISQLService, IDuckDbService, IDataVaultService, ISpaceService, ISpace, ISharingService, ICapabilityKeyRegistry, DelegationManager, Delegation, CreateDelegationParams, Result, DelegationError, ClientSession, Extension, ISpaceCreationHandler } from "@tinycloud/sdk-core";
13
+ import type { providers } from "ethers";
14
+ import { RPCProviders, ClientConfig } from "../providers";
15
+ import type { NotificationConfig } from "../notifications/types";
16
+ import type { PortableDelegation, DelegatedAccess } from "@tinycloud/node-sdk/core";
8
17
  declare global {
9
18
  interface Window {
10
19
  ethereum?: any;
@@ -13,712 +22,121 @@ declare global {
13
22
  /**
14
23
  * Configuration for TinyCloudWeb.
15
24
  *
16
- * Extends ClientConfig with notification options and the unified auth module.
17
- *
18
- * ## Auth Module Features
19
- *
20
- * - **SignStrategy pattern**: Control how sign requests are handled
21
- * - **Session-only mode**: Receive delegations without a wallet
22
- * - **`did` vs `sessionDid` model**: Clear identity distinction
23
- * - **`connectWallet()` upgrade pattern**: Upgrade from session-only to full auth
24
- *
25
- * @example
26
- * ```typescript
27
- * // Standard wallet popup flow
28
- * const tcw = new TinyCloudWeb({
29
- * providers: { web3: { driver: window.ethereum } },
30
- * signStrategy: { type: 'wallet-popup' },
31
- * spaceCreationHandler: new ModalSpaceCreationHandler()
32
- * });
33
- *
34
- * // Session-only mode (no wallet required)
35
- * const tcw = new TinyCloudWeb();
36
- * console.log(tcw.sessionDid); // did:key:z6Mk...
37
- * ```
25
+ * Extends ClientConfig with browser-specific options.
38
26
  */
39
27
  export interface Config extends ClientConfig {
40
28
  /** Notification configuration for error popups and toasts */
41
29
  notifications?: NotificationConfig;
42
30
  /** Optional prefix for KV service keys */
43
31
  kvPrefix?: string;
44
- /**
45
- * Prefix for space names when creating spaces.
46
- * @example 'myapp' results in spaces like 'myapp-default'
47
- */
32
+ /** Prefix for space names when creating spaces */
48
33
  spacePrefix?: string;
49
- /**
50
- * TinyCloud server hosts.
51
- * @default ['https://node.tinycloud.xyz']
52
- */
34
+ /** TinyCloud server hosts (default: ['https://node.tinycloud.xyz']) */
53
35
  tinycloudHosts?: string[];
54
- /**
55
- * Whether to auto-create space on sign-in if it doesn't exist.
56
- * @default true
57
- */
36
+ /** Whether to auto-create space on sign-in (default: true) */
58
37
  autoCreateSpace?: boolean;
59
- /**
60
- * Sign strategy for handling sign requests.
61
- *
62
- * Determines how SIWE signing is handled:
63
- * - `'wallet-popup'` (default): Show browser wallet popup
64
- * - `{ type: 'auto-sign' }`: Automatically sign (requires external signer setup)
65
- * - `{ type: 'callback', handler: fn }`: Custom callback for sign requests
66
- * - `{ type: 'event-emitter', emitter: ee }`: Emit events for external handling
67
- *
68
- * @example
69
- * ```typescript
70
- * // Default: wallet popup
71
- * signStrategy: 'wallet-popup'
72
- *
73
- * // Custom callback for approval UI
74
- * signStrategy: {
75
- * type: 'callback',
76
- * handler: async (req) => {
77
- * const approved = await showCustomApprovalDialog(req.message);
78
- * return { approved };
79
- * }
80
- * }
81
- * ```
82
- */
83
- signStrategy?: WebSignStrategy;
84
- /**
85
- * Handler for space creation confirmation.
86
- *
87
- * Controls how space creation is confirmed:
88
- * - `ModalSpaceCreationHandler` (default): Shows a modal dialog
89
- * - `{ confirmSpaceCreation: async () => true }`: Auto-approve
90
- * - Custom implementation of `ISpaceCreationHandler`
91
- *
92
- * @example
93
- * ```typescript
94
- * // Default: modal confirmation
95
- * spaceCreationHandler: new ModalSpaceCreationHandler()
96
- *
97
- * // Auto-approve (no UI)
98
- * spaceCreationHandler: { confirmSpaceCreation: async () => true }
99
- *
100
- * // Custom handler
101
- * spaceCreationHandler: {
102
- * confirmSpaceCreation: async (context) => {
103
- * return await showCustomDialog(`Create space: ${context.spaceId}?`);
104
- * }
105
- * }
106
- * ```
107
- */
38
+ /** Space creation handler (default: ModalSpaceCreationHandler) */
108
39
  spaceCreationHandler?: ISpaceCreationHandler;
40
+ /** Session expiration time in milliseconds (default: 1 hour) */
41
+ sessionExpirationMs?: number;
42
+ /** Shorthand for passing a Web3 provider */
43
+ provider?: any;
109
44
  }
110
45
  /**
111
46
  * Result of receiving a share link.
112
47
  */
113
48
  export interface ShareReceiveResult<T = unknown> {
114
- /** The retrieved data */
115
49
  data: T;
116
- /** The delegation that authorized access */
117
50
  delegation: Delegation;
118
- /** The path the share grants access to */
119
51
  path: string;
120
- /** The space ID */
121
52
  spaceId: string;
122
53
  }
123
- /** TinyCloud Web SDK
124
- *
125
- * An SDK for building user-controlled web apps.
126
- */
127
54
  export declare class TinyCloudWeb {
128
- private config;
129
55
  /** The Ethereum provider */
130
56
  provider: providers.Web3Provider;
131
57
  /** Supported RPC Providers */
132
58
  static RPCProviders: typeof RPCProviders;
133
- /**
134
- * Receive and retrieve data from a v2 share link.
135
- *
136
- * This static method allows receiving shared data without being signed in.
137
- * The share link contains an embedded private key and delegation that
138
- * grants access to the shared resource.
139
- *
140
- * @param link - The share link (tc1:... format or full URL)
141
- * @param key - Optional specific key to retrieve within the shared path
142
- * @returns Result containing the data or an error
143
- *
144
- * @example
145
- * ```typescript
146
- * // Receive shared data using just the link
147
- * const result = await TinyCloudWeb.receiveShare('tc1:...');
148
- * if (result.ok) {
149
- * console.log('Data:', result.data.data);
150
- * console.log('Path:', result.data.path);
151
- * } else {
152
- * console.error('Error:', result.error.message);
153
- * }
154
- *
155
- * // Or from a full URL
156
- * const result = await TinyCloudWeb.receiveShare(
157
- * 'https://share.example.com/share/tc1:...'
158
- * );
159
- * ```
160
- */
161
- static receiveShare<T = unknown>(link: string, key?: string): Promise<Result<ShareReceiveResult<T>, DelegationError>>;
162
- /** UserAuthorization Module
163
- *
164
- * Handles the capabilities that a user can provide a app, specifically
165
- * authentication and authorization. This resource handles all key and
166
- * signing capabilities including:
167
- * - ethereum provider, wallet connection, SIWE message creation and signing
168
- * - session key management
169
- * - creates, manages, and handles session data
170
- * - manages/provides capabilities
171
- */
172
- userAuthorization: WebUserAuthorization;
173
- /** Error Handler for Notifications */
174
- private errorHandler;
175
- /** Service Context for sdk-services */
176
- private _serviceContext?;
177
- /** KV Service instance */
178
- private _kvService?;
179
- /** Capability Key Registry for automatic key selection */
180
- private _capabilityRegistry?;
181
- /** Delegation Manager for CRUD operations on delegations */
182
- private _delegationManager?;
183
- /** Space Service for managing spaces */
184
- private _spaceService?;
185
- /** KeyProvider for SharingService */
186
- private _keyProvider?;
187
- /** SharingService for generating/receiving share links */
188
- private _sharingService?;
189
- /** Data Vault service instance */
190
- private _vault?;
191
- /** Public KV service instance (lazily initialized, scoped to public space) */
192
- private _publicKV?;
59
+ /** Underlying TinyCloudNode (created after WASM init) */
60
+ private _node;
61
+ /** Browser notification handler */
62
+ private notificationHandler;
63
+ /** Browser WASM bindings */
64
+ private wasmBindings;
65
+ /** Browser wallet signer */
66
+ private walletSigner?;
67
+ /** Promise that resolves when WASM + node are ready */
68
+ private _initPromise;
69
+ /** User config */
70
+ private config;
193
71
  constructor(config?: Config);
194
72
  /**
195
- * Create a WebUserAuthorization instance from the config.
196
- * Maps Config options to WebUserAuthorizationConfig.
197
- * @private
198
- */
199
- private createWebUserAuthorization;
200
- /**
201
- * Get the KV service.
202
- *
203
- * Returns the new sdk-services KVService with Result pattern.
204
- * Must be signed in for the service to be available.
205
- *
206
- * @throws Error if not signed in
207
- *
208
- * @example
209
- * ```typescript
210
- * const result = await tcw.kv.get('key');
211
- * if (result.ok) {
212
- * console.log(result.data.data);
213
- * } else {
214
- * console.error(result.error.code, result.error.message);
215
- * }
216
- * ```
217
- */
218
- get kv(): IKVService;
219
- /**
220
- * Get the KV prefix configured for this instance.
221
- */
222
- get kvPrefix(): string;
223
- /**
224
- * Get the capability key registry for automatic key selection.
225
- * This registry tracks keys and their associated delegations,
226
- * enabling automatic selection of the best key for operations.
227
- *
228
- * Must be signed in for the registry to be available.
229
- *
230
- * @throws Error if not signed in
231
- *
232
- * @example
233
- * ```typescript
234
- * // Get the best key for an operation
235
- * const key = tcw.capabilityRegistry.getKeyForCapability(
236
- * 'tinycloud://my-space/kv/data',
237
- * 'tinycloud.kv/get'
238
- * );
239
- *
240
- * // List all capabilities
241
- * const capabilities = tcw.capabilityRegistry.getAllCapabilities();
242
- * ```
243
- */
244
- get capabilityRegistry(): ICapabilityKeyRegistry;
245
- /**
246
- * Get the delegation manager for CRUD operations on delegations.
247
- * Handles creating, revoking, listing, and querying delegations.
248
- *
249
- * Must be signed in for the manager to be available.
250
- *
251
- * @throws Error if not signed in
252
- *
253
- * @example
254
- * ```typescript
255
- * // Create a delegation
256
- * const result = await tcw.delegations.create({
257
- * delegateDID: 'did:pkh:eip155:1:0x...',
258
- * path: 'shared/',
259
- * actions: ['tinycloud.kv/get', 'tinycloud.kv/list'],
260
- * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
261
- * });
262
- *
263
- * // List all delegations
264
- * const listResult = await tcw.delegations.list();
265
- *
266
- * // Revoke a delegation
267
- * await tcw.delegations.revoke('bafy...');
268
- * ```
269
- */
270
- get delegations(): DelegationManager;
271
- /**
272
- * Get the space service for managing spaces (owned and delegated).
273
- * Provides listing, creation, and access to space-scoped operations.
274
- *
275
- * Must be signed in for the service to be available.
276
- *
277
- * @throws Error if not signed in
278
- *
279
- * @example
280
- * ```typescript
281
- * // List all accessible spaces
282
- * const result = await tcw.spaces.list();
283
- * if (result.ok) {
284
- * for (const space of result.data) {
285
- * console.log(`${space.name} (${space.type})`);
286
- * }
287
- * }
288
- *
289
- * // Create a new space
290
- * const createResult = await tcw.spaces.create('photos');
291
- *
292
- * // Get a space object for operations
293
- * const space = tcw.spaces.get('photos');
294
- * await space.kv.put('album/vacation', { photos: [...] });
295
- * ```
296
- */
297
- get spaces(): ISpaceService;
298
- /**
299
- * Get a specific space by name or URI.
300
- * Shorthand for `tcw.spaces.get(nameOrUri)`.
301
- *
302
- * Must be signed in for the service to be available.
303
- *
304
- * @param nameOrUri - Short name or full space URI
305
- * @returns Space object with scoped operations
306
- * @throws Error if not signed in
307
- *
308
- * @example
309
- * ```typescript
310
- * // Get an owned space by short name
311
- * const photos = tcw.space('photos');
312
- * await photos.kv.put('vacation/photo1.jpg', imageData);
313
- *
314
- * // Get a delegated space by full URI
315
- * const shared = tcw.space('tinycloud:pkh:eip155:1:0x...:shared');
316
- * const data = await shared.kv.get('document.json');
317
- * ```
318
- */
319
- space(nameOrUri: string): ISpace;
320
- /**
321
- * Get the sharing service for generating and managing share links.
322
- * Provides v2 sharing links with embedded private keys.
323
- *
324
- * Must be signed in for the service to be available.
325
- *
326
- * @throws Error if not signed in
327
- *
328
- * @example
329
- * ```typescript
330
- * // Generate a sharing link for a key
331
- * const result = await tcw.sharing.generate({
332
- * path: 'shared/document.json',
333
- * actions: ['tinycloud.kv/get'],
334
- * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
335
- * });
336
- * if (result.ok) {
337
- * console.log('Share link:', result.data.link);
338
- * }
339
- *
340
- * // Receive a share (static method, no auth needed)
341
- * const shareResult = await TinyCloudWeb.receiveShare('tc1:...');
342
- * ```
343
- */
344
- get sharing(): ISharingService;
345
- /**
346
- * Get the Data Vault service for encrypted KV storage.
347
- *
348
- * Must be signed in for the service to be available.
349
- * Call `vault.unlock(signer)` after sign-in to derive encryption keys.
350
- *
351
- * @throws Error if not signed in
352
- *
353
- * @example
354
- * ```typescript
355
- * await tcw.vault.unlock(signer);
356
- * await tcw.vault.put('secrets/api-key', { key: 'sk-...' });
357
- * const result = await tcw.vault.get<{ key: string }>('secrets/api-key');
358
- * if (result.ok) console.log(result.data.value.key);
359
- * ```
360
- */
361
- get vault(): IDataVaultService;
362
- /**
363
- * Initialize the sdk-services KVService and other services.
364
- * Called internally after sign-in when the session is established.
365
- *
73
+ * Async initialization: ensure WASM is ready, then create TinyCloudNode.
366
74
  * @internal
367
75
  */
368
- private initializeKVService;
76
+ private _init;
369
77
  /**
370
- * Initialize the delegation system services.
371
- * Called internally after sign-in when the session is established.
372
- *
373
- * @param hosts - TinyCloud host URLs
374
- * @param serviceSession - The service session
78
+ * Get the TinyCloudNode instance, awaiting init if necessary.
375
79
  * @internal
376
80
  */
377
- private initializeDelegationServices;
81
+ private ensureNode;
378
82
  /**
379
- * Initialize the Data Vault service after sign-in.
83
+ * Get the TinyCloudNode instance synchronously.
84
+ * Throws if called before WASM initialization completes.
380
85
  * @internal
381
86
  */
382
- private initializeVaultService;
87
+ private get node();
383
88
  /**
384
- * Ensure the user's public space exists. Creates it if needed.
385
- * Used by the Data Vault service to publish encryption keys.
386
- * @internal
387
- */
388
- private ensurePublicSpace;
389
- /**
390
- * Get or create a KV service scoped to the user's public space.
391
- * Used by the Data Vault service for publishing grants and public keys.
392
- * @internal
393
- */
394
- private getPublicKV;
395
- /**
396
- * Create a delegation for sharing using the WASM /delegate endpoint.
397
- * @internal
398
- */
399
- private createDelegationForSharing;
400
- /**
401
- * Wrapper for the WASM createDelegation function.
402
- * Adapts the WASM interface to what SharingService expects.
403
- * @internal
404
- */
405
- private createDelegationWrapper;
406
- /**
407
- * Get the session expiry time by parsing the SIWE message.
408
- * @internal
409
- */
410
- private getSessionExpiry;
411
- /**
412
- * Create a direct root delegation from the wallet to a share key.
413
- * This is the CORRECT solution for long-lived share links.
414
- *
415
- * Instead of creating a sub-delegation chain (PKH -> session key -> share key),
416
- * this creates a DIRECT delegation (PKH -> share key), which is not constrained
417
- * by the session's expiry time.
418
- *
419
- * This will trigger the OpenKey popup to sign a new SIWE message.
420
- *
421
- * @param params - Parameters for creating the root delegation
422
- * @param hosts - TinyCloud host URLs
423
- * @returns The delegation from wallet to share key, or undefined if failed
424
- * @internal
425
- */
426
- private createRootDelegationForSharing;
427
- /**
428
- * Create a delegation using SIWE-based flow.
429
- * This method implements the correct delegation creation pattern:
430
- * 1. Use prepareSession() to build the delegation
431
- * 2. Sign the SIWE message with the user's wallet
432
- * 3. Use completeSessionSetup() to get the delegation header
433
- * 4. Activate the delegation with the server
434
- *
435
- * @param params - Delegation parameters including spaceId
436
- * @param session - The TinyCloud session
437
- * @param address - User's address
438
- * @param chainId - Chain ID
439
- * @param hosts - TinyCloud host URLs
440
- * @returns Result containing the created Delegation or an error
441
- * @internal
442
- */
443
- private createDelegationWithSIWE;
444
- /**
445
- * Convert TinyCloud session to ServiceSession.
446
- * Gets session from WebUserAuthorization.
447
- * @internal
448
- */
449
- private toServiceSession;
450
- /**
451
- * Extends TinyCloudWeb with functions that are called after connecting and signing in.
452
- */
453
- extend(extension: Extension): void;
454
- /**
455
- * Request the user to sign in, and start the session.
456
- * @returns Object containing information about the session
89
+ * Factory method for guaranteed correct initialization.
90
+ * Awaits WASM loading before returning the instance.
457
91
  */
92
+ static create(config?: Config): Promise<TinyCloudWeb>;
93
+ get kv(): IKVService;
94
+ get sql(): ISQLService;
95
+ get duckdb(): IDuckDbService;
96
+ get vault(): IDataVaultService;
97
+ get spaces(): ISpaceService;
98
+ get sharing(): ISharingService;
99
+ get delegations(): DelegationManager;
100
+ get capabilityRegistry(): ICapabilityKeyRegistry;
101
+ space(nameOrUri: string): ISpace;
102
+ get kvPrefix(): string;
458
103
  signIn: () => Promise<ClientSession>;
459
- /**
460
- * Invalidates user's session.
461
- */
462
104
  signOut: () => Promise<void>;
463
- /**
464
- * Cleanup SDK resources including notification system.
465
- * Should be called when the SDK is no longer needed.
466
- */
467
- cleanup(): void;
468
- /**
469
- * Gets the session representation (once signed in).
470
- * @returns Session object.
471
- */
472
105
  session: () => ClientSession | undefined;
473
- /**
474
- * Gets the address that is connected and signed in.
475
- * @returns Address.
476
- */
477
106
  address: () => string | undefined;
478
- /**
479
- * Get the chainId that the address is connected and signed in on.
480
- * @returns chainId.
481
- */
482
107
  chainId: () => number | undefined;
483
- /**
484
- * Get the WebUserAuthorization instance.
485
- */
486
- get webAuth(): WebUserAuthorization;
487
- /**
488
- * Get the primary DID for this user.
489
- *
490
- * - If wallet connected and signed in: returns PKH DID (persistent identity)
491
- * - If session-only mode: returns session key DID (ephemeral)
492
- */
493
108
  get did(): string;
494
- /**
495
- * Get the session key DID.
496
- * Always available, even before sign-in.
497
- *
498
- * Format: `did:key:z6Mk...#z6Mk...`
499
- */
500
109
  get sessionDid(): string;
501
- /**
502
- * Check if in session-only mode.
503
- * Session-only mode means no wallet is connected, but delegations can be received.
504
- */
505
110
  get isSessionOnly(): boolean;
506
- /**
507
- * Check if a wallet is connected.
508
- * Wallet may be connected but not signed in.
509
- */
510
111
  get isWalletConnected(): boolean;
511
- /**
512
- * Connect a wallet to upgrade from session-only mode (new auth module only).
513
- *
514
- * This allows users who started in session-only mode (e.g., received
515
- * delegations) to later connect a wallet and create their own space.
516
- *
517
- * @param provider - Web3 provider (e.g., window.ethereum)
518
- * @param options - Optional configuration
519
- *
520
- * @example
521
- * ```typescript
522
- * // Create in session-only mode
523
- * const tcw = new TinyCloudWeb();
524
- * console.log(tcw.isSessionOnly); // true
525
- *
526
- * // User clicks "Connect Wallet"
527
- * tcw.connectWallet(window.ethereum);
528
- * console.log(tcw.isSessionOnly); // false
529
- *
530
- * // Now can sign in
531
- * await tcw.signIn();
532
- * ```
533
- */
112
+ extend(_extension: Extension): void;
113
+ cleanup(): void;
534
114
  connectWallet(provider: providers.ExternalProvider | providers.Web3Provider, options?: {
535
115
  spacePrefix?: string;
536
116
  }): void;
537
- /**
538
- * Use a delegation received from another user.
539
- *
540
- * This creates a session that chains from the received delegation,
541
- * allowing operations on the delegator's space.
542
- *
543
- * Works in both modes:
544
- * - **Session-only mode**: Uses the delegation directly (must target session key DID)
545
- * - **Wallet mode**: Creates a SIWE sub-delegation from PKH to session key
546
- *
547
- * @param delegation - The PortableDelegation to use (from createDelegation or transport)
548
- * @returns A DelegatedAccess instance for performing operations
549
- *
550
- * @throws Error if in session-only mode and delegation doesn't target this user's DID
551
- * @throws Error if in wallet mode and not signed in
552
- *
553
- * @example
554
- * ```typescript
555
- * // Session-only mode (most common for receiving delegations)
556
- * const tcw = new TinyCloudWeb();
557
- * const delegation = deserializeDelegation(receivedData);
558
- *
559
- * // The delegation must target tcw.did (session key DID in session-only mode)
560
- * const access = await tcw.useDelegation(delegation);
561
- *
562
- * // Perform KV operations on the delegated space
563
- * const data = await access.kv.get("shared/document.json");
564
- * await access.kv.put("shared/notes.txt", "Hello!");
565
- *
566
- * // Wallet mode (signed in user receiving delegation)
567
- * const tcw = new TinyCloudWeb({ providers: { web3: { driver: window.ethereum } } });
568
- * await tcw.signIn();
569
- *
570
- * // The delegation should target tcw.did (PKH DID when signed in)
571
- * const access = await tcw.useDelegation(delegation);
572
- * ```
573
- */
574
- useDelegation(delegation: PortableDelegation): Promise<DelegatedAccess>;
575
- /**
576
- * Convenience method to create a delegation via the delegation manager.
577
- * For creating PortableDelegations, use createDelegation() instead.
578
- *
579
- * @param params - Delegation parameters
580
- * @returns Result containing the created Delegation or an error
581
- *
582
- * @example
583
- * ```typescript
584
- * const result = await tcw.delegate({
585
- * delegateDID: 'did:pkh:eip155:1:0x...',
586
- * path: 'shared/',
587
- * actions: ['tinycloud.kv/get', 'tinycloud.kv/put'],
588
- * expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
589
- * });
590
- *
591
- * if (result.ok) {
592
- * console.log('Delegation created:', result.data.cid);
593
- * }
594
- * ```
595
- */
596
- delegate(params: CreateDelegationParams): Promise<Result<Delegation, DelegationError>>;
597
- /**
598
- * Revoke a delegation by CID.
599
- *
600
- * @param cid - The CID of the delegation to revoke
601
- * @returns Result indicating success or failure
602
- *
603
- * @example
604
- * ```typescript
605
- * const result = await tcw.revokeDelegation('bafy...');
606
- * if (result.ok) {
607
- * console.log('Delegation revoked');
608
- * }
609
- * ```
610
- */
611
- revokeDelegation(cid: string): Promise<Result<void, DelegationError>>;
612
- /**
613
- * List all delegations for the current space.
614
- *
615
- * @returns Result containing an array of Delegations
616
- *
617
- * @example
618
- * ```typescript
619
- * const result = await tcw.listDelegations();
620
- * if (result.ok) {
621
- * console.log('Delegations:', result.data.length);
622
- * }
623
- * ```
624
- */
625
- listDelegations(): Promise<Result<Delegation[], DelegationError>>;
626
- /**
627
- * Check if the current session has permission for a path and action.
628
- *
629
- * @param path - The resource path to check
630
- * @param action - The action to check (e.g., 'tinycloud.kv/get')
631
- * @returns Result containing boolean permission status
632
- *
633
- * @example
634
- * ```typescript
635
- * const result = await tcw.checkPermission('shared/docs', 'tinycloud.kv/get');
636
- * if (result.ok && result.data) {
637
- * console.log('Permission granted');
638
- * }
639
- * ```
640
- */
641
- checkPermission(path: string, action: string): Promise<Result<boolean, DelegationError>>;
642
- /**
643
- * Create a delegation to grant access to another user.
644
- * Returns a PortableDelegation that can be serialized and sent to the recipient.
645
- *
646
- * @param params - Delegation parameters
647
- * @returns A portable delegation that can be sent to the recipient
648
- *
649
- * @throws Error if not signed in
650
- *
651
- * @example
652
- * ```typescript
653
- * const delegation = await tcw.createDelegation({
654
- * path: "shared/",
655
- * actions: ["tinycloud.kv/get", "tinycloud.kv/list"],
656
- * delegateDID: recipientDid,
657
- * expiryMs: 7 * 24 * 60 * 60 * 1000, // 7 days
658
- * });
659
- *
660
- * // Send to recipient
661
- * const token = serializeDelegation(delegation);
662
- * ```
663
- */
664
117
  createDelegation(params: {
665
- /** Path within the space to delegate access to */
666
118
  path: string;
667
- /** Actions to allow (e.g., ["tinycloud.kv/get", "tinycloud.kv/put"]) */
668
119
  actions: string[];
669
- /** DID of the recipient (from their TinyCloudWeb.did) */
670
120
  delegateDID: string;
671
- /** Whether to prevent the recipient from creating sub-delegations (default: false) */
672
121
  disableSubDelegation?: boolean;
673
- /** Expiration time in milliseconds from now (default: 1 hour) */
674
122
  expiryMs?: number;
675
123
  }): Promise<PortableDelegation>;
676
- /**
677
- * Track a received delegation in the capability registry.
678
- * @private
679
- */
680
- private trackReceivedDelegation;
681
- /**
682
- * Create a sub-delegation from a received delegation.
683
- * Allows chaining delegations (Alice -> Bob -> Carol).
684
- *
685
- * This allows further delegating access that was received from another user,
686
- * if the original delegation allows sub-delegation.
687
- *
688
- * @param parentDelegation - The delegation received from another user
689
- * @param params - Sub-delegation parameters (must be within parent's scope)
690
- * @returns A portable delegation for the sub-delegate
691
- *
692
- * @throws Error if in session-only mode (requires wallet)
693
- * @throws Error if not signed in
694
- * @throws Error if parent delegation does not allow sub-delegation
695
- * @throws Error if sub-delegation path is outside parent's path
696
- * @throws Error if sub-delegation actions are not a subset of parent's actions
697
- *
698
- * @example
699
- * ```typescript
700
- * // Bob received a delegation from Alice
701
- * const access = await tcw.useDelegation(aliceDelegation);
702
- *
703
- * // Bob creates sub-delegation for Carol
704
- * const subDelegation = await tcw.createSubDelegation(aliceDelegation, {
705
- * path: "shared/subset/",
706
- * actions: ["tinycloud.kv/get"],
707
- * delegateDID: carolDid,
708
- * });
709
- * ```
710
- */
124
+ useDelegation(delegation: PortableDelegation): Promise<DelegatedAccess>;
711
125
  createSubDelegation(parentDelegation: PortableDelegation, params: {
712
- /** Path within the delegated path to sub-delegate */
713
126
  path: string;
714
- /** Actions to allow (must be subset of parent's actions) */
715
127
  actions: string[];
716
- /** DID of the recipient */
717
128
  delegateDID: string;
718
- /** Whether to prevent the recipient from creating further sub-delegations */
719
129
  disableSubDelegation?: boolean;
720
- /** Expiration time in milliseconds from now (must be before parent's expiry) */
721
130
  expiryMs?: number;
722
131
  }): Promise<PortableDelegation>;
132
+ delegate(params: CreateDelegationParams): Promise<Result<Delegation, DelegationError>>;
133
+ revokeDelegation(cid: string): Promise<Result<void, DelegationError>>;
134
+ listDelegations(): Promise<Result<Delegation[], DelegationError>>;
135
+ checkPermission(path: string, action: string): Promise<Result<boolean, DelegationError>>;
136
+ /**
137
+ * Receive and retrieve data from a v2 share link.
138
+ * Static method — no auth required. Uses browser WASM.
139
+ */
140
+ static receiveShare<T = unknown>(link: string, key?: string): Promise<Result<ShareReceiveResult<T>, DelegationError>>;
723
141
  }
724
142
  //# sourceMappingURL=tcw.d.ts.map