RolebookDocs

@rolebook/client

A typed fetch client for the sharing HTTP API.

@rolebook/client calls a server mounted with @rolebook/server. Its methods mirror TenantSharing, typed by your resource catalog when you pass it, and return the wire shapes.

import { createIdempotencyKey, createSharingClient, SharingHttpError } from "@rolebook/client";

const sharing = createSharingClient({
  baseUrl: "/api/sharing",
  credentials: "include",
  headers: async () => ({ "x-request-id": crypto.randomUUID() }),
});

try {
  const page = await sharing.listAccessible({ type: "project", action: "read", limit: 50 });
  const history = await sharing.auditHistory({ resource: { type: "project", id: "project_1" }, limit: 20 });
  if (history.ok) history.page.events[0]?.occurredAt.getTime(); // revived to a Date
  await sharing.execute({
    kind: "revokeMember",
    resource: { type: "project", id: "project_1" },
    subject: { type: "user", id: "user_789" },
    idempotencyKey: createIdempotencyKey(),
  });
} catch (error) {
  if (error instanceof SharingHttpError) console.error(error.status, error.code);
  else throw error;
}
  • baseUrl is a path or an absolute URL; one trailing slash is removed. fetch defaults to the platform fetch, and credentials to "same-origin". headers may be a function, called per request.
  • Results are the wire shapes: authorize has no decision, permissions decisions are { allowed }, listed resources have no snapshot. describeAccess and auditHistory revive their timestamps to Date.
  • Four failures throw the client’s own typed classes: InvalidCursorError, AccessibleListingError, and AuditHistoryError for cursor, listing, and audit requests the server refuses with 400, and AccessListingUnavailableError when listAccessible gets a 503 because the server could not read a consistent page. Every other HTTP error throws SharingHttpError (code UNEXPECTED_RESPONSE for a body that is not a wire error). None of these is instanceof a class from @rolebook/sharing: check name or code.
  • An unavailable listing returned no page; it is not an empty result. See handling an unavailable listing.
  • Call createIdempotencyKey() once per user intent and send that key again when retrying the intent. A replay answers ALREADY_APPLIED without an invitation token.

Handling an unavailable listing

import { AccessListingUnavailableError, createSharingClient } from "@rolebook/client";

const sharing = createSharingClient({ baseUrl: "/api/sharing" });

try {
  const page = await sharing.listAccessible({ type: "project", action: "read", limit: 50 });
  console.log(page.resources.length, page.exhausted);
} catch (error) {
  if (!(error instanceof AccessListingUnavailableError)) throw error;
  // The server returned no page. Offer a retry; do not render an empty list.
  console.warn(`listing unavailable: ${error.reason}`);
}

The error has code: "ACCESS_LISTING_UNAVAILABLE" and a reason, one of the eight values of WireAccessListingUnavailableReason. The reasons expiry_crossed, session_expired, snapshot_unavailable, and changed may succeed on a later call, although snapshot_unavailable can also mean corrupt stored data that needs repair; the others indicate the server’s configuration or identity data and need attention there. See the reason table.

import { ... } from "@rolebook/client". Signatures are checked against the built declarations.

Client

createSharingClient

function createSharingClient<
  TResources extends SharingResourceConfigurations = SharingResourceConfigurations,
>(options: SharingClientOptions): SharingClient<TResources>;

Creates a client. Pass your resource catalog type for typed resource types, actions, and roles.

SharingClient

