// src/core.ts
import { TinyCloud as TinyCloud2 } from "@tinycloud/sdk-core";
import {
  SilentNotificationHandler as SilentNotificationHandler2,
  AutoApproveSpaceCreationHandler as AutoApproveSpaceCreationHandler2,
  defaultSpaceCreationHandler
} from "@tinycloud/sdk-core";

// src/storage/MemorySessionStorage.ts
var MemorySessionStorage = class {
  constructor() {
    this.sessions = /* @__PURE__ */ new Map();
  }
  /**
   * Save a session for an address.
   */
  async save(address, session) {
    const normalizedAddress = address.toLowerCase();
    this.sessions.set(normalizedAddress, session);
  }
  /**
   * Load a session for an address.
   */
  async load(address) {
    const normalizedAddress = address.toLowerCase();
    const session = this.sessions.get(normalizedAddress);
    if (!session) {
      return null;
    }
    const expiresAt = new Date(session.expiresAt);
    if (expiresAt < /* @__PURE__ */ new Date()) {
      this.sessions.delete(normalizedAddress);
      return null;
    }
    return session;
  }
  /**
   * Clear a session for an address.
   */
  async clear(address) {
    const normalizedAddress = address.toLowerCase();
    this.sessions.delete(normalizedAddress);
  }
  /**
   * Check if a session exists for an address.
   */
  exists(address) {
    const normalizedAddress = address.toLowerCase();
    const session = this.sessions.get(normalizedAddress);
    if (!session) {
      return false;
    }
    const expiresAt = new Date(session.expiresAt);
    if (expiresAt < /* @__PURE__ */ new Date()) {
      this.sessions.delete(normalizedAddress);
      return false;
    }
    return true;
  }
  /**
   * Memory storage is always available.
   */
  isAvailable() {
    return true;
  }
  /**
   * Clear all sessions.
   */
  clearAll() {
    this.sessions.clear();
  }
  /**
   * Get the number of stored sessions.
   */
  size() {
    return this.sessions.size;
  }
};

// src/storage/FileSessionStorage.ts
import { validatePersistedSessionData } from "@tinycloud/sdk-core";
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from "fs";
import { join } from "path";
var FileSessionStorage = class {
  /**
   * Create a new FileSessionStorage.
   *
   * @param baseDir - Directory to store session files (default: ~/.tinycloud/sessions)
   */
  constructor(baseDir) {
    this.baseDir = baseDir || this.getDefaultDir();
    this.ensureDirectoryExists();
  }
  /**
   * Get the default session storage directory.
   */
  getDefaultDir() {
    const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
    return join(home, ".tinycloud", "sessions");
  }
  /**
   * Ensure the storage directory exists.
   */
  ensureDirectoryExists() {
    if (!existsSync(this.baseDir)) {
      mkdirSync(this.baseDir, { recursive: true });
    }
  }
  /**
   * Get the file path for an address.
   */
  getFilePath(address) {
    const normalizedAddress = address.toLowerCase();
    const filename = `${normalizedAddress.replace("0x", "")}.json`;
    return join(this.baseDir, filename);
  }
  /**
   * Save a session for an address.
   */
  async save(address, session) {
    const filePath = this.getFilePath(address);
    const data = JSON.stringify(session, null, 2);
    writeFileSync(filePath, data, "utf-8");
  }
  /**
   * Load a session for an address.
   */
  async load(address) {
    const filePath = this.getFilePath(address);
    if (!existsSync(filePath)) {
      return null;
    }
    try {
      const data = readFileSync(filePath, "utf-8");
      const parsed = JSON.parse(data);
      const validation = validatePersistedSessionData(parsed);
      if (!validation.ok) {
        console.warn(`Invalid session data for ${address}:`, validation.error.message);
        unlinkSync(filePath);
        return null;
      }
      const session = validation.data;
      const expiresAt = new Date(session.expiresAt);
      if (expiresAt < /* @__PURE__ */ new Date()) {
        unlinkSync(filePath);
        return null;
      }
      return session;
    } catch (error) {
      try {
        unlinkSync(filePath);
      } catch {
      }
      return null;
    }
  }
  /**
   * Clear a session for an address.
   */
  async clear(address) {
    const filePath = this.getFilePath(address);
    if (existsSync(filePath)) {
      unlinkSync(filePath);
    }
  }
  /**
   * Check if a session exists for an address.
   */
  exists(address) {
    const filePath = this.getFilePath(address);
    if (!existsSync(filePath)) {
      return false;
    }
    try {
      const data = readFileSync(filePath, "utf-8");
      const session = JSON.parse(data);
      const expiresAt = new Date(session.expiresAt);
      if (expiresAt < /* @__PURE__ */ new Date()) {
        unlinkSync(filePath);
        return false;
      }
      return true;
    } catch {
      return false;
    }
  }
  /**
   * Check if file system storage is available.
   */
  isAvailable() {
    try {
      this.ensureDirectoryExists();
      return existsSync(this.baseDir);
    } catch {
      return false;
    }
  }
};

// src/authorization/NodeUserAuthorization.ts
import {
  fetchPeerId,
  submitHostDelegation,
  activateSessionWithHost,
  checkNodeInfo,
  AutoApproveSpaceCreationHandler,
  manifestAbilitiesUnion,
  resolveManifest
} from "@tinycloud/sdk-core";

// src/authorization/strategies.ts
var defaultSignStrategy = { type: "auto-sign" };

