/** * NFSP v0 client for nfs_server (buckyos/src/frame/nfs_server). * * Speaks the control plane (`POST /nfs/v1/{method}`), the data plane * (`GET /nfs/v1/read/{node_id}`), the minimal tus upload area * (`PATCH|HEAD /nfs/v1/uploads/{fb}`) and the watch SSE stream * (`GET /nfs/v1/watch`). * * Protocol references: * - cyfs-ndn/doc/NamedFileSystem_Protocol_v0.md (NFSP v0) * - buckyos/product/bucky_file/nfs_server.md * - buckyos/src/frame/nfs_server/README.md (v1 降级契约) * * Client contract highlights (nfs_server README §4.2): * - `revision` is an opaque equality token: only compare, never order. * - Write ops require `seq` (exactly-once); the client auto-assigns one per * write and replays with the SAME seq on network retry. * - Leases are advisory versus server-local bypass writers: commit may fail * with TARGET_MISMATCH{reason:"bypass_modified"} — surface, don't retry. * - watch is lossy: any `resync` event means "re-list what you care about". * * Uses only fetch/WHATWG streams, so it runs in the browser and in Node ≥ 18. */ export declare const NFSP_VERSION = "nfsp/0"; /** `{"type":"live",...}` or `{"type":"object",...}` (NFSP §3.1.2). */ export type LiveRef = { type: 'live'; node_id: string; gen?: number; }; export type ObjectRef = { type: 'object'; obj_id: string; inner_path?: string; }; export type WireRef = LiveRef | ObjectRef; export declare const liveRef: (nodeId: string, gen?: number) => LiveRef; /** The `at` locator: ref > uri > path (NFSP §3.4). */ export interface Locator { realm?: string; path?: string; uri?: string; ref?: WireRef; } /** Sugar: accept a dfs path string, a `xxx://` uri, a WireRef or a Locator. */ export type LocatorLike = string | WireRef | Locator; export declare const toLocator: (at: LocatorLike) => Locator; export type WantGroup = 'base' | 'ident' | 'access' | 'meta'; export type NodeKind = 'dir' | 'file' | 'symlink' | 'view' | 'collection' | 'group'; /** * The caller's effective permission on a node. `traverse` = only the way to * something shared deeper down: listable, but only those children are shown. */ export type AccessLevel = 'none' | 'traverse' | 'read' | 'write' | 'manage'; /** `user:`, `zone_users` (any signed-in user) or `public` (anyone, read only). */ export type AclPrincipal = `user:${string}` | 'zone_users' | 'public'; export interface AclEntry { principal: AclPrincipal; level: Exclude; } /** `get_acl` result; the entry lists only appear for callers who may manage. */ export interface AclInfo { path: string; access_level: AccessLevel; can_manage: boolean; revision: string; inherit?: boolean; entries?: AclEntry[]; /** Grants arriving from ancestors, with the directory they come from. */ inherited?: (AclEntry & { from: string; })[]; /** Built-in rules (zone owner, home owner) that no record can remove. */ builtin?: (AclEntry & { reason: 'zone_owner' | 'home_owner'; })[]; updated_by?: string; updated_at?: number; } export interface AclRecordInfo { path: string; inherit: boolean; entries: AclEntry[]; home_owner: string | null; updated_by: string; updated_at: number; revision: string; /** The path no longer exists (removed outside the protocol). */ missing: boolean; } export interface Capabilities { list: boolean; read: boolean; accepts_content: boolean; accepts_references: boolean; remove_semantics: 'destroy' | 'unlink' | 'none'; ordered: boolean; } /** resolve/stat result (fields beyond `base` appear per the `want` mask). */ export interface NodeInfo { kind: NodeKind; state: string; ref: WireRef; copy_ref?: WireRef | null; capabilities: Capabilities; access_level?: AccessLevel; revision?: string; locations?: unknown[]; name?: string; size?: number; mtime?: number; ctime?: number; flags?: string[]; node_id?: string; gen?: number; etag?: string; obj_id?: string; access_urls?: { kind: string; url: string; }[]; meta_summary?: Record; view_id?: string; collection_id?: string; title?: string; origin?: string; stale?: boolean; } export type EntryBinding = 'native' | 'reference' | 'member' | 'derived' | 'projection'; /** Compact target of a listing entry (not a full NodeInfo). */ export interface EntryTarget { ref: WireRef; copy_ref?: WireRef | null; kind: NodeKind; /** Attribute groups per the `want` mask: base → size/mtime/flags, ident → etag/obj_id, access → access_urls. */ attrs?: { size?: number; mtime?: number; flags?: string[]; etag?: string; obj_id?: string; access_urls?: { kind: string; url: string; }[]; } & Record; /** `stale` when a referenced target no longer resolves, `denied` when the caller may not see it. */ target_state?: string; access_level?: AccessLevel; } export interface Entry { name: string; binding: EntryBinding; entry_ref?: string; target: EntryTarget; canonical_path?: string; context?: { count?: number; provenance?: Record; } & Record; } export interface Listing { container: NodeInfo; entries: Entry[]; truncated?: boolean; next_cursor?: string; revision_changed?: boolean; watch_token?: string; /** Same-name virtual bindings shadowed by native entries (`native_shadow`). */ conflicts?: { name: string; reason: string; entry_ref?: string; target?: EntryTarget; }[]; } export interface ListOptions { cursor?: string; limit?: number; order?: 'name' | 'mtime' | 'size' | 'manual'; filter?: { kind?: NodeKind[]; name_glob?: string; }; } export interface HelloResult { version: string; session: string; features: string[]; limits: { max_batch: number; max_list: number; replay_window: number; attr_ttl_ms: number; }; realms: { id: string; writable: boolean; }[]; /** Who this session acts as (`admin` = the zone owner or a trusted service). */ identity?: { user_id: string | null; role: 'admin' | 'user' | 'anonymous'; }; /** The Preview Pipeline's converter, also when `repr` is not advertised. */ repr?: ReprCapability; } /** What the node converts with: ffmpeg / ffprobe found on it, or why not. */ export type ReprCapability = { available: true; ffmpeg: { path: string; version: string; }; ffprobe: { path: string; version: string; }; tonemap: boolean; h264_encoder: boolean; heif: boolean; profiles: string[]; } | { available: false; missing?: string[]; detail?: string; }; /** Content that is not an NFSP path / ref (those go in `at`). */ export type ReprSource = { bucket: { bucket_id: string; key: string; version?: number; access_token?: string; }; } | { obj_id: string; }; /** Runtime capability hints; `video_codecs.hevc` lets the node remux instead of transcoding. */ export interface ReprRuntime { accept?: string[]; image?: string[]; video?: string[]; audio?: string[]; video_codecs?: { h264: boolean; hevc: boolean; }; heic?: boolean; pdf_inline?: boolean; } export interface ReprArgs { purpose?: 'preview' | 'thumbnail'; source?: ReprSource; runtime?: ReprRuntime; /** Explicit Retry: a new attempt only if `expected_attempt_id` is still the current one. */ retry?: boolean; expected_attempt_id?: string; } export interface ReprResult { media_type: string; result_type: 'image' | 'video' | 'audio'; /** Bucket data-plane URL with a short-lived read token (Range supported). */ read_url: string; result_obj_id: string; source_version: string; width?: number; height?: number; duration?: number; fidelity?: string; size: number; plan: string; } /** `unsupported` is a planning result (`reason` + `detail`), `failed` an execution failure. */ export type ReprRecord = { state: 'unsupported'; reason: 'no-pipeline' | 'no-renderer' | 'not-content'; detail?: string; } | { work_key: string; state: 'processing'; attempt_id: string; retry_after_ms?: number; progress?: { completed: number; total?: number; message?: string; }; } | { work_key: string; state: 'completed'; attempt_id: string; result: ReprResult; } | { work_key: string; state: 'failed'; attempt_id: string; error: { code: string; message: string; retryable: boolean; retry_after?: number; }; }; export type BatchOp = { m: 'walk'; args: { name?: string; names?: string[]; entry_ref?: string; }; } | { m: 'stat' | 'resolve'; args?: { name?: string; }; want?: WantGroup[]; } | { m: 'list'; args?: ListOptions; want?: WantGroup[]; }; export interface BatchResult { completed: number; results: ({ ok: true; result: unknown; } | { ok: false; error: NfspErrorBody; })[]; } export interface OpenWriteResult { fb_handle: string; upload_url: string; lease: { lease_id: string; seq: number; ttl_ms: number; }; target: { path: string; exists: boolean; }; } export interface CommitResult { ref: WireRef; entry_ref: string; revision: string; obj: { sha256: string; size: number; }; } export interface CommitObjectResult { ref: WireRef; entry_ref: string; revision: string; obj_id: string; kind: 'file' | 'dir'; obj: { size: number; sha256?: string; }; } export interface MetaRecord { ns: string; key: string; value: unknown; source?: unknown; confidence?: number; anchor?: string; visibility?: string; } export interface SearchHit { copy_ref?: WireRef | null; match_source: string; canonical_path: string; explain?: Record; [k: string]: unknown; } export interface SearchResult { hits: SearchHit[]; partial: boolean; sources: { mode: string; state: string; took_ms?: number; reason?: string; }[]; next_cursor?: string; } export interface GrantResult { cap_id: string; token: string; subtree: string; ops: string[]; expires_at?: number; } export type ShareAccess = 'holder' | 'password'; export type ShareStatus = 'active' | 'stopping' | 'stopped' | 'expired' | 'failed'; export type ShareKind = 'link' | 'app_delivery'; export type ShareTargetApp = 'messagehub' | 'homestation'; export type ShareContentKind = 'image' | 'video' | 'audio' | 'file' | 'folder'; export type ShareDeliveryState = 'handed_off' | 'confirmed' | 'canceled' | 'failed' | 'unknown'; export type ShareOperationState = 'preparing' | 'running' | 'completed' | 'failed' | 'canceled'; export interface ShareStatsTotals { views: number; downloads: number; bytes: number; visitors: number; last_access_at?: number | null; } export interface ShareInfo { share_id: string; kind: ShareKind; title: string; status: ShareStatus; status_reason?: string | null; hidden: boolean; revision: number; created_at: number; updated_at: number; stopped_at?: number | null; owner_user_id: string; created_by_app?: string | null; related_share_id?: string | null; obj_id: string; obj_type?: string; name?: string; mime?: string | null; total_size?: number; item_count?: number; content_kind?: ShareContentKind; excluded?: { path: string; reason: string; }[]; prepared_at?: number; source_path: string; retained: boolean; /** Link shares. `url` is only returned to the owner. */ access?: ShareAccess; has_password?: boolean; allow_download?: boolean; expires_at?: number | null; url?: string | null; /** App deliveries. */ target_app?: ShareTargetApp; delivery_state?: ShareDeliveryState; business_ref?: Record | null; handoff_at?: number; reported_at?: number | null; delivery_error?: string | null; stats: ShareStatsTotals; } export interface ShareAuditEntry { action: string; revision_before?: number | null; revision_after?: number | null; actor_user_id: string; actor_app_id?: string | null; source: string; reason?: string | null; outcome: string; at: number; } export interface ShareDetail extends ShareInfo { /** The bucket binding that retains the snapshot (`zone/nfs-server/_/shares`); empty once released. */ retention: { bucket_id: string; key: string; obj_id: string; version: number; bound_at: number; }[]; audit: ShareAuditEntry[]; related?: ShareInfo; } export interface ShareCapabilities { actions: string[]; access: ShareAccess[]; expiry_presets: (number | null)[]; default_expiry: number; limits: { sync_threshold: number; max_total_size: number; max_items: number; }; targets: { app: ShareTargetApp; accepts: string | string[]; max_item_size: number; fallback: 'link'; }[]; blocked: { action: string; reason: string; }[]; share_base_url?: string | null; public: { dir: string; base_url?: string | null; }; } export interface ShareTargetFit { app: ShareTargetApp; mode: 'attachment' | 'link'; reason?: 'folder' | 'not_media' | 'too_large' | null; kind: ShareContentKind; } export interface SharePlan { plan_fingerprint: string; source: { path: string; name: string; kind: 'file' | 'dir'; mime?: string | null; }; estimate: { total_size: number; item_count: number; excluded: { path: string; reason: string; }[]; }; warnings: string[]; requires_task: boolean; existing: ShareInfo[]; source_public: { in_publish_dir: boolean; public_acl: boolean; public_url?: string | null; }; /** Folders with an index.html may be websites (going live is App Service's job). */ site: { has_index_html: boolean; }; target_fit?: ShareTargetFit; } export interface SharePolicyInput { access: ShareAccess; password?: string; /** Unix seconds; `null` = does not expire; omitted = seven days. */ expires_at?: number | null; allow_download?: boolean; } export interface ShareHandoff { share_id: string; obj_id: string; name: string; size: number; mime?: string | null; kind: ShareContentKind; mode: 'attachment' | 'link'; link_share_id?: string | null; url?: string | null; launch: { appId: ShareTargetApp; payload: Record; }; } export interface ShareOperation { operation_id: string; intent: 'create_link' | 'app_handoff'; state: ShareOperationState; share_id?: string | null; task_id?: string | null; error?: NfspErrorBody | null; progress: { done_bytes?: number; total_bytes?: number; }; created_at: number; updated_at: number; source_changed?: boolean; obj_id?: string; url?: string | null; share?: ShareInfo; handoff?: ShareHandoff | null; } export interface ShareListFilter { kind?: ShareKind; status?: ShareStatus; source?: string | Locator; objId?: string; q?: string; includeHidden?: boolean; limit?: number; cursor?: string; } export interface ShareStatsPoint { t: number; views: number; downloads: number; bytes: number; visitors: number; } export interface ShareStatsResult { granularity: 'hour' | 'day'; from: number; to: number; series: ShareStatsPoint[]; totals: Omit; /** `expiring_soon`: active links ending within `expiring_within` seconds. */ summary: { active: number; expiring_soon: number; expiring_within: number; }; unavailable: string[]; } export interface PublicEntry { rel_path: string; entry_kind: 'file' | 'dir' | 'symlink'; link_target?: string | null; link_ok?: boolean | null; size?: number | null; mtime?: number | null; first_seen_at: number; last_seen_at: number; missing_since?: number | null; url?: string | null; } export interface PublicListing { entries: PublicEntry[]; last_scan_at: number; scan_ok: boolean; dir: string; base_url?: string | null; } export type CollectionPatchOp = { add_ref: { target_ref: WireRef; name?: string; position?: number; parent_entry_ref?: string; }; } | { remove_entry: { entry_ref: string; }; } | { move_entries: { entry_refs: string[]; to_index: number; }; } | { create_group: { name: string; position?: number; }; } | { rename_group: { entry_ref: string; name: string; }; }; export interface WatchEvent { /** `resync` | `container_changed` | `meta_changed` (extensible). */ event: string; /** Parsed JSON payload of the SSE `data:` line. */ data: Record; /** SSE `id:` (the server_rev), when present. */ id?: string; } /** Structured NFSP error body (§8 plus implementation extensions). */ export interface NfspErrorBody { code: string; message: string; [k: string]: unknown; } export declare class NfspError extends Error { readonly code: string; readonly httpStatus: number; /** Extra structured fields (reason, holder_session, obj_id, expected, ...). */ readonly details: Record; constructor(body: NfspErrorBody, httpStatus: number); } export interface NfspClientOptions { sessionToken?: () => Promise; /** e.g. `http://127.0.0.1:3260` — no trailing slash needed. */ baseUrl: string; /** Override fetch (tests, custom auth wrappers). Defaults to global fetch. */ fetch?: typeof fetch; /** tus PATCH chunk size; server guidance is 4–16 MB. Default 8 MB. */ uploadChunkSize?: number; } interface EnvelopeExtras { at?: Locator; want?: WantGroup[]; args?: Record; } export declare class NfspClient { private readonly sessionToken?; readonly baseUrl: string; private readonly fetchFn; private readonly chunkSize; private session; private seq; private helloResult; constructor(opts: NfspClientOptions); get sessionId(): string | null; /** The Preview Pipeline converter reported by hello (null before hello). */ get reprCapability(): ReprCapability | null; /** Features advertised by the server in hello (empty before hello). */ get features(): string[]; get limits(): HelloResult['limits'] | null; hello(clientFeatures?: string[]): Promise; bye(): Promise; resolve(at: LocatorLike, want?: WantGroup[]): Promise; /** stat with an optional child `name` step (server-side walk). */ stat(at: LocatorLike, opts?: { name?: string; want?: WantGroup[]; }): Promise; list(at: LocatorLike, opts?: ListOptions, want?: WantGroup[]): Promise; batch(start: LocatorLike, ops: BatchOp[], onError?: 'abort' | 'continue'): Promise; /** * Ref form: create one child under `parent` (optional CAS via * `expectedRevision`). Path form: pass a dfs path string and no name — * behaves like `mkdir -p` (idempotent, no CAS). */ mkdir(parent: LocatorLike, name?: string, opts?: { expectedRevision?: string; }): Promise<{ ref: WireRef; existed: boolean; revision?: string; }>; move(from: { parentRef: WireRef; name: string; }, to: { parentRef: WireRef; name: string; }, opts?: { expectedFromRevision?: string; expectedToRevision?: string; }): Promise<{ from_revision: string; to_revision: string; }>; /** Destroys a native entry. Reference entries must use `unlink` instead. */ delete(parent: LocatorLike, name: string, opts?: { recursive?: boolean; expectedRevision?: string; }): Promise<{ revision: string; }>; bindRef(parentRef: WireRef, name: string, targetRef: WireRef, opts?: { expectedRevision?: string; }): Promise<{ entry_ref: string; revision: string; }>; /** Removes a reference entry (`be_*`) only; the target is never touched. */ unlink(entryRef: string, opts?: { expectedRevision?: string; }): Promise<{ revision: string; }>; openWrite(target: { parentRef: WireRef; name: string; size?: number; } | { ref: WireRef; }): Promise; /** Current upload offset (tus HEAD) — resume point after interruption. */ uploadOffset(fbHandle: string): Promise; /** One tus PATCH. Returns the new offset. */ uploadChunk(fbHandle: string, offset: number, chunk: Uint8Array): Promise; /** Uploads a whole buffer in chunks, resuming from the server's offset. */ uploadContent(fbHandle: string, content: Uint8Array, onProgress?: (sent: number, total: number) => void): Promise; abortWrite(leaseId: string): Promise; private authHeaders; commitFile(parent: LocatorLike, name: string, source: { fbHandle: string; leaseId?: string; } | { hash: string; }, opts?: { overwrite?: boolean; expectedRevision?: string; }): Promise; commitObject(parent: LocatorLike, name: string, objId: string, opts?: { overwrite?: boolean; expectedRevision?: string; leaseId?: string; }): Promise; /** Which of these digests must be uploaded (§ probe / 秒传). */ probe(digests: { hash: string; size?: number; }[]): Promise<{ missing: { hash: string; size?: number; }[]; }>; /** * Convenience: open_write + chunked tus upload + commit_file. * Overwrites an existing file only when `opts.overwrite` is set. */ uploadFile(parentRef: WireRef, name: string, content: Uint8Array, opts?: { overwrite?: boolean; onProgress?: (sent: number, total: number) => void; }): Promise; /** * URL for `GET /nfs/v1/read/{node_id}` (usable in , , …). * It carries no token: same-origin requests authenticate with the SSO cookie, * anything else only reads public paths. */ readUrl(nodeId: string, opts?: { download?: boolean; name?: string; }): string; /** Reads file content; `range` is inclusive byte positions. */ readFile(nodeId: string, opts?: { range?: { start: number; end?: number; }; ifNoneMatch?: string; }): Promise; getMeta(target: LocatorLike, ns?: string[]): Promise<{ records: MetaRecord[]; }>; /** v1: only `ns: "user"` records are writable. */ setMeta(target: LocatorLike, records: { ns: string; key: string; value: unknown; visibility?: string; }[]): Promise<{ updated: number; }>; search(q: string, opts?: { limit?: number; cursor?: string; scope?: LocatorLike; modes?: string[]; }, want?: WantGroup[]): Promise; openView(viewId: string, want?: WantGroup[]): Promise; createCollection(title: string, collectionId?: string, want?: WantGroup[]): Promise; openCollection(collectionId: string, want?: WantGroup[]): Promise; collectionPatch(ref: WireRef, ops: CollectionPatchOp[], opts?: { expectedRevision?: string; }): Promise<{ revision: string; }>; grant(subtree: LocatorLike, opts?: { ops?: string[]; ttl?: number; audience?: string; maxUses?: number; }): Promise; revoke(capId: string): Promise<{ revoked: string; }>; getAcl(at: LocatorLike): Promise; /** Replaces the node's own record; `inherit: true` with no entries removes it. */ setAcl(at: LocatorLike, acl: { inherit: boolean; entries: AclEntry[]; }, opts?: { expectedRevision?: string; }): Promise<{ path: string; revision: string; }>; /** Every ACL record the caller may manage (all of them for the zone owner). */ listAcls(): Promise<{ records: AclRecordInfo[]; zone_owner: string | null; is_admin: boolean; }>; /** Ensures a preview of `at` (or `args.source`); idempotent per work key. */ repr(at: LocatorLike | null, args?: ReprArgs): Promise; /** Queries a work this principal ensured; never starts an attempt. */ getRepr(workKey: string): Promise; shareCapabilities(): Promise; /** Side-effect free: size, exclusions, existing links, Public state, target fit. */ sharePlan(source: LocatorLike, opts?: { intent?: 'create_link' | 'app_handoff'; target?: ShareTargetApp; }): Promise; /** Snapshots the source and creates a link. Large sources return `state: 'running'`. */ shareCreate(source: LocatorLike, policy: SharePolicyInput, opts?: { title?: string; idempotencyKey?: string; planFingerprint?: string; sourceHint?: 'gui' | 'cli' | 'agent'; }): Promise; shareOperation(operationId: string, opts?: { cancel?: boolean; }): Promise; /** Polls a running operation until it settles. */ waitShareOperation(op: ShareOperation, opts?: { intervalMs?: number; signal?: AbortSignal; onProgress?: (op: ShareOperation) => void; }): Promise; shareGet(shareId: string): Promise; shareList(filter?: ShareListFilter): Promise<{ items: ShareInfo[]; next_cursor?: string | null; }>; /** `password: null` removes it, `expires_at: null` = no expiry. REVISION_CONFLICT carries `current`. */ shareUpdate(shareId: string, revision: number, changes: { title?: string; expires_at?: number | null; password?: string | null; allow_download?: boolean; access?: ShareAccess; }, reason?: string): Promise<{ revision: number; share: ShareInfo; }>; shareStop(shareId: string, revision: number, reason?: string): Promise<{ status: ShareStatus; revision: number; }>; shareHide(shareId: string, hidden: boolean): Promise<{ hidden: boolean; revision: number; }>; /** Snapshot for an app target; the result's `handoff.launch` opens the app. */ shareAppHandoff(source: LocatorLike, targetApp: ShareTargetApp, opts?: { title?: string; idempotencyKey?: string; }): Promise; /** What the target app did; older facts (by `observedAt`, ms) are refused. */ shareAppReport(shareId: string, deliveryState: Exclude, opts?: { businessRef?: Record; error?: string; observedAt?: number; }): Promise<{ accepted: boolean; delivery_state: string; }>; sharePublicList(opts?: { refresh?: boolean; }): Promise; shareStats(opts?: { shareId?: string; from?: number; to?: number; granularity?: 'hour' | 'day'; }): Promise; /** * Opens the watch stream. `tokens` filters to specific containers using the * `watch_token` returned by list. The stream is lossy by contract: on any * `resync` event, re-list watched containers. */ watch(opts?: { tokens?: string[]; signal?: AbortSignal; }): AsyncIterableIterator & { close: () => void; }; /** Read-path call: no seq. Throws NfspError on `ok:false`. */ call(method: string, extras: EnvelopeExtras): Promise; /** * Write-path call: assigns the next seq once and reuses it across network * retries so the server's replay window guarantees exactly-once. */ write(method: string, extras: EnvelopeExtras, retries?: number): Promise; private envelope; private post; private httpError; } export {}; //# sourceMappingURL=nfsp.d.ts.map