@tinycloud/web-sdk 1.7.2 → 2.0.1

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