// src/authorization/NodeUserAuthorization.ts
var NodeUserAuthorization = class {
  constructor(config) {
    this.extensions = [];
    this._nodeFeatures = [];
    this.wasm = config.wasmBindings;
    this.signer = config.signer;
    this.signStrategy = config.signStrategy ?? defaultSignStrategy;
    this.sessionStorage = config.sessionStorage ?? new MemorySessionStorage();
    this.domain = config.domain;
    this.uri = config.uri ?? `https://${config.domain}`;
    this.statement = config.statement;
    this.spacePrefix = config.spacePrefix ?? "default";
    this.defaultActions = config.defaultActions ?? {
      kv: {
        "": [
          "tinycloud.kv/put",
          "tinycloud.kv/get",
          "tinycloud.kv/del",
          "tinycloud.kv/list",
          "tinycloud.kv/metadata"
        ]
      },
      sql: {
        "": [
          "tinycloud.sql/read",
          "tinycloud.sql/write",
          "tinycloud.sql/admin",
          "tinycloud.sql/export"
        ]
      },
      duckdb: {
        "": [
          "tinycloud.duckdb/read",
          "tinycloud.duckdb/write",
          "tinycloud.duckdb/admin",
          "tinycloud.duckdb/describe",
          "tinycloud.duckdb/export",
          "tinycloud.duckdb/import",
          "tinycloud.duckdb/execute"
        ]
      },
      capabilities: {
        "": ["tinycloud.capabilities/read"]
      },
      hooks: {
        "": [
          "tinycloud.hooks/subscribe",
          "tinycloud.hooks/register",
          "tinycloud.hooks/list",
          "tinycloud.hooks/unregister"
        ]
      }
    };
    this.sessionExpirationMs = config.sessionExpirationMs ?? 60 * 60 * 1e3;
    this.autoCreateSpace = config.autoCreateSpace ?? false;
    this.spaceCreationHandler = config.spaceCreationHandler;
    this.tinycloudHosts = config.tinycloudHosts ?? [
      "https://node.tinycloud.xyz"
    ];
    this.enablePublicSpace = config.enablePublicSpace ?? true;
    this.nonce = config.nonce;
    this.siweConfig = config.siweConfig;
    this._manifest = config.manifest;
    this.sessionManager = this.wasm.createSessionManager();
  }
  /**
   * Return the manifest currently driving sign-in behavior, or
   * `undefined` if none is set. Used by TinyCloudWeb/TinyCloudNode
   * internals to surface the manifest for requestPermissions flows
   * without forcing the caller to track it separately.
   */
  get manifest() {
    return this._manifest;
  }
  /**
   * Install or replace the stored manifest. Takes effect on the next
   * `signIn()` call — the current session (if any) is not touched.
   */
  setManifest(manifest) {
    this._manifest = manifest;
  }
  /**
   * The current active session (web-core compatible).
   */
  get session() {
    return this._session;
  }
  /**
   * The current TinyCloud session with full delegation data.
   * Includes spaceId, delegationHeader, and delegationCid.
   */
  get tinyCloudSession() {
    return this._tinyCloudSession;
  }
  get nodeFeatures() {
    return this._nodeFeatures;
  }
  /**
   * Compute the `abilities` map the WASM `prepareSession` call should
   * see at sign-in time.
   *
   * When a manifest is installed, we resolve it and union together:
   * - the app's own `resources` (what it needs at runtime)
   * - every `additionalDelegates[*].permissions` list (what it will
   *   re-delegate to other DIDs post sign-in)
   *
   * into the short-service / path / full-URN-actions shape the WASM
   * layer expects. This is the key invariant that lets
   * {@link TinyCloudNode.delegateTo} issue manifest-declared
   * delegations via the session key (no wallet prompt): the session's
   * own recap already covers every action those delegations need.
   *
   * When no manifest is installed, we fall back to the
   * {@link defaultActions} table so existing callers see no change.
   *
   * This is a pure function of `this._manifest` + `this.defaultActions`
   * — the manifest resolution performs no I/O and throws a
   * {@link ManifestValidationError} on structural problems (missing
   * id/name, unparseable expiry, etc), which will surface at sign-in
   * rather than being silently swallowed.
   *
   * @internal
   */
  resolveSignInAbilities() {
    if (this._manifest === void 0) {
      return this.defaultActions;
    }
    const resolved = resolveManifest(this._manifest);
    return manifestAbilitiesUnion(resolved);
  }
  /**
   * Build SIWE overrides from the top-level nonce and siweConfig.
   * - Top-level `nonce` is seeded first so `siweConfig.nonce` wins if both are set.
   * - statement is prepended to the default statement
   * - resources are appended to the default resources
   * - uri triggers a warning (overwriting delegation target)
   * - all other fields override directly
   * - per-call nonce overrides siweConfig.nonce when provided
   */
  buildSiweOverrides(options) {
    const base = { uri: this.uri };
    if (this.nonce !== void 0) {
      base.nonce = this.nonce;
    }
    if (!this.siweConfig && !options?.nonce) {
      return base;
    }
    const { statement, resources, uri, ...rest } = this.siweConfig ?? {};
    const overrides = { ...base, ...rest };
    if (statement) {
      overrides.statement = this.statement ? `${statement} ${this.statement}` : statement;
    }
    if (resources && resources.length > 0) {
      overrides.resources = resources;
    }
    if (uri) {
      console.warn(
        "[tinycloud] siweConfig.uri is overwriting the delegation target URI. This may break delegation chain validation if the URI does not match the session key DID."
      );
      overrides.uri = uri;
    }
    if (options?.nonce) {
      overrides.nonce = options.nonce;
    }
    return overrides;
  }
  /**
   * Add an extension to the authorization flow.
   */
  extend(extension) {
    this.extensions.push(extension);
  }
  /**
   * Get the space ID for the current session.
   */
  getSpaceId() {
    return this._tinyCloudSession?.spaceId;
  }
  /**
   * Create the space on the TinyCloud server (host delegation).
   * This registers the user as the owner of the space.
   */
  async hostSpace(targetSpaceId) {
    if (!this._tinyCloudSession || !this._address || !this._chainId) {
      throw new Error("Must be signed in to host space");
    }
    const host = this.tinycloudHosts[0];
    const spaceId = targetSpaceId ?? this._tinyCloudSession.spaceId;
    const peerId = await fetchPeerId(host, spaceId);
    const siwe = this.wasm.generateHostSIWEMessage({
      address: this._address,
      chainId: this._chainId,
      domain: this.domain,
      issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
      spaceId,
      peerId
    });
    const signature = await this.signMessage(siwe);
    const headers = this.wasm.siweToDelegationHeaders({ siwe, signature });
    const result = await submitHostDelegation(host, headers);
    return result.success;
  }
  /**
   * Create a specific space on the server via host delegation.
   * Used for lazy creation of additional spaces (e.g., public).
   */
  async hostPublicSpace(spaceId) {
    return this.hostSpace(spaceId);
  }
  /**
   * Ensure the user's space exists on the TinyCloud server.
   * Creates the space if it doesn't exist and autoCreateSpace is enabled.
   * If autoCreateSpace is false and space doesn't exist, silently returns
   * (user may be using delegations to access other spaces).
   *
   * @throws Error if space creation fails
   */
  async ensureSpaceExists() {
    if (!this._tinyCloudSession) {
      throw new Error("Must be signed in to ensure space exists");
    }
    const host = this.tinycloudHosts[0];
    const primarySpaceId = this._tinyCloudSession.spaceId;
    const result = await activateSessionWithHost(
      host,
      this._tinyCloudSession.delegationHeader
    );
    const handler = this.spaceCreationHandler ?? (this.autoCreateSpace ? new AutoApproveSpaceCreationHandler() : void 0);
    const creationContext = {
      spaceId: primarySpaceId,
      address: this._address,
      chainId: this._chainId,
      host
    };
    if (result.success) {
      const primarySkipped = result.skipped?.includes(primarySpaceId);
      if (!primarySkipped) {
        return;
      }
      if (!handler) {
        return;
      }
      const confirmed = await handler.confirmSpaceCreation(creationContext);
      if (!confirmed) {
        return;
      }
      try {
        const created = await this.hostSpace();
        if (!created) {
          const err = new Error(`Failed to create space: ${primarySpaceId}`);
          handler.onSpaceCreationFailed?.(creationContext, err);
          throw err;
        }
      } catch (error) {
        handler.onSpaceCreationFailed?.(
          creationContext,
          error instanceof Error ? error : new Error(String(error))
        );
        throw error;
      }
      await new Promise((resolve) => setTimeout(resolve, 100));
      const retryResult = await activateSessionWithHost(
        host,
        this._tinyCloudSession.delegationHeader
      );
      if (!retryResult.success) {
        const err = new Error(
          `Failed to activate session after creating space: ${retryResult.error}`
        );
        handler.onSpaceCreationFailed?.(creationContext, err);
        throw err;
      }
      handler.onSpaceCreated?.(creationContext);
      return;
    }
    if (result.status === 404) {
      if (!handler) {
        return;
      }
      const confirmed = await handler.confirmSpaceCreation(creationContext);
      if (!confirmed) {
        return;
      }
      try {
        const created = await this.hostSpace();
        if (!created) {
          const err = new Error(`Failed to create space: ${primarySpaceId}`);
          handler.onSpaceCreationFailed?.(creationContext, err);
          throw err;
        }
      } catch (error) {
        handler.onSpaceCreationFailed?.(
          creationContext,
          error instanceof Error ? error : new Error(String(error))
        );
        throw error;
      }
      await new Promise((resolve) => setTimeout(resolve, 100));
      const retryResult = await activateSessionWithHost(
        host,
        this._tinyCloudSession.delegationHeader
      );
      if (!retryResult.success) {
        const err = new Error(
          `Failed to activate session after creating space: ${retryResult.error}`
        );
        handler.onSpaceCreationFailed?.(creationContext, err);
        throw err;
      }
      handler.onSpaceCreated?.(creationContext);
      return;
    }
    throw new Error(`Failed to activate session: ${result.error}`);
  }
  /**
   * Sign in and create a new session.
   *
   * This follows the correct SIWE-ReCap flow:
   * 1. Create session key and get JWK
   * 2. Call prepareSession() which generates the SIWE with ReCap capabilities
   * 3. Sign the SIWE string from prepareSession
   * 4. Call completeSessionSetup() with the prepared session + signature
   *
   * @param options - Optional per-call SIWE overrides for this sign-in only
   */
  async signIn(options) {
    this._address = await this.signer.getAddress();
    this._chainId = await this.signer.getChainId();
    const address = this.wasm.ensureEip55(this._address);
    const chainId = this._chainId;
    const keyId = `session-${Date.now()}`;
    this.sessionManager.renameSessionKeyId("default", keyId);
    const jwkString = this.sessionManager.jwk(keyId);
    if (!jwkString) {
      throw new Error("Failed to create session key");
    }
    const jwk = JSON.parse(jwkString);
    const spaceId = this.wasm.makeSpaceId(address, chainId, this.spacePrefix);
    const now = /* @__PURE__ */ new Date();
    const expirationTime = new Date(now.getTime() + this.sessionExpirationMs);
    const prepared = this.wasm.prepareSession({
      abilities: this.resolveSignInAbilities(),
      address,
      chainId,
      domain: this.domain,
      issuedAt: now.toISOString(),
      expirationTime: expirationTime.toISOString(),
      spaceId,
      jwk,
      ...this.buildSiweOverrides(options)
    });
    const signature = await this.requestSignature({
      address,
      chainId,
      message: prepared.siwe,
      type: "siwe"
    });
    const session = this.wasm.completeSessionSetup({
      ...prepared,
      signature
    });
    const clientSession = {
      address,
      walletAddress: address,
      chainId,
      sessionKey: keyId,
      siwe: prepared.siwe,
      signature
    };
    const spacesMetadata = this.enablePublicSpace ? { public: this.wasm.makeSpaceId(address, chainId, "public") } : void 0;
    const tinyCloudSession = {
      address,
      chainId,
      sessionKey: keyId,
      spaceId,
      spaces: spacesMetadata,
      delegationCid: session.delegationCid,
      delegationHeader: session.delegationHeader,
      verificationMethod: this.sessionManager.getDID(keyId),
      jwk,
      siwe: prepared.siwe,
      signature
    };
    const persistedData = {
      address,
      chainId,
      sessionKey: JSON.stringify(jwk),
      siwe: prepared.siwe,
      signature,
      tinycloudSession: {
        delegationHeader: session.delegationHeader,
        delegationCid: session.delegationCid,
        spaceId,
        spaces: spacesMetadata,
        verificationMethod: this.sessionManager.getDID(keyId)
      },
      expiresAt: expirationTime.toISOString(),
      createdAt: now.toISOString(),
      version: "1.0"
    };
    await this.sessionStorage.save(address, persistedData);
    this._session = clientSession;
    this._tinyCloudSession = tinyCloudSession;
    this._address = address;
    this._chainId = chainId;
    const nodeInfo = await checkNodeInfo(
      this.tinycloudHosts[0],
      this.wasm.protocolVersion()
    );
    this._nodeFeatures = nodeInfo.features;
    for (const ext of this.extensions) {
      if (ext.afterSignIn) {
        await ext.afterSignIn(clientSession);
      }
    }
    await this.ensureSpaceExists();
    return clientSession;
  }
  /**
   * Sign out and clear the current session.
   */
  async signOut() {
    if (this._address) {
      await this.clearPersistedSession(this._address);
    }
    this._session = void 0;
  }
  /**
   * Get the current wallet/signer address.
   */
  address() {
    return this._address;
  }
  /**
   * Get the current chain ID.
   */
  chainId() {
    return this._chainId;
  }
  /**
   * Sign a message with the connected signer.
   */
  async signMessage(message) {
    if (!this._address) {
      this._address = await this.signer.getAddress();
    }
    if (!this._chainId) {
      this._chainId = await this.signer.getChainId();
    }
    return this.requestSignature({
      address: this._address,
      chainId: this._chainId,
      message,
      type: "message"
    });
  }
  /**
   * Prepare a session for external signing.
   *
   * Use this method when you need to sign the SIWE message externally (e.g., via
   * a hardware wallet, multi-sig, or external service). After obtaining the signature,
   * call `signInWithPreparedSession()` to complete the sign-in.
   *
   * @example
   * ```typescript
   * const { prepared, keyId, jwk } = await auth.prepareSessionForSigning();
   * const signature = await externalSigner.signMessage(prepared.siwe);
   * const session = await auth.signInWithPreparedSession(prepared, signature, keyId, jwk);
   * ```
   */
  async prepareSessionForSigning() {
    const address = this.wasm.ensureEip55(await this.signer.getAddress());
    const chainId = await this.signer.getChainId();
    const keyId = `session-${Date.now()}`;
    this.sessionManager.renameSessionKeyId("default", keyId);
    const jwkString = this.sessionManager.jwk(keyId);
    if (!jwkString) {
      throw new Error("Failed to create session key");
    }
    const jwk = JSON.parse(jwkString);
    const spaceId = this.wasm.makeSpaceId(address, chainId, this.spacePrefix);
    const now = /* @__PURE__ */ new Date();
    const expirationTime = new Date(now.getTime() + this.sessionExpirationMs);
    const prepared = this.wasm.prepareSession({
      abilities: this.resolveSignInAbilities(),
      address,
      chainId,
      domain: this.domain,
      issuedAt: now.toISOString(),
      expirationTime: expirationTime.toISOString(),
      spaceId,
      jwk,
      ...this.buildSiweOverrides()
    });
    return {
      prepared,
      keyId,
      jwk,
      address,
      chainId
    };
  }
  /**
   * Complete sign-in with a prepared session and signature.
   *
   * Use this method after obtaining a signature for the SIWE message from
   * `prepareSessionForSigning()`. The signature MUST be over `prepared.siwe`.
   *
   * @param prepared - The prepared session from `prepareSessionForSigning()`
   * @param signature - The signature over `prepared.siwe`
   * @param keyId - The session key ID from `prepareSessionForSigning()`
   * @param jwk - The JWK from `prepareSessionForSigning()`
   */
  async signInWithPreparedSession(prepared, signature, keyId, jwk) {
    const session = this.wasm.completeSessionSetup({
      ...prepared,
      signature
    });
    const address = this.wasm.ensureEip55(await this.signer.getAddress());
    const chainId = await this.signer.getChainId();
    const clientSession = {
      address,
      walletAddress: address,
      chainId,
      sessionKey: keyId,
      siwe: prepared.siwe,
      signature
    };
    const spacesMetadata = this.enablePublicSpace ? { public: this.wasm.makeSpaceId(address, chainId, "public") } : void 0;
    const tinyCloudSession = {
      address,
      chainId,
      sessionKey: keyId,
      spaceId: prepared.spaceId,
      spaces: spacesMetadata,
      delegationCid: session.delegationCid,
      delegationHeader: session.delegationHeader,
      verificationMethod: this.sessionManager.getDID(keyId),
      jwk,
      siwe: prepared.siwe,
      signature
    };
    const expirationMatch = prepared.siwe.match(/Expiration Time: (.+)/);
    const issuedAtMatch = prepared.siwe.match(/Issued At: (.+)/);
    const expiresAt = expirationMatch?.[1] ?? new Date(Date.now() + this.sessionExpirationMs).toISOString();
    const createdAt = issuedAtMatch?.[1] ?? (/* @__PURE__ */ new Date()).toISOString();
    const persistedData = {
      address,
      chainId,
      sessionKey: JSON.stringify(jwk),
      siwe: prepared.siwe,
      signature,
      tinycloudSession: {
        delegationHeader: session.delegationHeader,
        delegationCid: session.delegationCid,
        spaceId: prepared.spaceId,
        spaces: spacesMetadata,
        verificationMethod: this.sessionManager.getDID(keyId)
      },
      expiresAt,
      createdAt,
      version: "1.0"
    };
    await this.sessionStorage.save(address, persistedData);
    this._session = clientSession;
    this._tinyCloudSession = tinyCloudSession;
    this._address = address;
    this._chainId = chainId;
    const nodeInfo = await checkNodeInfo(
      this.tinycloudHosts[0],
      this.wasm.protocolVersion()
    );
    this._nodeFeatures = nodeInfo.features;
    for (const ext of this.extensions) {
      if (ext.afterSignIn) {
        await ext.afterSignIn(clientSession);
      }
    }
    await this.ensureSpaceExists();
    return clientSession;
  }
  /**
   * Clear persisted session data.
   */
  async clearPersistedSession(address) {
    const targetAddress = address ?? this._address;
    if (targetAddress) {
      await this.sessionStorage.clear(targetAddress);
    }
  }
  /**
   * Check if a session is persisted for an address.
   */
  isSessionPersisted(address) {
    return this.sessionStorage.exists(address);
  }
  /**
   * Request a signature based on the configured strategy.
   */
  async requestSignature(request) {
    switch (this.signStrategy.type) {
      case "auto-sign":
        return this.signer.signMessage(request.message);
      case "auto-reject":
        throw new Error("Sign request rejected by auto-reject strategy");
      case "callback": {
        const response = await this.signStrategy.handler(request);
        if (!response.approved) {
          throw new Error(
            response.reason ?? "Sign request rejected by callback"
          );
        }
        return response.signature ?? await this.signer.signMessage(request.message);
      }
      case "event-emitter": {
        return this.requestSignatureViaEmitter(
          request,
          this.signStrategy.emitter,
          this.signStrategy.timeout ?? 6e4
        );
      }
      default:
        throw new Error(
          `Unknown sign strategy: ${this.signStrategy.type}`
        );
    }
  }
  /**
   * Request signature via event emitter with timeout.
   */
  requestSignatureViaEmitter(request, emitter, timeout) {
    return new Promise((resolve, reject) => {
      const timeoutId = setTimeout(() => {
        reject(new Error("Sign request timed out"));
      }, timeout);
      const respond = async (response) => {
        clearTimeout(timeoutId);
        if (!response.approved) {
          reject(
            new Error(response.reason ?? "Sign request rejected via emitter")
          );
        } else {
          const signature = response.signature ?? await this.signer.signMessage(request.message);
          resolve(signature);
        }
      };
      emitter.emit("sign-request", request, respond);
    });
  }
};