interface SharingClient<TResources extends SharingResourceConfigurations> {
  authorize<TType extends ResourceType<TResources>>(input: {
    readonly resource: ResourceKey<TType>;
    readonly action: ActionFor<TResources, TType>;
  }): Promise<WireSharingDecision>;
  permissions<TType extends ResourceType<TResources>>(input: {
    readonly resource: ResourceKey<TType>;
  }): Promise<WireResourcePermissionsResult<ActionFor<TResources, TType>, TType>>;
  describeAccess<TType extends ResourceType<TResources>>(input: {
    readonly resource: ResourceKey<TType>;
  }): Promise<ClientAccessDescriptionResult<RoleFor<TResources, TType>, TType>>;
  listAccessible<TType extends ResourceType<TResources>>(input: {
    readonly type: TType;
    readonly action: ActionFor<TResources, TType>;
    readonly limit: number;
    readonly cursor?: string;
  }): Promise<WireAccessiblePage<TType>>;
  auditHistory<TType extends ResourceType<TResources>>(input: {
    readonly resource: ResourceKey<TType>;
    readonly limit: number;
    readonly cursor?: string;
  }): Promise<ClientAuditHistoryResult<TType>>;
  execute<TType extends ResourceType<TResources>>(
    command: SharingCommand<TResources, TType>,
  ): Promise<WireMutationResult>;
  explain<TType extends ResourceType<TResources>>(input: {
    readonly resource: ResourceKey<TType>;
    readonly action: ActionFor<TResources, TType>;
    readonly subject?: WireRef;
    readonly field?: string;
  }): Promise<HttpInspectionResult>;
}

The operations over HTTP. explain is described under Inspection.

execute sends a command with expectedSharingRevision as sharing.executeIfUnchanged: it applies only while the resource’s sharing revision is still that value, and resolves to { ok: false, code: "SHARING_REVISION_CHANGED" } otherwise. A server that predates the operation, or a newer server whose sharing runtime does not declare conditionalExecution, rejects with SharingHttpError 404 UNKNOWN_OPERATION and applies nothing; the client never falls back to an unconditional sharing.execute. A key set to undefined still counts: the server refuses it with SharingHttpError 400. A command without the key is sent as before.

import { createIdempotencyKey, createSharingClient } from "@rolebook/client";

const sharing = createSharingClient({ baseUrl: "/api/sharing" });
const described = await sharing.describeAccess({ resource: { type: "project", id: "p1" } });
if (described.ok) {
  const result = await sharing.execute({
    kind: "revokeMember",
    resource: { type: "project", id: "p1" },
    subject: { type: "user", id: "u2" },
    idempotencyKey: createIdempotencyKey(),
    expectedSharingRevision: described.access.sharingRevision,
  });
  if (!result.ok && result.code === "SHARING_REVISION_CHANGED") {
    // Someone changed access since it was read: read it again and ask the user.
  }
}

SharingClientOptions

interface SharingClientOptions {
  readonly baseUrl: string;
  readonly fetch?: (input: string, init: RequestInit) => Promise<Response>;
  readonly headers?: SharingHeadersInit | (() => SharingHeadersInit | Promise<SharingHeadersInit>);
  readonly credentials?: SharingCredentials;
  readonly timeoutMs?: number;
  readonly maxResponseBytes?: number;
}

timeoutMs bounds each call, from sending the request to reading the whole response; it defaults to DEFAULT_TIMEOUT_MS. maxResponseBytes caps how much of a response body is read; it defaults to DEFAULT_MAX_RESPONSE_BYTES. The client sends every request with redirect: "error" and never follows a redirect.

SharingCredentials

type SharingCredentials = "omit" | "same-origin" | "include";

SharingHeadersInit

type SharingHeadersInit =
  | Headers
  | readonly (readonly [string, string])[]
  | Readonly<Record<string, string>>;

createIdempotencyKey

function createIdempotencyKey(): string;

A new random idempotency key for one user intent.

DEFAULT_TIMEOUT_MS

const DEFAULT_TIMEOUT_MS = 10000;

The default timeoutMs: 10 seconds, the default of the Python, Go and Rust SDKs.

DEFAULT_MAX_RESPONSE_BYTES

const DEFAULT_MAX_RESPONSE_BYTES = 4194304;

The default maxResponseBytes: 4 MiB, the default of the Python, Go and Rust SDKs.

Inspection

explain calls sharing.explain, the privileged current-state inspection of TenantSharing.explain, when the server enables it. subject defaults to the authenticated actor.

import { createSharingClient } from "@rolebook/client";