// src/TinyCloudNode.ts
import {
  TinyCloud,
  activateSessionWithHost as activateSessionWithHost2,
  KVService as KVService2,
  SQLService as SQLService2,
  DuckDbService as DuckDbService2,
  HooksService as HooksService2,
  DataVaultService,
  createVaultCrypto,
  ServiceContext as ServiceContext2,
  SilentNotificationHandler,
  DelegationManager,
  SpaceService,
  CapabilityKeyRegistry,
  SharingService,
  UnsupportedFeatureError,
  makePublicSpaceId,
  PermissionNotInManifestError,
  SessionExpiredError,
  expandActionShortNames,
  isCapabilitySubset,
  parseRecapCapabilities,
  SERVICE_LONG_TO_SHORT
} from "@tinycloud/sdk-core";

// src/DelegatedAccess.ts
import {
  KVService,
  HooksService,
  SQLService,
  DuckDbService,
  ServiceContext
} from "@tinycloud/sdk-core";
var DelegatedAccess = class {
  constructor(session, delegation, host, invoke) {
    this.session = session;
    this._delegation = delegation;
    this.host = host;
    this._serviceContext = new ServiceContext({
      invoke,
      fetch: globalThis.fetch.bind(globalThis),
      hosts: [host]
    });
    const prefix = this._delegation.path.replace(/\/$/, "");
    this._kv = new KVService({ prefix });
    this._kv.initialize(this._serviceContext);
    this._serviceContext.registerService("kv", this._kv);
    this._sql = new SQLService({});
    this._sql.initialize(this._serviceContext);
    this._serviceContext.registerService("sql", this._sql);
    this._duckdb = new DuckDbService({});
    this._duckdb.initialize(this._serviceContext);
    this._serviceContext.registerService("duckdb", this._duckdb);
    this._hooks = new HooksService({});
    this._hooks.initialize(this._serviceContext);
    this._serviceContext.registerService("hooks", this._hooks);
    const serviceSession = {
      delegationHeader: session.delegationHeader,
      delegationCid: session.delegationCid,
      spaceId: session.spaceId,
      verificationMethod: session.verificationMethod,
      jwk: session.jwk
    };
    this._serviceContext.setSession(serviceSession);
  }
  /**
   * Get the delegation this access was created from.
   */
  get delegation() {
    return this._delegation;
  }
  /**
   * The space ID this access is for.
   */
  get spaceId() {
    return this._delegation.spaceId;
  }
  /**
   * The path this access is scoped to.
   */
  get path() {
    return this._delegation.path;
  }
  /**
   * KV operations on the delegated space.
   */
  get kv() {
    return this._kv;
  }
  /**
   * SQL operations on the delegated space.
   */
  get sql() {
    return this._sql;
  }
  /**
   * DuckDB operations on the delegated space.
   */
  get duckdb() {
    return this._duckdb;
  }
  /**
   * Hooks write-stream subscriptions on the delegated space.
   */
  get hooks() {
    return this._hooks;
  }
};

// src/keys/WasmKeyProvider.ts
var WasmKeyProvider = class {
  /**
   * Create a new WasmKeyProvider.
   *
   * @param config - Configuration with the WASM session manager
   */
  constructor(config) {
    this.sessionManager = config.sessionManager;
  }
  /**
   * Generate a new session key with the given name.
   *
   * This creates a new Ed25519 key pair in the WASM session manager.
   * The key can then be used for signing delegations in sharing links.
   *
   * @param name - A unique name/ID for the key (e.g., "share:timestamp:random")
   * @returns The key ID (same as the name provided)
   */
  async createSessionKey(name) {
    return this.sessionManager.createSessionKey(name);
  }
  /**
   * Get the JWK (JSON Web Key) for a key.
   *
   * Returns the full JWK including the private key (d parameter),
   * which is required for signing and for embedding in sharing links.
   *
   * @param keyId - The key ID to retrieve
   * @returns The JWK object with public and private key components
   * @throws Error if the key is not found
   */
  getJWK(keyId) {
    const jwkJson = this.sessionManager.jwk(keyId);
    if (!jwkJson) {
      throw new Error(`Key not found: ${keyId}`);
    }
    return JSON.parse(jwkJson);
  }
  /**
   * Get the DID (Decentralized Identifier) for a key.
   *
   * Returns the did:key format DID derived from the key's public key.
   * This DID can be used as the delegatee in delegations.
   *
   * @param keyId - The key ID to retrieve
   * @returns The DID in did:key format (e.g., "did:key:z6Mk...")
   */
  async getDID(keyId) {
    return this.sessionManager.getDID(keyId);
  }
  /**
   * List all session keys currently held by the provider.
   *
   * @returns Array of key IDs
   */
  listKeys() {
    const keys = this.sessionManager.listSessionKeys?.();
    return Array.isArray(keys) ? keys : [];
  }
  /**
   * Check if a key exists in the provider.
   *
   * @param keyId - The key ID to check
   * @returns True if the key exists
   */
  hasKey(keyId) {
    const jwk = this.sessionManager.jwk(keyId);
    return jwk !== void 0;
  }
};
function createWasmKeyProvider(sessionManager) {
  return new WasmKeyProvider({ sessionManager });
}

// src/delegateToHelpers.ts
import {
  parseExpiry,
  SiweMessage
} from "@tinycloud/sdk-core";
function legacyParamsToPermissionEntries(actions, path, spaceIdOverride) {
  const byService = /* @__PURE__ */ new Map();
  for (const a of actions) {
    const slashIdx = a.indexOf("/");
    if (slashIdx === -1) {
      continue;
    }
    const service = a.slice(0, slashIdx);
    if (!service.startsWith("tinycloud.")) {
      continue;
    }
    const list = byService.get(service);
    if (list === void 0) {
      byService.set(service, [a]);
    } else {
      list.push(a);
    }
  }
  const space = spaceIdOverride ?? "default";
  const entries = [];
  for (const [service, actionList] of byService) {
    entries.push({
      service,
      space,
      path,
      actions: actionList
    });
  }
  return entries;
}
function resolveExpiryMs(expiry) {
  if (expiry === void 0) {
    return 60 * 60 * 1e3;
  }
  if (typeof expiry === "number") {
    if (!Number.isFinite(expiry) || expiry <= 0) {
      throw new Error(
        `delegateTo expiry must be a positive finite number (got ${expiry})`
      );
    }
    return expiry;
  }
  return parseExpiry(expiry);
}
function extractSiweExpiration(siwe) {
  const parsed = new SiweMessage(siwe);
  if (parsed.expirationTime === void 0 || parsed.expirationTime === null) {
    return void 0;
  }
  const d = new Date(parsed.expirationTime);
  if (Number.isNaN(d.getTime())) {
    throw new Error(
      `Session SIWE has unparseable expirationTime: ${parsed.expirationTime}`
    );
  }
  return d;
}

// src/TinyCloudNode.ts
var DEFAULT_HOST = "https://node.tinycloud.xyz";
var _TinyCloudNode = class _TinyCloudNode {
  /**
   * Create a new TinyCloudNode instance.
   *
   * All configuration is optional. Without a privateKey, the instance operates
   * in "session-only" mode where it can receive delegations but cannot create
   * its own space via signIn().
   *
   * @param config - Configuration options (all optional)
   *
   * @example
   * ```typescript
   * // Session-only mode - can receive delegations
   * const bob = new TinyCloudNode();
   * console.log(bob.did); // did:key:z6Mk... - available immediately
   *
   * // Wallet mode - can create own space
   * const alice = new TinyCloudNode({
   *   privateKey: process.env.ALICE_PRIVATE_KEY,
   *   prefix: "myapp",
   * });
   * await alice.signIn();
   * ```
   */
  constructor(config = {}) {
    this.signer = null;
    this.auth = null;
    this.tc = null;
    this._chainId = 1;
    this.config = {
      ...config,
      host: config.host ?? DEFAULT_HOST
    };
    if (config.wasmBindings) {
      this.wasmBindings = config.wasmBindings;
    } else if (_TinyCloudNode.nodeDefaults) {
      this.wasmBindings = _TinyCloudNode.nodeDefaults.createWasmBindings();
    } else {
      throw new Error(
        "wasmBindings must be provided in config. Import from '@tinycloud/node-sdk' (not '/core') for automatic Node.js defaults."
      );
    }
    this.sessionManager = this.wasmBindings.createSessionManager();
    const defaultKeyId = "default";
    let jwkStr = this.sessionManager.jwk(defaultKeyId);
    if (jwkStr) {
      this.sessionKeyId = defaultKeyId;
    } else {
      this.sessionKeyId = this.sessionManager.createSessionKey(defaultKeyId);
      jwkStr = this.sessionManager.jwk(this.sessionKeyId);
    }
    if (!jwkStr) {
      throw new Error("Failed to get session key JWK");
    }
    this.sessionKeyJwk = JSON.parse(jwkStr);
    this._capabilityRegistry = new CapabilityKeyRegistry();
    this._keyProvider = new WasmKeyProvider({
      sessionManager: this.sessionManager
    });
    this.notificationHandler = config.notificationHandler ?? new SilentNotificationHandler();
    this._sharingService = new SharingService({
      hosts: [this.config.host],
      // session: undefined - not needed for receive()
      invoke: this.wasmBindings.invoke,
      fetch: globalThis.fetch.bind(globalThis),
      keyProvider: this._keyProvider,
      registry: this._capabilityRegistry,
      // delegationManager: undefined - not needed for receive()
      createKVService: (config2) => {
        const prefix = config2.pathPrefix?.replace(/\/$/, "");
        const kvService = new KVService2({ prefix });
        const kvContext = new ServiceContext2({
          invoke: config2.invoke,
          fetch: config2.fetch ?? globalThis.fetch.bind(globalThis),
          hosts: config2.hosts
        });
        kvContext.setSession(config2.session);
        kvService.initialize(kvContext);
        return kvService;
      }
    });
    if (config.signer) {
      this.signer = config.signer;
      this.setupAuth(config);
    } else if (config.privateKey) {
      if (!_TinyCloudNode.nodeDefaults) {
        throw new Error(
          "privateKey requires PrivateKeySigner. Either provide a signer in config, or import from '@tinycloud/node-sdk' (not '/core') for automatic Node.js defaults."
        );
      }
      this.signer = _TinyCloudNode.nodeDefaults.createSigner(config.privateKey, this._chainId);
      this.setupAuth(config);
    }
  }
  /** @internal Register Node.js-specific defaults (NodeWasmBindings, PrivateKeySigner) */
  static registerNodeDefaults(defaults) {
    _TinyCloudNode.nodeDefaults = defaults;
  }
  get nodeFeatures() {
    return this.auth?.nodeFeatures ?? [];
  }
  /** SIWE domain — uses config override or defaults to app.tinycloud.xyz */
  get siweDomain() {
    return this.config.domain ?? "app.tinycloud.xyz";
  }
  /**
   * Set up authorization handler and TinyCloud instance.
   * @internal
   */
  setupAuth(config) {
    const host = this.config.host;
    this.auth = new NodeUserAuthorization({
      signer: this.signer,
      signStrategy: { type: "auto-sign" },
      wasmBindings: this.wasmBindings,
      sessionStorage: config.sessionStorage ?? new MemorySessionStorage(),
      domain: this.siweDomain,
      spacePrefix: config.prefix,
      sessionExpirationMs: config.sessionExpirationMs ?? 60 * 60 * 1e3,
      tinycloudHosts: [host],
      autoCreateSpace: config.autoCreateSpace,
      enablePublicSpace: config.enablePublicSpace ?? true,
      spaceCreationHandler: config.spaceCreationHandler,
      nonce: config.nonce,
      siweConfig: config.siweConfig,
      manifest: config.manifest
    });
    this.tc = new TinyCloud(this.auth, {
      invokeAny: this.wasmBindings.invokeAny
    });
  }
  /**
   * Install or replace the manifest that drives the SIWE recap at
   * sign-in. Takes effect on the next `signIn()` call — the current
   * session (if any) is not touched. Wire this up from a higher
   * layer (e.g. TinyCloudWeb.setManifest) so the manifest is kept
   * in sync across the stack.
   */
  setManifest(manifest) {
    if (!this.auth) {
      throw new Error(
        "setManifest requires wallet mode. Provide a signer or privateKey in the TinyCloudNode config."
      );
    }
    this.auth.setManifest(manifest);
  }
  /**
   * Return the manifest currently installed on the auth handler,
   * or `undefined` if none is set.
   */
  get manifest() {
    return this.auth?.manifest;
  }
  /**
   * Get the primary identity DID for this user.
   * - If wallet connected and signed in: returns PKH DID (did:pkh:eip155:{chainId}:{address})
   * - If session-only mode: returns session key DID (did:key:z6Mk...)
   *
   * Use this for delegations - it always returns the appropriate identity.
   */
  get did() {
    if (this._address) {
      return `did:pkh:eip155:${this._chainId}:${this._address}`;
    }
    return this.sessionManager.getDID(this.sessionKeyId);
  }
  /**
   * Get the session key DID. Always available.
   * Format: did:key:z6Mk...#z6Mk...
   *
   * Use this when you specifically need the session key, not the user identity.
   */
  get sessionDid() {
    return this.sessionManager.getDID(this.sessionKeyId);
  }
  /**
   * Get the Ethereum address for this user.
   */
  get address() {
    return this._address;
  }
  /**
   * Check if this instance is in session-only mode (no wallet).
   * In session-only mode, the instance can receive delegations but cannot
   * create its own space via signIn().
   */
  get isSessionOnly() {
    return this.signer === null;
  }
  /**
   * Get the space ID for this user.
   * Available after signIn().
   */
  get spaceId() {
    return this.auth?.tinyCloudSession?.spaceId;
  }
  /**
   * Get the current TinyCloud session.
   * Available after signIn().
   */
  get session() {
    return this.auth?.tinyCloudSession;
  }
  /**
   * Sign in and create a new session.
   * This creates the user's space if it doesn't exist.
   * Requires wallet mode (privateKey in config).
   *
   * @param options - Optional per-call SIWE overrides for this sign-in only
   */
  async signIn(options) {
    if (!this.signer || !this.tc) {
      throw new Error(
        "Cannot signIn() in session-only mode. Provide a privateKey in config to create your own space."
      );
    }
    await this.wasmBindings.ensureInitialized?.();
    this._address = await this.signer.getAddress();
    this._chainId = await this.signer.getChainId();
    this._kv = void 0;
    this._sql = void 0;
    this._duckdb = void 0;
    this._hooks = void 0;
    this._serviceContext = void 0;
    await this.tc.signIn(options);
    this.initializeServices();
    this.notificationHandler.success("Successfully signed in");
  }
  /**
   * Restore a previously established session from stored delegation data.
   *
   * This is used by the CLI to restore a session that was created via the
   * browser-based delegation flow (OpenKey `/delegate` page). Instead of
   * signing in with a private key, it injects the delegation data directly.
   *
   * @param sessionData - The stored delegation data from the browser flow
   */
  async restoreSession(sessionData) {
    await this.wasmBindings.ensureInitialized?.();
    this._kv = void 0;
    this._sql = void 0;
    this._duckdb = void 0;
    this._hooks = void 0;
    this._serviceContext = void 0;
    if (sessionData.address) {
      this._address = sessionData.address;
    }
    if (sessionData.chainId) {
      this._chainId = sessionData.chainId;
    }
    this._serviceContext = new ServiceContext2({
      invoke: this.wasmBindings.invoke,
      invokeAny: this.wasmBindings.invokeAny,
      fetch: globalThis.fetch.bind(globalThis),
      hosts: [this.config.host]
    });
    this._kv = new KVService2({});
    this._kv.initialize(this._serviceContext);
    this._serviceContext.registerService("kv", this._kv);
    this._sql = new SQLService2({});
    this._sql.initialize(this._serviceContext);
    this._serviceContext.registerService("sql", this._sql);
    this._duckdb = new DuckDbService2({});
    this._duckdb.initialize(this._serviceContext);
    this._serviceContext.registerService("duckdb", this._duckdb);
    this._hooks = new HooksService2({});
    this._hooks.initialize(this._serviceContext);
    this._serviceContext.registerService("hooks", this._hooks);
    const serviceSession = {
      delegationHeader: sessionData.delegationHeader,
      delegationCid: sessionData.delegationCid,
      spaceId: sessionData.spaceId,
      verificationMethod: sessionData.verificationMethod,
      jwk: sessionData.jwk
    };
    this._serviceContext.setSession(serviceSession);
    const wasm = this.wasmBindings;
    const vaultCrypto = createVaultCrypto({
      vault_encrypt: wasm.vault_encrypt,
      vault_decrypt: wasm.vault_decrypt,
      vault_derive_key: wasm.vault_derive_key,
      vault_x25519_from_seed: wasm.vault_x25519_from_seed,
      vault_x25519_dh: wasm.vault_x25519_dh,
      vault_random_bytes: wasm.vault_random_bytes,
      vault_sha256: wasm.vault_sha256
    });
    const self = this;
    this._vault = new DataVaultService({
      spaceId: sessionData.spaceId,
      crypto: vaultCrypto,
      tc: {
        kv: this._kv,
        ensurePublicSpace: async () => {
          try {
            await self.ensurePublicSpace();
            return { ok: true, data: void 0 };
          } catch (error) {
            return { ok: false, error: { code: "STORAGE_ERROR", message: error instanceof Error ? error.message : String(error), service: "vault" } };
          }
        },
        get publicKV() {
          return self._publicKV ?? self.tc.publicKV;
        },
        readPublicSpace: (host, spaceId, key) => TinyCloud.readPublicSpace(host, spaceId, key),
        makePublicSpaceId: TinyCloud.makePublicSpaceId,
        did: this.did,
        address: sessionData.address ?? this._address ?? "",
        chainId: sessionData.chainId ?? this._chainId,
        hosts: [this.config.host]
      }
    });
    this._vault.initialize(this._serviceContext);
    this._serviceContext.registerService("vault", this._vault);
    this.initializeV2Services(serviceSession);
  }
  /**
   * Connect a wallet to upgrade from session-only mode to wallet mode.
   *
   * This allows a user who started in session-only mode to later connect
   * a wallet and gain the ability to create their own space.
   *
   * Note: This does NOT automatically sign in. Call signIn() after connecting
   * the wallet to create your space.
   *
   * @param privateKey - The Ethereum private key (hex string, no 0x prefix)
   * @param options - Optional configuration
   * @param options.prefix - Space name prefix (defaults to "default")
   *
   * @example
   * ```typescript
   * // Start in session-only mode
   * const node = new TinyCloudNode({ host: "https://node.tinycloud.xyz" });
   * console.log(node.did); // did:key:z6Mk... (session key)
   *
   * // Later, connect a wallet
   * node.connectWallet(privateKey);
   * await node.signIn();
   * console.log(node.did); // did:pkh:eip155:1:0x... (PKH)
   * ```
   */
  connectWallet(privateKey, options) {
    if (this.signer) {
      throw new Error("Wallet already connected. Cannot connect another wallet.");
    }
    const prefix = options?.prefix ?? "default";
    const host = this.config.host;
    if (!_TinyCloudNode.nodeDefaults) {
      throw new Error(
        "connectWallet() requires PrivateKeySigner. Use connectSigner() instead, or import from '@tinycloud/node-sdk' (not '/core') for automatic Node.js defaults."
      );
    }
    this.signer = _TinyCloudNode.nodeDefaults.createSigner(privateKey);
    this.auth = new NodeUserAuthorization({
      signer: this.signer,
      signStrategy: { type: "auto-sign" },
      wasmBindings: this.wasmBindings,
      sessionStorage: options?.sessionStorage ?? this.config.sessionStorage ?? new MemorySessionStorage(),
      domain: this.siweDomain,
      spacePrefix: prefix,
      sessionExpirationMs: this.config.sessionExpirationMs ?? 60 * 60 * 1e3,
      tinycloudHosts: [host],
      autoCreateSpace: this.config.autoCreateSpace,
      enablePublicSpace: this.config.enablePublicSpace ?? true,
      spaceCreationHandler: this.config.spaceCreationHandler,
      nonce: this.config.nonce,
      siweConfig: this.config.siweConfig
    });
    this.tc = new TinyCloud(this.auth, {
      invokeAny: this.wasmBindings.invokeAny
    });
    this.config.prefix = prefix;
  }
  /**
   * Connect any ISigner to upgrade from session-only mode to wallet mode.
   *
   * Same as connectWallet() but accepts any ISigner implementation instead
   * of a raw private key string. Use this for browser wallets, hardware wallets,
   * or custom signing backends.
   *
   * Note: This does NOT automatically sign in. Call signIn() after connecting.
   *
   * @param signer - Any ISigner implementation
   * @param options - Optional configuration
   * @param options.prefix - Space name prefix (defaults to "default")
   */
  connectSigner(signer, options) {
    if (this.signer) {
      throw new Error("Signer already connected. Cannot connect another signer.");
    }
    const prefix = options?.prefix ?? "default";
    const host = this.config.host;
    this.signer = signer;
    this.auth = new NodeUserAuthorization({
      signer: this.signer,
      signStrategy: { type: "auto-sign" },
      wasmBindings: this.wasmBindings,
      sessionStorage: options?.sessionStorage ?? this.config.sessionStorage ?? new MemorySessionStorage(),
      domain: this.siweDomain,
      spacePrefix: prefix,
      sessionExpirationMs: this.config.sessionExpirationMs ?? 60 * 60 * 1e3,
      tinycloudHosts: [host],
      autoCreateSpace: this.config.autoCreateSpace,
      enablePublicSpace: this.config.enablePublicSpace ?? true,
      spaceCreationHandler: this.config.spaceCreationHandler,
      nonce: this.config.nonce,
      siweConfig: this.config.siweConfig
    });
    this.tc = new TinyCloud(this.auth, {
      invokeAny: this.wasmBindings.invokeAny
    });
    this.config.prefix = prefix;
  }
  /**
   * Initialize the service context and KV service after sign-in.
   * @internal
   */
  initializeServices() {
    const session = this.auth?.tinyCloudSession;
    if (!session) {
      return;
    }
    this.tc.initializeServices(this.wasmBindings.invoke, [this.config.host]);
    this._serviceContext = new ServiceContext2({
      invoke: this.wasmBindings.invoke,
      invokeAny: this.wasmBindings.invokeAny,
      fetch: globalThis.fetch.bind(globalThis),
      hosts: [this.config.host]
    });
    this._kv = new KVService2({});
    this._kv.initialize(this._serviceContext);
    this._serviceContext.registerService("kv", this._kv);
    const features = this.nodeFeatures;
    if (features.length === 0 || features.includes("sql")) {
      this._sql = new SQLService2({});
      this._sql.initialize(this._serviceContext);
      this._serviceContext.registerService("sql", this._sql);
    }
    if (features.length === 0 || features.includes("duckdb")) {
      this._duckdb = new DuckDbService2({});
      this._duckdb.initialize(this._serviceContext);
      this._serviceContext.registerService("duckdb", this._duckdb);
    }
    this._hooks = new HooksService2({});
    this._hooks.initialize(this._serviceContext);
    this._serviceContext.registerService("hooks", this._hooks);
    const serviceSession = {
      delegationHeader: session.delegationHeader,
      delegationCid: session.delegationCid,
      spaceId: session.spaceId,
      verificationMethod: session.verificationMethod,
      jwk: session.jwk
    };
    this._serviceContext.setSession(serviceSession);
    this.tc.serviceContext.setSession(serviceSession);
    const wasm = this.wasmBindings;
    const vaultCrypto = createVaultCrypto({
      vault_encrypt: wasm.vault_encrypt,
      vault_decrypt: wasm.vault_decrypt,
      vault_derive_key: wasm.vault_derive_key,
      vault_x25519_from_seed: wasm.vault_x25519_from_seed,
      vault_x25519_dh: wasm.vault_x25519_dh,
      vault_random_bytes: wasm.vault_random_bytes,
      vault_sha256: wasm.vault_sha256
    });
    const self = this;
    this._vault = new DataVaultService({
      spaceId: session.spaceId,
      crypto: vaultCrypto,
      tc: {
        kv: this._kv,
        ensurePublicSpace: async () => {
          try {
            await self.ensurePublicSpace();
            return { ok: true, data: void 0 };
          } catch (error) {
            return { ok: false, error: { code: "STORAGE_ERROR", message: error instanceof Error ? error.message : String(error), service: "vault" } };
          }
        },
        get publicKV() {
          return self._publicKV ?? self.tc.publicKV;
        },
        readPublicSpace: (host, spaceId, key) => TinyCloud.readPublicSpace(host, spaceId, key),
        makePublicSpaceId: TinyCloud.makePublicSpaceId,
        did: this.did,
        address: this._address,
        chainId: this._chainId,
        hosts: [this.config.host]
      }
    });
    this._vault.initialize(this._serviceContext);
    this._serviceContext.registerService("vault", this._vault);
    this.initializeV2Services(serviceSession);
  }
  /**
   * Initialize the v2 delegation system services.
   * @internal
   */
  initializeV2Services(serviceSession) {
    this._capabilityRegistry = new CapabilityKeyRegistry();
    const tcSession = this.auth?.tinyCloudSession;
    if (tcSession && this._address) {
      const sessionKey = {
        id: tcSession.sessionKey,
        did: tcSession.verificationMethod,
        type: "session",
        // Cast jwk from generic object to JWK - we know it has the required structure
        jwk: tcSession.jwk,
        priority: 0
        // Session keys have highest priority
      };
      const rootDelegation = {
        cid: tcSession.delegationCid,
        delegateDID: tcSession.verificationMethod,
        spaceId: tcSession.spaceId,
        path: "",
        // Root access
        actions: [
          "tinycloud.kv/put",
          "tinycloud.kv/get",
          "tinycloud.kv/del",
          "tinycloud.kv/list",
          "tinycloud.kv/metadata",
          "tinycloud.sql/read",
          "tinycloud.sql/write",
          "tinycloud.sql/admin",
          "tinycloud.sql/*",
          "tinycloud.duckdb/read",
          "tinycloud.duckdb/write",
          "tinycloud.duckdb/admin",
          "tinycloud.duckdb/describe",
          "tinycloud.duckdb/export",
          "tinycloud.duckdb/import",
          "tinycloud.duckdb/*"
        ],
        expiry: this.getSessionExpiry(),
        isRevoked: false,
        allowSubDelegation: true
      };
      const delegations = [rootDelegation];
      if (tcSession.spaces) {
        for (const [spaceName, spaceId] of Object.entries(tcSession.spaces)) {
          delegations.push({
            cid: tcSession.delegationCid,
            delegateDID: tcSession.verificationMethod,
            spaceId,
            path: "",
            actions: [
              "tinycloud.kv/put",
              "tinycloud.kv/get",
              "tinycloud.kv/del",
              "tinycloud.kv/list",
              "tinycloud.kv/metadata",
              "tinycloud.sql/read",
              "tinycloud.sql/write",
              "tinycloud.sql/admin",
              "tinycloud.sql/*",
              "tinycloud.duckdb/read",
              "tinycloud.duckdb/write",
              "tinycloud.duckdb/admin",
              "tinycloud.duckdb/describe",
              "tinycloud.duckdb/export",
              "tinycloud.duckdb/import",
              "tinycloud.duckdb/*"
            ],
            expiry: this.getSessionExpiry(),
            isRevoked: false,
            allowSubDelegation: true
          });
        }
      }
      this._capabilityRegistry.registerKey(sessionKey, delegations);
    }
    this._delegationManager = new DelegationManager({
      hosts: [this.config.host],
      session: serviceSession,
      invoke: this.wasmBindings.invoke,
      fetch: globalThis.fetch.bind(globalThis)
    });
    this._spaceService = new SpaceService({
      hosts: [this.config.host],
      session: serviceSession,
      invoke: this.wasmBindings.invoke,
      fetch: globalThis.fetch.bind(globalThis),
      capabilityRegistry: this._capabilityRegistry,
      userDid: this.did,
      createKVService: (spaceId) => {
        const kvService = new KVService2({});
        if (this._serviceContext) {
          const spaceScopedContext = new ServiceContext2({
            invoke: this._serviceContext.invoke,
            fetch: this._serviceContext.fetch,
            hosts: this._serviceContext.hosts
          });
          const session = this._serviceContext.session;
          if (session) {
            spaceScopedContext.setSession({ ...session, spaceId });
          }
          kvService.initialize(spaceScopedContext);
        }
        return kvService;
      },
      // Enable space.delegations.create() via SIWE-based delegation
      createDelegation: async (params) => {
        try {
          const portableDelegation = await this.createDelegation({
            delegateDID: params.delegateDID,
            path: params.path,
            actions: params.actions,
            disableSubDelegation: params.disableSubDelegation,
            expiryMs: params.expiry ? params.expiry.getTime() - Date.now() : void 0
          });
          const delegation = {
            cid: portableDelegation.cid,
            delegateDID: portableDelegation.delegateDID,
            delegatorDID: this.did,
            spaceId: portableDelegation.spaceId,
            path: portableDelegation.path,
            actions: portableDelegation.actions,
            expiry: portableDelegation.expiry,
            isRevoked: false,
            allowSubDelegation: !portableDelegation.disableSubDelegation,
            createdAt: /* @__PURE__ */ new Date(),
            authHeader: portableDelegation.delegationHeader.Authorization
          };
          return { ok: true, data: delegation };
        } catch (error) {
          return {
            ok: false,
            error: {
              code: "CREATION_FAILED",
              message: error instanceof Error ? error.message : String(error),
              service: "delegation"
            }
          };
        }
      }
    });
    this._sharingService.updateConfig({
      session: serviceSession,
      delegationManager: this._delegationManager,
      sessionExpiry: this.getSessionExpiry(),
      // WASM-based delegation creation (preferred - no server roundtrip)
      createDelegationWasm: (params) => this.createDelegationWrapper(params),
      // Root delegation for long-lived share links (bypasses session expiry)
      // In node-sdk we have direct signer access, so no popup needed
      onRootDelegationNeeded: this.signer ? async (params) => this.createRootDelegationForSharing(params) : void 0
    });
    this._spaceService.updateConfig({
      sharingService: this._sharingService
    });
  }
  /**
   * Get the session expiry time.
   * @internal
   */
  getSessionExpiry() {
    const expirationMs = this.config.sessionExpirationMs ?? 60 * 60 * 1e3;
    return new Date(Date.now() + expirationMs);
  }
  /**
   * Wrapper for the WASM createDelegation function.
   *
   * The WASM call now takes a multi-resource `abilities` map
   * (matching `prepareSession`'s shape) and emits ONE UCAN that
   * covers every `(service, path, actions)` entry. We mirror the raw
   * result back through `CreateDelegationWasmResult`, converting the
   * seconds-since-epoch `expiry` to a Date and normalizing the
   * `delegateDid` → `delegateDID` case.
   *
   * Both SharingService (single-entry) and
   * {@link TinyCloudNode.delegateTo} (multi-entry) drive this through
   * the same code path so there's exactly one place that touches the
   * WASM boundary.
   *
   * @internal
   */
  createDelegationWrapper(params) {
    const wasmSession = {
      delegationHeader: params.session.delegationHeader,
      delegationCid: params.session.delegationCid,
      jwk: params.session.jwk,
      spaceId: params.session.spaceId,
      verificationMethod: params.session.verificationMethod
    };
    const result = this.wasmBindings.createDelegation(
      wasmSession,
      params.delegateDID,
      params.spaceId,
      params.abilities,
      params.expirationSecs,
      params.notBeforeSecs
    );
    return {
      delegation: result.delegation,
      cid: result.cid,
      // Rust serde `rename_all = "camelCase"` emits `delegateDid`
      // (lowercase d); the TypeScript interface uses `delegateDID`
      // (historical, matches Delegation.delegateDID). Normalize here.
      delegateDID: result.delegateDid ?? result.delegateDID,
      expiry: new Date(result.expiry * 1e3),
      resources: result.resources
    };
  }
  /**
   * Create a direct root delegation from the wallet to a share key.
   * This bypasses the session delegation chain, allowing share links
   * with expiry longer than the current session.
   * @internal
   */
  async createRootDelegationForSharing(params) {
    if (!this.signer) {
      return void 0;
    }
    const session = this.auth?.tinyCloudSession;
    if (!session) {
      return void 0;
    }
    try {
      const host = this.config.host;
      const now = /* @__PURE__ */ new Date();
      const abilities = {
        kv: {
          [params.path]: params.actions
        }
      };
      const prepared = this.wasmBindings.prepareSession({
        abilities,
        address: this.wasmBindings.ensureEip55(session.address),
        chainId: session.chainId,
        domain: this.siweDomain,
        issuedAt: now.toISOString(),
        expirationTime: params.requestedExpiry.toISOString(),
        spaceId: params.spaceId,
        delegateUri: params.shareKeyDID
      });
      const signature = await this.signer.signMessage(prepared.siwe);
      const delegationSession = this.wasmBindings.completeSessionSetup({
        ...prepared,
        signature
      });
      const activateResult = await activateSessionWithHost2(
        host,
        delegationSession.delegationHeader
      );
      if (!activateResult.success) {
        return void 0;
      }
      return {
        cid: delegationSession.delegationCid,
        delegateDID: params.shareKeyDID,
        delegatorDID: `did:pkh:eip155:${session.chainId}:${session.address}`,
        spaceId: params.spaceId,
        path: params.path,
        actions: params.actions,
        expiry: params.requestedExpiry,
        isRevoked: false,
        allowSubDelegation: true,
        createdAt: now,
        authHeader: delegationSession.delegationHeader.Authorization
      };
    } catch {
      return void 0;
    }
  }
  /**
   * Track a received delegation in the capability registry.
   * @internal
   */
  trackReceivedDelegation(delegation, jwk) {
    if (!this._capabilityRegistry) {
      return;
    }
    const keyInfo = {
      id: `received:${delegation.cid}`,
      did: this.sessionDid,
      type: "ingested",
      jwk,
      priority: 2
    };
    const delegationRecord = {
      cid: delegation.cid,
      delegateDID: delegation.delegateDID,
      spaceId: delegation.spaceId,
      path: delegation.path,
      actions: delegation.actions,
      expiry: delegation.expiry,
      isRevoked: false,
      allowSubDelegation: !delegation.disableSubDelegation
    };
    this._capabilityRegistry.ingestKey(keyInfo, delegationRecord);
  }
  /**
   * Key-value storage operations on this user's space.
   */
  get kv() {
    if (!this._kv) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    return this._kv;
  }
  /**
   * SQL database operations on this user's space.
   */
  get sql() {
    if (!this._sql) {
      const features = this.nodeFeatures;
      if (features.length > 0 && !features.includes("sql")) {
        throw new UnsupportedFeatureError("sql", this.config.host, features);
      }
      throw new Error("Not signed in. Call signIn() first.");
    }
    return this._sql;
  }
  /**
   * DuckDB database operations on this user's space.
   */
  get duckdb() {
    if (!this._duckdb) {
      const features = this.nodeFeatures;
      if (features.length > 0 && !features.includes("duckdb")) {
        throw new UnsupportedFeatureError("duckdb", this.config.host, features);
      }
      throw new Error("Not signed in. Call signIn() first.");
    }
    return this._duckdb;
  }
  /**
   * Data Vault operations - client-side encrypted KV storage.
   * Call `vault.unlock(signer)` after signIn() to derive encryption keys.
   */
  get vault() {
    if (!this._vault) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    return this._vault;
  }
  /**
   * Hooks write stream subscription API.
   */
  get hooks() {
    if (!this._hooks) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    return this._hooks;
  }
  // ===========================================================================
  // v2 Service Accessors
  // ===========================================================================
  /**
   * Get the CapabilityKeyRegistry for managing keys and their capabilities.
   *
   * The registry tracks keys (session, main, ingested) and their associated
   * delegations, enabling automatic key selection for operations.
   *
   * @example
   * ```typescript
   * const registry = alice.capabilityRegistry;
   *
   * // Get the best key for an operation
   * const key = registry.getKeyForCapability(
   *   "tinycloud://my-space/kv/data",
   *   "tinycloud.kv/get"
   * );
   *
   * // List all capabilities
   * const capabilities = registry.getAllCapabilities();
   * ```
   */
  get capabilityRegistry() {
    if (!this._capabilityRegistry) {
      throw new Error("CapabilityKeyRegistry not initialized.");
    }
    return this._capabilityRegistry;
  }
  /**
   * Access received delegations (recipient view).
   *
   * Use this to see what delegations have been received via useDelegation().
   *
   * @example
   * ```typescript
   * // List all received delegations
   * const received = bob.delegations.list();
   * console.log("I have access to:", received.length, "spaces");
   *
   * // Get a specific delegation by CID
   * const delegation = bob.delegations.get(cid);
   * ```
   */
  get delegations() {
    const registry = this._capabilityRegistry;
    if (!registry) {
      return {
        list: () => [],
        get: () => void 0
      };
    }
    return {
      list: () => registry.getAllCapabilities().map((entry) => entry.delegation),
      get: (cid) => {
        const capabilities = registry.getAllCapabilities();
        const entry = capabilities.find((e) => e.delegation.cid === cid);
        return entry?.delegation;
      }
    };
  }
  /**
   * Get the DelegationManager for delegation CRUD operations.
   *
   * This is the v2 delegation service providing a cleaner API than
   * the legacy createDelegation/useDelegation methods.
   *
   * @example
   * ```typescript
   * const delegations = alice.delegationManager;
   *
   * // Create a delegation
   * const result = await delegations.create({
   *   delegateDID: bob.did,
   *   path: "shared/",
   *   actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
   *   expiry: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
   * });
   *
   * // List delegations
   * const listResult = await delegations.list();
   *
   * // Revoke a delegation
   * await delegations.revoke(delegationCid);
   * ```
   */
  get delegationManager() {
    if (!this._delegationManager) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    return this._delegationManager;
  }
  /**
   * Get the SpaceService for managing spaces.
   *
   * The SpaceService provides access to owned and delegated spaces,
   * including space creation, listing, and scoped operations.
   *
   * @example
   * ```typescript
   * const spaces = alice.spaces;
   *
   * // List all accessible spaces
   * const result = await spaces.list();
   *
   * // Create a new space
   * const createResult = await spaces.create('photos');
   *
   * // Get a space object for operations
   * const mySpace = spaces.get('default');
   * await mySpace.kv.put('key', 'value');
   *
   * // Check if a space exists
   * const exists = await spaces.exists('photos');
   * ```
   */
  get spaces() {
    if (!this._spaceService) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    return this._spaceService;
  }
  /**
   * Alias for `spaces` - get the SpaceService.
   * @see spaces
   */
  get spaceService() {
    return this.spaces;
  }
  /**
   * Get the SharingService for creating and receiving v2 sharing links.
   *
   * The SharingService creates sharing links with embedded private keys,
   * allowing recipients to exercise delegations without prior session setup.
   *
   * @example
   * ```typescript
   * const sharing = alice.sharing;
   *
   * // Generate a sharing link
   * const result = await sharing.generate({
   *   path: "/kv/documents/report.pdf",
   *   actions: ["tinycloud.kv/get"],
   *   expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
   * });
   *
   * if (result.ok) {
   *   console.log("Share URL:", result.data.url);
   *   // Send the URL to the recipient
   * }
   *
   * // Receive a sharing link
   * const receiveResult = await sharing.receive(shareUrl);
   * if (receiveResult.ok) {
   *   // Use the pre-configured KV service
   *   const data = await receiveResult.data.kv.get("report.pdf");
   * }
   * ```
   */
  get sharing() {
    return this._sharingService;
  }
  /**
   * Alias for `sharing` - get the SharingService.
   * @see sharing
   */
  get sharingService() {
    return this.sharing;
  }
  // ===========================================================================
  // Public Space Methods
  // ===========================================================================
  /**
   * Ensure the user's public space exists and is accessible.
   * Creates the space and activates a session delegation for it.
   * This is the trigger for lazy public space creation — call it
   * before writing to spaces.get('public').kv.
   */
  async ensurePublicSpace() {
    if (!this.auth || !this.session || !this.signer) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    const publicSpaceId = this.session.spaces?.public;
    if (!publicSpaceId) {
      throw new Error("Public space not enabled. Set enablePublicSpace: true in config.");
    }
    await this.auth.hostPublicSpace(publicSpaceId);
    const kvActions = [
      "tinycloud.kv/put",
      "tinycloud.kv/get",
      "tinycloud.kv/del",
      "tinycloud.kv/list",
      "tinycloud.kv/metadata"
    ];
    const abilities = { kv: { "": kvActions } };
    const now = /* @__PURE__ */ new Date();
    const expiryMs = 60 * 60 * 1e3;
    const expirationTime = new Date(now.getTime() + expiryMs);
    const prepared = this.wasmBindings.prepareSession({
      abilities,
      address: this.wasmBindings.ensureEip55(this.session.address),
      chainId: this.session.chainId,
      domain: this.siweDomain,
      issuedAt: now.toISOString(),
      expirationTime: expirationTime.toISOString(),
      spaceId: publicSpaceId,
      jwk: this.session.jwk,
      parents: [this.session.delegationCid]
    });
    const signature = await this.signer.signMessage(prepared.siwe);
    const delegationSession = this.wasmBindings.completeSessionSetup({
      ...prepared,
      signature
    });
    const activateResult = await activateSessionWithHost2(
      this.config.host,
      delegationSession.delegationHeader
    );
    if (!activateResult.success) {
      throw new Error(`Failed to activate public space delegation: ${activateResult.error}`);
    }
    if (this._capabilityRegistry && this.session) {
      const sessionKey = {
        id: this.session.sessionKey,
        did: this.session.verificationMethod,
        type: "session",
        jwk: this.session.jwk,
        priority: 0
      };
      this._capabilityRegistry.registerKey(sessionKey, [{
        cid: delegationSession.delegationCid,
        delegateDID: this.session.verificationMethod,
        spaceId: publicSpaceId,
        path: "",
        actions: kvActions,
        expiry: expirationTime,
        isRevoked: false,
        allowSubDelegation: true
      }]);
    }
    if (this._serviceContext) {
      const publicKV = new KVService2({ prefix: "" });
      const publicContext = new ServiceContext2({
        invoke: this.wasmBindings.invoke,
        fetch: this._serviceContext.fetch,
        hosts: this._serviceContext.hosts
      });
      publicContext.setSession({
        delegationHeader: delegationSession.delegationHeader,
        delegationCid: delegationSession.delegationCid,
        spaceId: publicSpaceId,
        verificationMethod: this.session.verificationMethod,
        jwk: this.session.jwk
      });
      publicKV.initialize(publicContext);
      this._publicKV = publicKV;
    }
  }
  /**
   * Get a KVService scoped to the user's own public space.
   * Writes require authentication (owner/delegate).
   */
  get publicKV() {
    if (this._publicKV) {
      return this._publicKV;
    }
    if (!this.tc) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    return this.tc.publicKV;
  }
  // ===========================================================================
  // v2 Delegation Convenience Methods
  // ===========================================================================
  /**
   * Create a delegation using the v2 DelegationManager.
   *
   * This is a convenience method that wraps DelegationManager.create().
   * For more control, use `this.delegationManager` directly.
   *
   * @param params - Delegation parameters
   * @returns Result containing the created Delegation
   *
   * @example
   * ```typescript
   * const result = await alice.delegate({
   *   delegateDID: bob.did,
   *   path: "shared/",
   *   actions: ["tinycloud.kv/get", "tinycloud.kv/put"],
   *   expiry: new Date(Date.now() + 24 * 60 * 60 * 1000),
   * });
   *
   * if (result.ok) {
   *   console.log("Delegation created:", result.data.cid);
   * }
   * ```
   */
  async delegate(params) {
    return this.delegationManager.create(params);
  }
  /**
   * Revoke a delegation using the v2 DelegationManager.
   *
   * @param cid - The CID of the delegation to revoke
   * @returns Result indicating success or failure
   */
  async revokeDelegation(cid) {
    return this.delegationManager.revoke(cid);
  }
  /**
   * List all delegations for the current session's space.
   *
   * @returns Result containing an array of Delegations
   */
  async listDelegations() {
    return this.delegationManager.list();
  }
  /**
   * Check if the current session has permission for a path and action.
   *
   * @param path - The resource path to check
   * @param action - The action to check (e.g., "tinycloud.kv/get")
   * @returns Result containing boolean permission status
   */
  async checkPermission(path, action) {
    return this.delegationManager.checkPermission(path, action);
  }
  /**
   * Issue a delegation using the capability-chain flow.
   *
   * When every requested permission is a subset of the current
   * session's recap, the delegation is signed by the session key via
   * WASM — no wallet prompt. When at least one is NOT derivable, a
   * {@link PermissionNotInManifestError} is raised (carrying the
   * missing entries) so the caller can trigger an escalation flow
   * (e.g. `TinyCloudWeb.requestPermissions`). Passing
   * `forceWalletSign: true` bypasses the derivability check and
   * always uses the wallet-signed SIWE path — used by the legacy
   * `createDelegation` fallback and by callers that want explicit
   * wallet confirmation.
   *
   * Multi-entry delegations are now emitted as **one** signed UCAN:
   * the underlying WASM `createDelegation` takes a full
   * `HashMap<Service, HashMap<Path, Vec<Ability>>>` abilities map
   * and produces a single attenuation carrying every
   * `(service, path, actions)` entry. The returned
   * {@link DelegateToResult.delegation} is that single blob, and
   * apps can POST it to their backend exactly like a single-entry
   * delegation (the server verifies all granted resources from one
   * UCAN).
   *
   * For single-entry requests the `PortableDelegation.path` and
   * `.actions` fields mirror the one granted entry. For
   * multi-entry requests they mirror the **first** entry (stable
   * lexicographic order from the Rust side); consumers that need
   * the full picture read `PortableDelegation.resources`.
   *
   * @throws {@link SessionExpiredError} when there is no session or
   *   the current session has expired (or will within the 60s
   *   safety margin).
   * @throws {@link PermissionNotInManifestError} when any requested
   *   entry is not a subset of the granted session capabilities and
   *   `forceWalletSign` is not set.
   */
  async delegateTo(did, permissions, options) {
    const session = this.auth?.tinyCloudSession;
    if (!session) {
      throw new SessionExpiredError(/* @__PURE__ */ new Date(0));
    }
    const sessionExpiry = extractSiweExpiration(session.siwe);
    if (sessionExpiry !== void 0) {
      const now2 = Date.now();
      const marginMs = _TinyCloudNode.SESSION_EXPIRY_SAFETY_MARGIN_MS;
      if (sessionExpiry.getTime() <= now2 + marginMs) {
        throw new SessionExpiredError(sessionExpiry);
      }
    }
    if (!Array.isArray(permissions) || permissions.length === 0) {
      throw new Error(
        "delegateTo requires a non-empty permissions array"
      );
    }
    const expandedEntries = permissions.map((entry) => ({
      ...entry,
      actions: expandActionShortNames(entry.service, entry.actions)
    }));
    const now = /* @__PURE__ */ new Date();
    const expiryMs = resolveExpiryMs(options?.expiry);
    const expirationTime = new Date(now.getTime() + expiryMs);
    let effectiveExpiration = expirationTime;
    if (sessionExpiry !== void 0 && sessionExpiry < expirationTime) {
      effectiveExpiration = sessionExpiry;
    }
    if (options?.forceWalletSign) {
      if (expandedEntries.length > 1) {
        throw new Error(
          "delegateTo with forceWalletSign=true supports at most one PermissionEntry. Multi-entry requests must go through the session-key UCAN path (drop forceWalletSign) or the legacy createDelegation method."
        );
      }
      const delegation2 = await this.createDelegationLegacyWalletPath(
        did,
        expandedEntries[0],
        effectiveExpiration
      );
      return { delegation: delegation2, prompted: true };
    }
    const granted = parseRecapCapabilities(
      (siwe) => this.wasmBindings.parseRecapFromSiwe(siwe),
      session.siwe
    );
    const { subset, missing } = isCapabilitySubset(expandedEntries, granted);
    if (!subset) {
      throw new PermissionNotInManifestError(missing, granted);
    }
    const delegation = await this.createDelegationViaWasmPath(
      did,
      expandedEntries,
      effectiveExpiration,
      session
    );
    return { delegation, prompted: false };
  }
  /**
   * Issue a delegation via the session-key UCAN WASM path.
   *
   * The caller has already verified every entry is derivable from
   * the current session; we build one multi-resource abilities map
   * and emit one signed UCAN covering them all.
   *
   * All entries must share the same target space (the UCAN is
   * scoped to a single space). If they don't, this throws — mixing
   * spaces in a single delegation is not supported by the underlying
   * Rust create_delegation call and the resulting UCAN would be
   * under-specified.
   *
   * @internal
   */
  async createDelegationViaWasmPath(did, entries, expirationTime, session) {
    if (entries.length === 0) {
      throw new Error(
        "createDelegationViaWasmPath requires a non-empty entries array"
      );
    }
    const resolvedSpaces = /* @__PURE__ */ new Set();
    for (const entry of entries) {
      const spaceId2 = entry.space === "default" ? session.spaceId : entry.space;
      resolvedSpaces.add(spaceId2);
    }
    if (resolvedSpaces.size !== 1) {
      throw new Error(
        `delegateTo: all permission entries must target the same space, got ${resolvedSpaces.size}: ${JSON.stringify([...resolvedSpaces])}`
      );
    }
    const spaceId = [...resolvedSpaces][0];
    const abilities = {};
    for (const entry of entries) {
      const shortService = SERVICE_LONG_TO_SHORT[entry.service];
      if (shortService === void 0) {
        throw new Error(
          `delegateTo: unknown service '${entry.service}' \u2014 no short-form mapping`
        );
      }
      if (abilities[shortService] === void 0) {
        abilities[shortService] = {};
      }
      const pathsMap = abilities[shortService];
      const existing = pathsMap[entry.path];
      if (existing === void 0) {
        pathsMap[entry.path] = [...entry.actions];
      } else {
        const seen = new Set(existing);
        for (const action of entry.actions) {
          if (!seen.has(action)) {
            existing.push(action);
            seen.add(action);
          }
        }
      }
    }
    const serviceSession = {
      delegationHeader: session.delegationHeader,
      delegationCid: session.delegationCid,
      jwk: session.jwk,
      spaceId,
      verificationMethod: session.verificationMethod
    };
    const expirationSecs = Math.floor(expirationTime.getTime() / 1e3);
    const result = this.createDelegationWrapper({
      session: serviceSession,
      delegateDID: did,
      spaceId,
      abilities,
      expirationSecs
    });
    const primary = result.resources[0];
    const delegationHeader = { Authorization: result.delegation };
    const activateResult = await activateSessionWithHost2(
      this.config.host,
      delegationHeader
    );
    if (!activateResult.success) {
      throw new Error(
        `Failed to activate delegation with host: ${activateResult.error}`
      );
    }
    return {
      cid: result.cid,
      delegationHeader,
      spaceId,
      path: primary.path,
      actions: primary.actions,
      resources: result.resources,
      disableSubDelegation: false,
      expiry: result.expiry,
      delegateDID: did,
      ownerAddress: session.address,
      chainId: session.chainId,
      host: this.config.host
    };
  }
  /**
   * Issue a delegation via the legacy wallet-signed SIWE path for a single
   * {@link PermissionEntry}. Shares the implementation with the public
   * `createDelegation` method via {@link createDelegationWalletPath} so
   * both entry points hit exactly the same SIWE / signer / public-space
   * logic without mutual recursion.
   *
   * @internal
   */
  async createDelegationLegacyWalletPath(delegateDID, entry, expirationTime) {
    const spaceIdOverride = entry.space === "default" ? void 0 : entry.space;
    return this.createDelegationWalletPath({
      path: entry.path,
      actions: entry.actions,
      delegateDID,
      includePublicSpace: true,
      expiryMs: Math.max(0, expirationTime.getTime() - Date.now()),
      spaceIdOverride
    });
  }
  /**
   * Create a delegation from this user to another user.
   *
   * The delegation grants the recipient access to a specific path and actions
   * within this user's space.
   *
   * @param params - Delegation parameters
   * @returns A portable delegation that can be sent to the recipient
   */
  async createDelegation(params) {
    if (!this.signer) {
      throw new Error("Cannot createDelegation() in session-only mode. Requires wallet mode.");
    }
    if (!this.auth?.tinyCloudSession) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    let resolvedDelegateDID = params.delegateDID;
    if (resolvedDelegateDID.endsWith(".eth") && this.config.ensResolver) {
      const address = await this.config.ensResolver.resolveAddress(resolvedDelegateDID);
      if (!address) throw new Error(`Could not resolve ENS name: ${resolvedDelegateDID}`);
      resolvedDelegateDID = `did:pkh:eip155:1:${address}`;
    }
    const entries = legacyParamsToPermissionEntries(
      params.actions,
      params.path,
      params.spaceIdOverride
    );
    try {
      const result = await this.delegateTo(
        resolvedDelegateDID,
        entries,
        params.expiryMs !== void 0 ? { expiry: params.expiryMs } : void 0
      );
      return result.delegation;
    } catch (err) {
      if (err instanceof PermissionNotInManifestError) {
      } else {
        throw err;
      }
    }
    return this.createDelegationWalletPath({
      ...params,
      delegateDID: resolvedDelegateDID
    });
  }
  /**
   * Legacy wallet-signed SIWE delegation path. Lifted from the original
   * `createDelegation` body verbatim so both the legacy public method and
   * `delegateTo({ forceWalletSign: true })` hit the same code.
   *
   * @internal
   */
  async createDelegationWalletPath(params) {
    if (!this.signer) {
      throw new Error("Cannot createDelegation() in session-only mode. Requires wallet mode.");
    }
    const session = this.auth?.tinyCloudSession;
    if (!session) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    const abilities = {};
    const kvActions = params.actions.filter((a) => a.startsWith("tinycloud.kv/"));
    const sqlActions = params.actions.filter((a) => a.startsWith("tinycloud.sql/"));
    const duckdbActions = params.actions.filter((a) => a.startsWith("tinycloud.duckdb/"));
    if (kvActions.length > 0) {
      abilities.kv = { [params.path]: kvActions };
    }
    if (sqlActions.length > 0) {
      abilities.sql = { [params.path]: sqlActions };
    }
    if (duckdbActions.length > 0) {
      abilities.duckdb = { [params.path]: duckdbActions };
    }
    const now = /* @__PURE__ */ new Date();
    const expiryMs = params.expiryMs ?? 60 * 60 * 1e3;
    const expirationTime = new Date(now.getTime() + expiryMs);
    const prepared = this.wasmBindings.prepareSession({
      abilities,
      address: this.wasmBindings.ensureEip55(session.address),
      chainId: session.chainId,
      domain: this.siweDomain,
      issuedAt: now.toISOString(),
      expirationTime: expirationTime.toISOString(),
      spaceId: params.spaceIdOverride ?? session.spaceId,
      delegateUri: params.delegateDID,
      parents: [session.delegationCid]
    });
    const signature = await this.signer.signMessage(prepared.siwe);
    const delegationSession = this.wasmBindings.completeSessionSetup({
      ...prepared,
      signature
    });
    const activateResult = await activateSessionWithHost2(
      this.config.host,
      delegationSession.delegationHeader
    );
    if (!activateResult.success) {
      throw new Error(`Failed to activate delegation: ${activateResult.error}`);
    }
    const result = {
      cid: delegationSession.delegationCid,
      delegationHeader: delegationSession.delegationHeader,
      spaceId: params.spaceIdOverride ?? session.spaceId,
      path: params.path,
      actions: params.actions,
      disableSubDelegation: params.disableSubDelegation ?? false,
      expiry: expirationTime,
      delegateDID: params.delegateDID,
      ownerAddress: session.address,
      chainId: session.chainId,
      host: this.config.host
    };
    const hasKvActions = params.actions.some((a) => a.startsWith("tinycloud.kv/"));
    if (hasKvActions && params.includePublicSpace !== false) {
      const publicSpaceId = makePublicSpaceId(
        this.wasmBindings.ensureEip55(session.address),
        session.chainId
      );
      const publicAbilities = {
        kv: { "": ["tinycloud.kv/get", "tinycloud.kv/put", "tinycloud.kv/metadata"] }
      };
      const publicPrepared = this.wasmBindings.prepareSession({
        abilities: publicAbilities,
        address: this.wasmBindings.ensureEip55(session.address),
        chainId: session.chainId,
        domain: this.siweDomain,
        issuedAt: now.toISOString(),
        expirationTime: expirationTime.toISOString(),
        spaceId: publicSpaceId,
        delegateUri: params.delegateDID,
        parents: [session.delegationCid]
      });
      const publicSignature = await this.signer.signMessage(publicPrepared.siwe);
      const publicSession = this.wasmBindings.completeSessionSetup({
        ...publicPrepared,
        signature: publicSignature
      });
      const publicActivateResult = await activateSessionWithHost2(
        this.config.host,
        publicSession.delegationHeader
      );
      if (publicActivateResult.success) {
        result.publicDelegation = {
          cid: publicSession.delegationCid,
          delegationHeader: publicSession.delegationHeader,
          spaceId: publicSpaceId,
          path: "",
          actions: ["tinycloud.kv/get", "tinycloud.kv/put", "tinycloud.kv/metadata"],
          disableSubDelegation: params.disableSubDelegation ?? false,
          expiry: expirationTime,
          delegateDID: params.delegateDID,
          ownerAddress: session.address,
          chainId: session.chainId,
          host: this.config.host
        };
      }
    }
    return result;
  }
  /**
   * Use a delegation received from another user.
   *
   * This creates a new session key for this user that chains from the
   * received delegation, allowing operations on the delegator's space.
   *
   * Works in both modes:
   * - **Wallet mode**: Creates a SIWE sub-delegation from PKH to session key
   * - **Session-only mode**: Uses the delegation directly (must target session key DID)
   *
   * @param delegation - The PortableDelegation to use (from createDelegation or transport)
   * @returns A DelegatedAccess instance for performing operations
   */
  async useDelegation(delegation) {
    const delegationHeader = delegation.delegationHeader;
    const targetHost = delegation.host ?? this.config.host;
    if (this.isSessionOnly) {
      const myDid = this.did;
      if (delegation.delegateDID !== myDid) {
        throw new Error(
          `Delegation targets ${delegation.delegateDID} but this user's DID is ${myDid}. The delegation must target this user's DID.`
        );
      }
      const session2 = {
        address: delegation.ownerAddress,
        chainId: delegation.chainId,
        sessionKey: JSON.stringify(this.sessionKeyJwk),
        spaceId: delegation.spaceId,
        delegationCid: delegation.cid,
        delegationHeader,
        verificationMethod: this.sessionDid,
        jwk: this.sessionKeyJwk,
        siwe: "",
        // Not used in session-only mode
        signature: ""
        // Not used in session-only mode
      };
      this.trackReceivedDelegation(delegation, this.sessionKeyJwk);
      return new DelegatedAccess(session2, delegation, targetHost, this.wasmBindings.invoke);
    }
    const mySession = this.auth?.tinyCloudSession;
    if (!mySession) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    const jwk = mySession.jwk;
    const abilities = {};
    const kvActions = delegation.actions.filter((a) => a.startsWith("tinycloud.kv/"));
    const sqlActions = delegation.actions.filter((a) => a.startsWith("tinycloud.sql/"));
    const duckdbActions = delegation.actions.filter((a) => a.startsWith("tinycloud.duckdb/"));
    if (kvActions.length > 0) {
      abilities.kv = { [delegation.path]: kvActions };
    }
    if (sqlActions.length > 0) {
      abilities.sql = { [delegation.path]: sqlActions };
    }
    if (duckdbActions.length > 0) {
      abilities.duckdb = { [delegation.path]: duckdbActions };
    }
    const now = /* @__PURE__ */ new Date();
    const maxExpiry = new Date(now.getTime() + 60 * 60 * 1e3);
    const expirationTime = delegation.expiry < maxExpiry ? delegation.expiry : maxExpiry;
    const prepared = this.wasmBindings.prepareSession({
      abilities,
      address: this.wasmBindings.ensureEip55(mySession.address),
      chainId: mySession.chainId,
      domain: this.siweDomain,
      issuedAt: now.toISOString(),
      expirationTime: expirationTime.toISOString(),
      spaceId: delegation.spaceId,
      jwk,
      parents: [delegation.cid]
    });
    const signature = await this.signer.signMessage(prepared.siwe);
    const invokerSession = this.wasmBindings.completeSessionSetup({
      ...prepared,
      signature
    });
    const activateResult = await activateSessionWithHost2(
      targetHost,
      invokerSession.delegationHeader
    );
    if (!activateResult.success) {
      throw new Error(`Failed to activate delegated session: ${activateResult.error}`);
    }
    const session = {
      address: mySession.address,
      chainId: mySession.chainId,
      sessionKey: mySession.sessionKey,
      spaceId: delegation.spaceId,
      delegationCid: invokerSession.delegationCid,
      delegationHeader: invokerSession.delegationHeader,
      verificationMethod: mySession.verificationMethod,
      jwk,
      siwe: prepared.siwe,
      signature
    };
    this.trackReceivedDelegation(delegation, jwk);
    return new DelegatedAccess(session, delegation, targetHost, this.wasmBindings.invoke);
  }
  /**
   * Create a sub-delegation from a received delegation.
   *
   * This allows further delegating access that was received from another user,
   * if the original delegation allows sub-delegation.
   *
   * @param parentDelegation - The delegation received from another user
   * @param params - Sub-delegation parameters (must be within parent's scope)
   * @returns A portable delegation for the sub-delegate
   */
  async createSubDelegation(parentDelegation, params) {
    if (!this.signer) {
      throw new Error("Cannot createSubDelegation() in session-only mode. Requires wallet mode.");
    }
    if (!this._address) {
      throw new Error("Not signed in. Call signIn() first.");
    }
    if (parentDelegation.disableSubDelegation) {
      throw new Error("Parent delegation does not allow sub-delegation");
    }
    if (!params.path.startsWith(parentDelegation.path)) {
      throw new Error(
        `Sub-delegation path "${params.path}" must be within parent path "${parentDelegation.path}"`
      );
    }
    const parentActions = new Set(parentDelegation.actions);
    for (const action of params.actions) {
      if (!parentActions.has(action)) {
        throw new Error(
          `Sub-delegation action "${action}" is not in parent's actions: ${parentDelegation.actions.join(", ")}`
        );
      }
    }
    const now = /* @__PURE__ */ new Date();
    const expiryMs = params.expiryMs ?? 60 * 60 * 1e3;
    const requestedExpiry = new Date(now.getTime() + expiryMs);
    const actualExpiry = requestedExpiry > parentDelegation.expiry ? parentDelegation.expiry : requestedExpiry;
    const abilities = {};
    const kvActions = params.actions.filter((a) => a.startsWith("tinycloud.kv/"));
    const sqlActions = params.actions.filter((a) => a.startsWith("tinycloud.sql/"));
    const duckdbActions = params.actions.filter((a) => a.startsWith("tinycloud.duckdb/"));
    if (kvActions.length > 0) {
      abilities.kv = { [params.path]: kvActions };
    }
    if (sqlActions.length > 0) {
      abilities.sql = { [params.path]: sqlActions };
    }
    if (duckdbActions.length > 0) {
      abilities.duckdb = { [params.path]: duckdbActions };
    }
    const targetHost = parentDelegation.host ?? this.config.host;
    const prepared = this.wasmBindings.prepareSession({
      abilities,
      address: this.wasmBindings.ensureEip55(this._address),
      chainId: this._chainId,
      domain: this.siweDomain,
      issuedAt: now.toISOString(),
      expirationTime: actualExpiry.toISOString(),
      spaceId: parentDelegation.spaceId,
      delegateUri: params.delegateDID,
      parents: [parentDelegation.cid]
    });
    const signature = await this.signer.signMessage(prepared.siwe);
    const subDelegationSession = this.wasmBindings.completeSessionSetup({
      ...prepared,
      signature
    });
    const activateResult = await activateSessionWithHost2(
      targetHost,
      subDelegationSession.delegationHeader
    );
    if (!activateResult.success) {
      throw new Error(`Failed to activate sub-delegation: ${activateResult.error}`);
    }
    return {
      cid: subDelegationSession.delegationCid,
      delegationHeader: subDelegationSession.delegationHeader,
      spaceId: parentDelegation.spaceId,
      path: params.path,
      actions: params.actions,
      disableSubDelegation: params.disableSubDelegation ?? false,
      expiry: actualExpiry,
      delegateDID: params.delegateDID,
      ownerAddress: parentDelegation.ownerAddress,
      chainId: parentDelegation.chainId,
      host: targetHost
    };
  }
};
// ===========================================================================
// Capability-chain delegation (spec: .claude/specs/capability-chain.md)
// ===========================================================================
/**
 * Safety margin before the session's own expiry at which {@link delegateTo}
 * will refuse to issue a derived delegation. Prevents issuing sub-delegations
 * that would be invalid by the time the recipient used them. Spec: 60 seconds.
 *
 * @internal
 */