const sharing = createSharingClient({ baseUrl: "/api/sharing" });
const result = await sharing.explain({
  resource: { type: "project", id: "project_1" },
  action: "read",
  subject: { type: "user", id: "user_789" },
});
if (result.ok) console.log(result.explanation.decision.code);
else console.log(result.code); // INVALID_REQUEST, NOT_FOUND_OR_DENIED, RATE_LIMITED, INSPECTION_UNAVAILABLE

It resolves to HttpInspectionResult only for a 200 that matches the ExplainResult schema, or for exactly the fixed body of a 400, 404, 429, or 503. Every other response rejects as usual: a 404 or 200 body that is not exactly the contract is SharingHttpError with UNEXPECTED_RESPONSE, and a 401, a 413 for a body over 8 KiB, a timeout, or a network failure keep their usual errors. A disabled server, a hidden resource, a denied inspector, and an unavailable target are all NOT_FOUND_OR_DENIED, and nothing in the response tells them apart. The result is never a permission; do not retry INSPECTION_UNAVAILABLE automatically.

Errors

SharingHttpError

class SharingHttpError extends Error {
  readonly status: number;
  readonly code: WireErrorCode | SharingClientErrorCode;
  readonly issues?: readonly WireIssue[];
  constructor(
    status: number,
    code: WireErrorCode | SharingClientErrorCode,
    message: string,
    issues?: readonly WireIssue[],
  );
}

Any non-200 response other than the cursor, listing, and audit errors and the typed AccessListingUnavailableError: status, code, and issues.

SharingClientErrorCode

type SharingClientErrorCode = "UNEXPECTED_RESPONSE" | "TIMEOUT";

The codes the client produces itself. UNEXPECTED_RESPONSE means a response did not match the wire contract at any status, including an HTTP 200 body that is not the operation’s result, a redirect, or a body over maxResponseBytes. TIMEOUT means the call did not finish within timeoutMs; its status is 0. A timed-out mutation may still have been applied, so retry it with the same idempotency key.

InvalidCursorError

class InvalidCursorError extends RangeError {
  readonly code: "INVALID_CURSOR";
  constructor(message: string);
}

The client’s own class for a 400 INVALID_CURSOR.

AccessibleListingError

class AccessibleListingError extends RangeError {
  readonly code: AccessibleListingErrorCode;
  constructor(code: AccessibleListingErrorCode, message: string);
}

The client’s own class for a listing 400.

AccessListingUnavailableError

class AccessListingUnavailableError extends Error {
  readonly code: "ACCESS_LISTING_UNAVAILABLE";
  readonly reason: WireAccessListingUnavailableReason;
  constructor(reason: WireAccessListingUnavailableReason, message: string);
}

Thrown by listAccessible when the server answers HTTP 503 with a body that is exactly the listing refusal of WireError: the code ACCESS_LISTING_UNAVAILABLE, a message, and an allowlisted reason. Only that status on that operation produces this class; the same code on any other response is an ordinary SharingHttpError. The server returned no page, partial page, or weaker page. The class has code and reason and no status. It extends Error, not RangeError, and is the client’s own class: it is not instanceof the AccessListingUnavailableError of @rolebook/sharing, and not a SharingHttpError.

The body is validated against the closed error schema before any error is constructed. A body with a missing or unknown reason, a reason beside another code, issues beside this code, or any extra member does not match and throws SharingHttpError with UNEXPECTED_RESPONSE, like every other response that is not the wire contract.

HierarchyUnavailableError

class HierarchyUnavailableError extends Error {
  readonly code: "HIERARCHY_UNAVAILABLE";
  readonly reason: WireHierarchyUnavailableReason;
  constructor(reason: WireHierarchyUnavailableReason, message: string);
}

Thrown by any client operation when the server answers HTTP 503 with the closed HIERARCHY_UNAVAILABLE body of WireError: the tenant’s hierarchy state could not be used and nothing was decided, listed or applied. reason is the server’s allowlisted cause. Like AccessListingUnavailableError, it is the client’s own class, not instanceof the @rolebook/sharing class and not a SharingHttpError; a body that does not match the closed schema throws SharingHttpError with UNEXPECTED_RESPONSE.