_TinyCloudNode.SESSION_EXPIRY_SAFETY_MARGIN_MS = 6e4;
var TinyCloudNode = _TinyCloudNode;

// src/core.ts
import {
  PermissionNotInManifestError as PermissionNotInManifestError2,
  SessionExpiredError as SessionExpiredError2,
  ManifestValidationError,
  resolveManifest as resolveManifest2,
  validateManifest,
  loadManifest,
  isCapabilitySubset as isCapabilitySubset2,
  expandActionShortNames as expandActionShortNames2,
  parseExpiry as parseExpiry2
} from "@tinycloud/sdk-core";

// src/delegation.ts
function serializeDelegation(delegation) {
  return JSON.stringify({
    ...delegation,
    expiry: delegation.expiry.toISOString()
  });
}
function deserializeDelegation(data) {
  const parsed = JSON.parse(data);
  return {
    ...parsed,
    cid: parsed.cid,
    expiry: new Date(parsed.expiry)
  };
}

// src/core.ts
import { KVService as KVService3, PrefixedKVService } from "@tinycloud/sdk-core";
import { SQLService as SQLService3, SQLAction, DatabaseHandle } from "@tinycloud/sdk-core";
import { DuckDbService as DuckDbService3, DuckDbDatabaseHandle, DuckDbAction } from "@tinycloud/sdk-core";
import { DataVaultService as DataVaultService2, VaultHeaders, VaultPublicSpaceKVActions, createVaultCrypto as createVaultCrypto2 } from "@tinycloud/sdk-core";
import {
  DelegationManager as DelegationManager2,
  SharingService as SharingService2,
  createSharingService,
  DelegationErrorCodes
} from "@tinycloud/sdk-core";
import {
  CapabilityKeyRegistry as CapabilityKeyRegistry2,
  createCapabilityKeyRegistry,
  CapabilityKeyRegistryErrorCodes
} from "@tinycloud/sdk-core";
import {
  SpaceService as SpaceService2,
  SpaceErrorCodes,
  createSpaceService,
  parseSpaceUri,
  buildSpaceUri,
  makePublicSpaceId as makePublicSpaceId2,
  Space
} from "@tinycloud/sdk-core";
import {
  ProtocolMismatchError,
  VersionCheckError,
  UnsupportedFeatureError as UnsupportedFeatureError2,
  checkNodeInfo as checkNodeInfo2
} from "@tinycloud/sdk-core";
import { ServiceContext as ServiceContext3 } from "@tinycloud/sdk-core";
export {
  AutoApproveSpaceCreationHandler2 as AutoApproveSpaceCreationHandler,
  CapabilityKeyRegistry2 as CapabilityKeyRegistry,
  CapabilityKeyRegistryErrorCodes,
  DataVaultService2 as DataVaultService,
  DatabaseHandle,
  DelegatedAccess,
  DelegationErrorCodes,
  DelegationManager2 as DelegationManager,
  DuckDbAction,
  DuckDbDatabaseHandle,
  DuckDbService3 as DuckDbService,
  FileSessionStorage,
  KVService3 as KVService,
  ManifestValidationError,
  MemorySessionStorage,
  NodeUserAuthorization,
  PermissionNotInManifestError2 as PermissionNotInManifestError,
  PrefixedKVService,
  ProtocolMismatchError,
  SQLAction,
  SQLService3 as SQLService,
  ServiceContext3 as ServiceContext,
  SessionExpiredError2 as SessionExpiredError,
  SharingService2 as SharingService,
  SilentNotificationHandler2 as SilentNotificationHandler,
  Space,
  SpaceErrorCodes,
  SpaceService2 as SpaceService,
  TinyCloud2 as TinyCloud,
  TinyCloudNode,
  UnsupportedFeatureError2 as UnsupportedFeatureError,
  VaultHeaders,
  VaultPublicSpaceKVActions,
  VersionCheckError,
  WasmKeyProvider,
  buildSpaceUri,
  checkNodeInfo2 as checkNodeInfo,
  createCapabilityKeyRegistry,
  createSharingService,
  createSpaceService,
  createVaultCrypto2 as createVaultCrypto,
  createWasmKeyProvider,
  defaultSignStrategy,
  defaultSpaceCreationHandler,
  deserializeDelegation,
  expandActionShortNames2 as expandActionShortNames,
  isCapabilitySubset2 as isCapabilitySubset,
  loadManifest,
  makePublicSpaceId2 as makePublicSpaceId,
  parseExpiry2 as parseExpiry,
  parseSpaceUri,
  resolveManifest2 as resolveManifest,
  serializeDelegation,
  validateManifest
};
//# sourceMappingURL=core.js.map