AuditHistoryError

class AuditHistoryError extends RangeError {
  readonly code: AuditHistoryErrorCode;
  constructor(code: AuditHistoryErrorCode, message: string);
}

The client’s own class for an audit 400.

Revived results

ClientAccessDescriptionResult

type ClientAccessDescriptionResult<TRole extends string = string, TType extends string = string> =
  | {
      readonly ok: true;
      readonly code: "DESCRIBED";
      readonly access: ClientAccessDescription<TRole, TType>;
    }
  | {
      readonly ok: false;
      readonly code: "NOT_FOUND_OR_DENIED";
    };

describeAccess() with timestamps revived to Date.

ClientAccessDescription

interface ClientAccessDescription<TRole extends string = string, TType extends string = string> {
  readonly resource: ResourceKey<TType>;
  readonly sharingRevision: string;
  readonly owner: ClientOwnership;
  readonly members: readonly ClientAccessMember<TRole>[];
  readonly invitations?: readonly ClientPendingInvitation<TRole>[];
}

ClientAccessMember

type ClientAccessMember<TRole extends string = string> = Omit<
  WireAccessMember<TRole>,
  "createdAt" | "expiresAt"
> & {
  readonly createdAt: Date;
  readonly expiresAt?: Date;
};

ClientOwnership

type ClientOwnership = Omit<WireOwnership, "createdAt"> & {
  readonly createdAt: Date;
};

ClientPendingInvitation

type ClientPendingInvitation<TRole extends string = string> = Omit<
  WirePendingInvitation<TRole>,
  "expiresAt" | "membershipExpiresAt" | "createdAt"
> & {
  readonly expiresAt: Date;
  readonly membershipExpiresAt?: Date;
  readonly createdAt: Date;
};

ClientAuditHistoryResult

type ClientAuditHistoryResult<TType extends string = string> =
  | {
      readonly ok: true;
      readonly code: "LISTED";
      readonly page: ClientAuditHistoryPage<TType>;
    }
  | {
      readonly ok: false;
      readonly code: "NOT_FOUND_OR_DENIED";
    };

auditHistory() with timestamps revived to Date.

ClientAuditHistoryPage

interface ClientAuditHistoryPage<TType extends string = string> {
  readonly resource: ResourceKey<TType>;
  readonly events: readonly ClientAuditEvent[];
  readonly nextCursor?: string;
  readonly exhausted: boolean;
}

ClientAuditEvent

type ClientAuditEvent = Omit<WireAuditEvent, "occurredAt"> & {
  readonly occurredAt: Date;
};

Wire types

Re-exported from @rolebook/http; their declarations are on the @rolebook/http page.

WireHierarchyUnavailableReason

See WireHierarchyUnavailableReason.

WireSharingDecision

See WireSharingDecision.

WireResourcePermissionsResult

See WireResourcePermissionsResult.

WireResourcePermissions

See WireResourcePermissions.

WireDecision

See WireDecision.

WireAccessDescriptionResult

See WireAccessDescriptionResult.

WireAccessDescription

See WireAccessDescription.

WireAccessMember

See WireAccessMember.

WireOwnership

See WireOwnership.

WirePendingInvitation

See WirePendingInvitation.

WireAccessiblePage

See WireAccessiblePage.

WireAccessibleResource

See WireAccessibleResource.

WireAuditHistoryResult

See WireAuditHistoryResult.

WireAuditHistoryPage

See WireAuditHistoryPage.

WireAuditEvent

See WireAuditEvent.

WireMutationResult

See WireMutationResult.

WireMutationFailureCode

See WireMutationFailureCode.

WireRef

See WireRef.

WireDateTime

See WireDateTime.

WireError

See WireError.

WireErrorCode

See WireErrorCode.

WireIssue

See WireIssue.

HttpInspectionResult

See HttpInspectionResult.