RolebookDocs

React components

@rolebook/react: accessible sharing screens and headless state for the Rolebook Sharing HTTP API.

@rolebook/react gives you ready-to-use React components and headless state for building sharing screens over the Rolebook Sharing HTTP API and @rolebook/client.

  • @rolebook/react provides SharingProvider, hooks (useSharingAccess, useSharingMutations, useAuditLog, useOffered), and accessible components: MembersList, InviteMember, OwnershipTransfer, AuditLog, IntentPanel, and ConfirmDialog.
  • @rolebook/react/core provides the framework-neutral state stores, idempotent mutation runner, and message catalog, with no React import.

Your server still authorizes every read and write. Permission hints in the browser only decide which controls to offer.

Install

Not on npm yet

@rolebook/react, @rolebook/client and @rolebook/sharing are not on npm yet. The npm package named rolebook is an unrelated project, so do not install it.

react (18.3 or 19), @rolebook/client, and @rolebook/sharing are peer dependencies. The package has no runtime dependencies of its own.

If you use Better Auth, @rolebook/better-auth/react wraps SharingProvider with RolebookSharingProvider, keeps scope in sync with the Better Auth session, and adds useCan(resource, action).

Use the components

Wrap your sharing UI in SharingProvider, passing your @rolebook/client instance, the current signed-in scope, and the action names from your Sharing definition:

import { createSharingClient } from "@rolebook/client";
import {
  AuditLog,
  type DirectorySearch,
  InviteMember,
  MembersList,
  OwnershipTransfer,
  SharingProvider,
  type SubjectRef,
} from "@rolebook/react";

const client = createSharingClient({ baseUrl: "/api/sharing" });
const roles = [
  { value: "viewer", label: "Viewer" },
  { value: "editor", label: "Editor" },
];

export function ProjectSharing({
  session,
  projectId,
  searchWorkspaceMembers,
  directoryName,
}: {
  session: { userId: string; tenantId: string; policyVersion: string; mfa?: boolean };
  projectId: string;
  searchWorkspaceMembers: DirectorySearch;
  directoryName: (subject: SubjectRef) => string;
}) {
  const resource = { type: "project", id: projectId };
  return (
    <SharingProvider
      client={client}
      scope={{
        actor: session.userId,
        tenant: session.tenantId,
        policy: session.policyVersion,
        ...(session.mfa ? { context: "mfa" } : {}),
      }}
      actions={{
        members: "manage_members",
        invitations: "manage_invitations",
        ownership: "transfer_ownership",
      }}
      onInvitationIssued={({ invitationId, token }) => ({
        copyLink: () =>
          navigator.clipboard.writeText(`${location.origin}/join/${invitationId}#${token}`),
      })}
      searchDirectory={searchWorkspaceMembers}
      describeSubject={directoryName}
    >
      <MembersList resource={resource} roles={roles} />
      <InviteMember resource={resource} roles={roles} />
      <OwnershipTransfer resource={resource} formerOwnerRoles={roles} />
      <AuditLog resource={resource} />
    </SharingProvider>
  );
}

Keep scope aligned with the active session that client sends: scope keys browser caches and in-flight intents and is never sent to the server. Update scope whenever the user, tenant, policy version, or MFA state changes.

Only pass retryWindow={{ serverRetentionMs }} once you know your deployment’s guaranteed idempotency retention (pruneSettledRecords retention minus safety margin). Leaving retryWindow unset keeps retries disabled (RETRY_WINDOW_UNDECLARED). Never hardcode a window longer than your server retains idempotency records: retrying after the server has pruned a record could replay a grant that was later revoked.

What the package handles for you

  • Hints stay hints. permissions() maps to "allowed", "not_allowed", or "no_hint". While access is being re-read, controls stay mounted with aria-disabled="true" so users keep focus and drafts, and the server still enforces delegation limits on every write.
  • No accidental duplicate writes. Mutations are admitted atomically under an idempotency key scoped to tenant, actor, and command across clicks and browser tabs (localStorage + Web Locks by default, or a custom intentStore).
  • Safe handling of unknown outcomes. If a network drop leaves a write’s outcome unknown, nothing retries automatically. Users explicitly choose retry() (reusing the original idempotency key within retryWindow) or release the blocked intent.
  • Minimal browser storage. The browser stores only digests, keys, statuses, and timestamps, never payloads, emails, roles, or invitation tokens. Invitation tokens go once to onInvitationIssued.
  • Accessibility. Labelled controls and tables, live status and alert regions, focus-trapped confirmation dialogs, and customizable messages / formatMessage for localization.

Headless usage (@rolebook/react/core)

Use @rolebook/react/core when you want the same access cache, hints, and safe mutation runner without React:

import { createSharingClient } from "@rolebook/client";
import {
  createIntentRegistry,
  createSharingAccessStore,
  createSharingMutationRunner,
  type SharingScope,
} from "@rolebook/react/core";

const client = createSharingClient({ baseUrl: "/api/sharing" });
const scope: SharingScope = { actor: "user_1", tenant: "org_1", policy: "1" };

const access = createSharingAccessStore({
  client,
  actions: { members: "manage_members" },
});
const runner = createSharingMutationRunner({
  client,
  registry: createIntentRegistry(),
  onChanged: (changedScope, resource) => void access.invalidate(changedScope, resource),
});

const outcome = await runner.submit(scope, {
  kind: "grantRole",
  resource: { type: "project", id: "p1" },
  subject: { type: "user", id: "u2" },
  role: "viewer",
});
outcome.status;

API

Signatures are checked against the built declarations.

Exports of @rolebook/react

ConfirmDialog

function ConfirmDialog(props: ConfirmDialogProps): ReactNode;

ConfirmDialogProps

interface ConfirmDialogProps {
  readonly title: string;
  readonly children?: ReactNode;
  readonly confirmLabel: string;
  readonly onConfirm: () => void;
  readonly onCancel: () => void;
}

useAnnouncer

function useAnnouncer(): {
  readonly announce: (tone: "status" | "alert", text: string) => void;
  readonly announceOutcome: (outcome: SharingMutationOutcome) => void;
  readonly announceKey: (tone: "status" | "alert", key: SharingMessageKey) => void;
  readonly clear: () => void;
  readonly regions: ReactNode;
};

AuditLog

function AuditLog(props: AuditLogProps): ReactNode;

AuditLogProps

interface AuditLogProps {
  readonly resource: SharingResource;
  readonly pageSize?: number;
}

DirectoryEntry

interface DirectoryEntry {
  readonly subject: SubjectRef;
  readonly label: string;
  readonly detail?: string;
}

DirectorySearch

type DirectorySearch = (query: string, context: {
  readonly resource: SharingResource;
  readonly purpose: "invite" | "transfer";
  readonly signal: AbortSignal;
}) => Promise<readonly DirectoryEntry[]>;

SharingContextValue

interface SharingContextValue {
  readonly scope: SharingScope;
  readonly access: SharingAccessStore;
  readonly runner: SharingMutationRunner;
  readonly client: SharingKitClient;
  readonly offerWithoutHint: boolean;
  readonly searchDirectory: DirectorySearch | undefined;
  readonly describeSubject: (subject: SubjectRef) => string;
  readonly t: (key: SharingMessageKey, params?: SharingMessageParams) => string;
  readonly now: () => number;
}

SharingProvider

function SharingProvider(props: SharingProviderProps): ReactNode;

SharingProviderProps

interface SharingProviderProps {
  readonly client: SharingKitClient;
  readonly scope: SharingScope;
  readonly actions?: SharingActionMap;
  readonly offerWithoutHint?: boolean;
  readonly intentStore?: IntentStore;
  readonly retryWindow?: RetryWindow;
  readonly retryCommands?: RetryCommandStore;
  readonly resolveOutcome?: OutcomeResolver;
  readonly acknowledgeDuplicateRisk?: DuplicateRiskAcknowledger;
  readonly onInvitationIssued?: InvitationIssuedCallback;
  readonly searchDirectory?: DirectorySearch;
  readonly describeSubject?: (subject: SubjectRef) => string;
  readonly messages?: Partial<SharingMessages>;
  readonly formatMessage?: SharingMessageFormatter;
  readonly freshForMs?: number;
  readonly now?: () => number;
  readonly newKey?: () => string;
  readonly children?: ReactNode;
}

useSharingContext

function useSharingContext(): SharingContextValue;

SharingMutations

interface SharingMutations {
  readonly busy: boolean;
  readonly outcome: SharingMutationOutcome | undefined;
  readonly unresolved: readonly UnresolvedIntent[];
  readonly unresolvedError: SharingKitUnavailableCode | undefined;
  readonly capabilities: {
    readonly retry: boolean;
    readonly resolve: boolean;
    readonly release: boolean;
  };
  submit(command: SharingKitCommand): Promise<SharingMutationOutcome>;
  retry(intentId: string, command?: SharingKitCommand): Promise<SharingMutationOutcome>;
  reconcile(intentId: string): Promise<SharingMutationOutcome>;
  abandon(intentId: string): Promise<SharingMutationOutcome>;
  release(intentId: string): Promise<SharingMutationOutcome>;
  refresh(): void;
  clearOutcome(): void;
}

useAuditLog

function useAuditLog(resourceInput: SharingResource, pageSize?: number): {
  readonly state: SharingAuditState;
  readonly loadMore: () => void;
  readonly reload: () => void;
};

useOffered

function useOffered(hint: SharingHint): boolean;

useSharingAccess

function useSharingAccess(resourceInput: SharingResource): {
  readonly state: SharingAccessState;
  readonly reload: () => void;
};

useSharingMessages

function useSharingMessages(): (key: import("../core.js").SharingMessageKey, params?: import("../core.js").SharingMessageParams) => string;

useSharingMutations

function useSharingMutations(resourceInput: SharingResource): SharingMutations;

IntentPanel

function IntentPanel({ mutations, onOutcome }: IntentPanelProps): ReactNode;

IntentPanelProps

interface IntentPanelProps {
  readonly mutations: SharingMutations;
  readonly onOutcome: (outcome: SharingMutationOutcome) => void;
}

InviteMember

function InviteMember(props: InviteMemberProps): ReactNode;

InviteMemberProps

interface InviteMemberProps {
  readonly resource: SharingResource;
  readonly roles: readonly RoleOption[];
  readonly allowEmail?: boolean;
  readonly defaultExpiresInMs?: number;
}

MembersList

function MembersList(props: MembersListProps): ReactNode;

MembersListProps

interface MembersListProps {
  readonly resource: SharingResource;
  readonly roles?: readonly RoleOption[];
  readonly resourceLabel?: string;
  readonly allowExpiry?: boolean;
}

RoleOption

interface RoleOption {
  readonly value: string;
  readonly label: string;
}

OwnershipTransfer

function OwnershipTransfer(props: OwnershipTransferProps): ReactNode;

OwnershipTransferProps

interface OwnershipTransferProps {
  readonly resource: SharingResource;
  readonly formerOwnerRoles?: readonly RoleOption[];
  readonly subjectType?: string;
}

Exports of @rolebook/react/core

ACCESS_LOADING

const ACCESS_LOADING: SharingAccessState;

createSharingAccessStore

function createSharingAccessStore(options: SharingAccessStoreOptions): SharingAccessStore;

hintsFrom

function hintsFrom(result: WireResourcePermissionsResult, actions: SharingActionMap, resource: SharingResource, sharingRevision: string): SharingActionHints;

NO_HINTS

const NO_HINTS: SharingActionHints;

SharingAccessState

type SharingAccessState = {
  readonly status: "loading";
} | {
  readonly status: "fresh";
  readonly access: ClientAccessDescription;
  readonly hints: SharingActionHints;
  readonly readAt: number;
} | {
  readonly status: "stale";
  readonly access: ClientAccessDescription;
  readonly hints: SharingActionHints;
  readonly lastHints: SharingActionHints;
  readonly readAt: number;
} | {
  readonly status: "denied";
} | {
  readonly status: "unavailable";
  readonly code: string;
};

SharingAccessStore

interface SharingAccessStore {
  get(key: string): SharingAccessState;
  subscribe(key: string, listener: () => void): () => void;
  load(scope: SharingScope, resource: SharingResource, options?: {
    readonly force?: boolean;
  }): Promise<SharingAccessState>;
  invalidate(scope: SharingScope, resource: SharingResource): Promise<SharingAccessState>;
  retain(scope: SharingScope): void;
  clear(): void;
}

SharingAccessStoreOptions

interface SharingAccessStoreOptions {
  readonly client: SharingKitClient;
  readonly actions: SharingActionMap;
  readonly freshForMs?: number;
  readonly now?: () => number;
}

SharingActionHints

interface SharingActionHints {
  readonly members: SharingHint;
  readonly invitations: SharingHint;
  readonly ownership: SharingHint;
  readonly audit: SharingHint;
}

SharingActionMap

interface SharingActionMap {
  readonly members?: string;
  readonly invitations?: string;
  readonly ownership?: string;
  readonly audit?: string;
}

SharingHint

type SharingHint = "allowed" | "not_allowed" | "no_hint";

AUDIT_LOADING

const AUDIT_LOADING: SharingAuditState;

readAuditPage

function readAuditPage(client: SharingKitClient, resource: SharingResource, limit: number, previous: readonly ClientAuditEvent[], cursor?: string): Promise<SharingAuditState>;

SharingAuditState

type SharingAuditState = {
  readonly status: "loading";
} | {
  readonly status: "ready";
  readonly events: readonly ClientAuditEvent[];
  readonly nextCursor?: string;
  readonly loadingMore: boolean;
} | {
  readonly status: "denied";
} | {
  readonly status: "unavailable";
  readonly code: string;
  readonly events: readonly ClientAuditEvent[];
};

canonicalJson

function canonicalJson(value: unknown): string;

sha256Hex

function sha256Hex(text: string): Promise<string>;

errorCode

function errorCode(error: unknown): string;

provesNotApplied

function provesNotApplied(error: unknown): boolean;

SharingKitClient

interface SharingKitClient {
  describeAccess(input: {
    readonly resource: SharingResource;
  }): Promise<ClientAccessDescriptionResult>;
  permissions(input: {
    readonly resource: SharingResource;
  }): Promise<WireResourcePermissionsResult>;
  auditHistory(input: {
    readonly resource: SharingResource;
    readonly limit: number;
    readonly cursor?: string;
  }): Promise<ClientAuditHistoryResult>;
  execute(command: SharingCommand<SharingResourceConfigurations>): Promise<WireMutationResult>;
}

describeOutcome

function describeOutcome(outcome: SharingMutationOutcome): OutcomeAnnouncement;

OutcomeAnnouncement

interface OutcomeAnnouncement {
  readonly tone: "status" | "alert";
  readonly key: SharingMessageKey;
}

SharingCommandError

class SharingCommandError extends TypeError {
  readonly code: "COMMAND_INVALID";
  constructor(message: string);
}

SharingKitUnavailableCode

type SharingKitUnavailableCode = "CRYPTO_UNAVAILABLE" | "STORAGE_UNAVAILABLE" | "ATOMICITY_UNAVAILABLE" | "INVITATION_CALLBACK_MISSING" | "IDEMPOTENCY_KEY_INVALID";

SharingKitUnavailableError

class SharingKitUnavailableError extends Error {
  readonly code: SharingKitUnavailableCode;
  constructor(code: SharingKitUnavailableCode, message: string);
}

createBrowserIntentStore

function createBrowserIntentStore(prefix?: string): IntentStore;

createMemoryIntentStore

function createMemoryIntentStore(): IntentStore;

createWebStorageIntentStore

function createWebStorageIntentStore(options: {
  readonly storage: IntentWebStorage | undefined;
  readonly locks: IntentLockManager | undefined;
  readonly prefix?: string;
}): IntentStore;

IntentLockManager

interface IntentLockManager {
  request<T>(name: string, options: {
    readonly mode: "exclusive";
  }, callback: () => Promise<T> | T): Promise<T>;
}

IntentStore

interface IntentStore {
  readonly durability: "durable" | "memory";
  update(id: string, change: (current: string | null) => string | null | undefined): Promise<string | null>;
  read(id: string): Promise<string | null>;
  entries(): Promise<readonly (readonly [
    string,
    string
  ])[]>;
}

IntentWebStorage

interface IntentWebStorage {
  readonly length: number;
  key(index: number): string | null;
  getItem(key: string): string | null;
  setItem(key: string, value: string): void;
  removeItem(key: string): void;
}

BeginResult

type BeginResult = {
  readonly admitted: true;
  readonly projected: ProjectedCommand;
  readonly record: IntentRecord;
} | {
  readonly admitted: false;
  readonly projected: ProjectedCommand;
  readonly record: IntentRecord;
};

createIntentRegistry

function createIntentRegistry(options?: IntentRegistryOptions): IntentRegistry;

IDEMPOTENCY_KEY_PATTERN

const IDEMPOTENCY_KEY_PATTERN: RegExp;

IntentRecord

interface IntentRecord {
  readonly intentId: string;
  readonly resourceDigest: string;
  readonly kind: SharingKitCommandKind;
  readonly idempotencyKey: string;
  readonly status: IntentStatus;
  readonly createdAt: number;
  readonly sentAt: number;
  readonly updatedAt: number;
  readonly retentionMs: number | null;
  readonly attempts: number;
}

IntentRegistry

interface IntentRegistry {
  readonly retryWindow: RetryWindow | undefined;
  begin(input: {
    readonly scope: SharingScope;
    readonly command: unknown;
  } | {
    readonly scope: SharingScope;
    readonly projected: ProjectedCommand;
  }): Promise<BeginResult>;
  get(intentId: string): Promise<IntentRecord | undefined>;
  transition(intentId: string, idempotencyKey: string, change: (record: IntentRecord) => IntentRecord | null | undefined): Promise<{
    readonly changed: boolean;
    readonly record: IntentRecord | undefined;
  }>;
  list(scope: SharingScope, resource: SharingResource): Promise<readonly IntentRecord[]>;
  preserve(record: IntentRecord, at: number): Promise<PreservedFence>;
}

IntentRegistryOptions

interface IntentRegistryOptions {
  readonly store?: IntentStore;
  readonly newKey?: () => string;
  readonly now?: () => number;
  readonly retryWindow?: RetryWindow;
}

IntentStatus

type IntentStatus = "pending" | "unknown" | "abandoned";

parseIntentRecord

function parseIntentRecord(intentId: string, text: string): IntentRecord | undefined;

RetryBlockReason

type RetryBlockReason = "RETRY_WINDOW_UNDECLARED" | "RETRY_WINDOW_EXPIRED" | "CLOCK_ROLLBACK";

retryBlock

function retryBlock(record: IntentRecord, now: number, window: RetryWindow | undefined): RetryBlockReason | undefined;

RetryWindow

interface RetryWindow {
  readonly serverRetentionMs: number;
}

createMessageFormatter

function createMessageFormatter(overrides?: Partial<SharingMessages>, format?: SharingMessageFormatter): SharingMessageFormatter;

DEFAULT_MESSAGES

const DEFAULT_MESSAGES: Readonly<{
  "access.loading": "Loading access…";
  "access.stale": "Showing the last known access while it is refreshed.";
  "access.denied": "This resource was not found, or you cannot view who has access.";
  "access.unavailable": "Access could not be loaded. Try again.";
  "access.retry": "Reload access";
  "members.title": "People with access";
  "members.caption": "Owner and members of {resource}";
  "members.column.member": "Member";
  "members.column.role": "Role";
  "members.column.expires": "Access ends";
  "members.column.actions": "Actions";
  "members.owner": "Owner";
  "members.never": "Never";
  "members.empty": "No members besides the owner.";
  "members.roleFor": "Role for {member}";
  "members.expiryFor": "Access end for {member}";
  "members.clearExpiryFor": "Remove access end for {member}";
  "members.save": "Save changes for {member}";
  "members.revoke": "Remove {member}";
  "members.revokeTitle": "Remove {member}?";
  "members.revokeBody": "{member} loses access granted by this membership.";
  "members.invitations": "Pending invitations";
  "members.invitationTo": "Invitation to {recipient} as {role}, expires {expires}";
  "members.revokeInvitation": "Revoke invitation to {recipient}";
  "members.noHint": "Permission could not be confirmed; the server will decide.";
  "invite.title": "Invite someone";
  "invite.search": "Search people";
  "invite.searchButton": "Search";
  "invite.results": "Search results";
  "invite.noResults": "No people found.";
  "invite.resultCount": "{count} people found.";
  "invite.recipientConflict": "Choose either a person or an email address, not both.";
  "invite.email": "Email address";
  "invite.role": "Role";
  "invite.expires": "Invitation expires";
  "invite.membershipExpires": "Access ends (optional)";
  "invite.submit": "Send invitation";
  "invite.recipientRequired": "Choose a person or enter an email address.";
  "invite.expiryRequired": "Enter a valid invitation expiry.";
  "invite.membershipExpiryInvalid": "Enter a valid access end, or leave it empty.";
  "invite.sent": "Invitation created.";
  "invite.copyLink": "Copy invitation link";
  "invite.copied": "Invitation link copied. It cannot be shown again.";
  "invite.copyFailed": "The link could not be copied. Revoke this invitation and send a new one.";
  "invite.deliveryFailed": "The invitation was created, but its link could not be delivered. Revoke it and send a new one.";
  "invite.tokenLost": "The invitation exists, but its link was only available to the first response and cannot be shown. Revoke it from pending invitations and send a new one.";
  "transfer.title": "Transfer ownership";
  "transfer.search": "Search for the new owner";
  "transfer.subjectId": "New owner's user ID";
  "transfer.formerRole": "Your role after the transfer";
  "transfer.formerRoleNone": "No role (lose access)";
  "transfer.submit": "Transfer ownership";
  "transfer.confirmTitle": "Transfer ownership to {member}?";
  "transfer.confirmBody": "Only the new owner can transfer it back.";
  "transfer.recipientRequired": "Choose the new owner.";
  "transfer.done": "Ownership transferred.";
  "audit.title": "Activity";
  "audit.empty": "No activity yet.";
  "audit.loadMore": "Load older activity";
  "audit.loading": "Loading activity…";
  "audit.denied": "You cannot view this resource's activity.";
  "audit.unavailable": "Activity could not be loaded.";
  "audit.event": "{actor} {action}{subject}";
  "audit.subject": " {subject}";
  "audit.action.member.granted": "granted access to";
  "audit.action.member.role_changed": "changed the role of";
  "audit.action.member.revoked": "removed";
  "audit.action.ownership.transferred": "transferred ownership to";
  "audit.action.invitation.issued": "invited";
  "audit.action.invitation.consumed": "accepted an invitation";
  "audit.action.invitation.revoked": "revoked an invitation";
  "audit.action.resource.initialized": "created the resource";
  "audit.action.resource.deleted": "deleted the resource";
  "audit.action.resource.moved": "moved the resource";
  "audit.action.unknown": "made a change";
  "dialog.confirm": "Confirm";
  "dialog.cancel": "Cancel";
  "outcome.applied": "Done.";
  "outcome.alreadyApplied": "This change had already been applied.";
  "outcome.resolvedApplied": "Confirmed: the change was applied.";
  "outcome.notApplied": "The change was not applied.";
  "outcome.unknown": "We could not confirm whether the change was applied. It will not be sent again automatically.";
  "outcome.retryRefused": "The retry was refused. That does not show whether the original change was applied.";
  "outcome.pending": "Sending…";
  "outcome.recordRetained": "The change was applied, but this browser could not record that. Check its status before repeating it.";
  "outcome.abandoned": "Stopped waiting. The same change stays blocked until it is resolved.";
  "outcome.released": "Released. The same change can be sent again.";
  "intent.title": "Changes waiting for confirmation";
  "intent.item": "{kind} — {status}, first sent {sentAt}";
  "intent.status.pending": "sending or unconfirmed";
  "intent.status.unknown": "outcome unknown";
  "intent.status.abandoned": "stopped waiting, unresolved";
  "intent.retry": "Retry {kind}";
  "intent.reconcile": "Check status of {kind}";
  "intent.abandon": "Stop waiting for {kind}";
  "intent.release": "Allow sending {kind} again";
  "intent.abandonTitle": "Stop waiting for this change?";
  "intent.abandonBody": "It may already have been applied. It stays recorded and blocks the identical change until its status is checked or you allow it explicitly.";
  "intent.kind.grantRole": "Grant access";
  "intent.kind.changeRole": "Change role";
  "intent.kind.revokeMember": "Remove member";
  "intent.kind.transferOwnership": "Transfer ownership";
  "intent.kind.issueInvitation": "Invitation";
  "intent.kind.revokeInvitation": "Revoke invitation";
  "blocked.UNRESOLVED_INTENT": "An identical change is still unconfirmed. Retry it or check its status below instead of sending it again.";
  "blocked.IN_FLIGHT": "This change is already being sent.";
  "blocked.STORAGE_FAULT": "This browser's storage could not record an earlier change's status, so nothing more is sent from this page until it can, or that change's status is checked.";
  "outcome.storageFault": "The outcome of this change is unknown, and this browser's storage could not record that. Nothing more is sent from this page until it can; check the change's status before repeating it.";
  "intent.storageFault": "not recorded in this browser's storage";
  "blocked.ABANDONED_NEEDS_RESOLUTION": "An identical change was abandoned without confirmation. Check its status before sending it again.";
  "blocked.RETRY_WINDOW_UNDECLARED": "Retrying is not enabled for this application.";
  "blocked.RETRY_WINDOW_EXPIRED": "This change is too old to retry safely. Check its status instead.";
  "blocked.CLOCK_ROLLBACK": "The device clock moved backwards. Retrying is blocked.";
  "blocked.RETRY_COMMAND_UNAVAILABLE": "The original change is not available to retry. Submit the identical change again to retry it.";
  "blocked.COMMAND_MISMATCH": "That is not the same change.";
  "blocked.RESOURCE_UNAVAILABLE": "The resource can no longer be reached, so the change is not retried.";
  "blocked.NOT_FOUND": "That change is no longer recorded.";
  "blocked.RESOLVER_MISSING": "Status checks are not available in this application.";
  "blocked.ACKNOWLEDGEMENT_REQUIRED": "Sending this change again was not acknowledged.";
  "unavailable.CRYPTO_UNAVAILABLE": "This browser cannot make changes safely (no Web Crypto).";
  "unavailable.STORAGE_UNAVAILABLE": "Changes are unavailable: this browser's storage cannot be used.";
  "unavailable.ATOMICITY_UNAVAILABLE": "Changes are unavailable: this browser cannot coordinate them between tabs.";
  "unavailable.INVITATION_CALLBACK_MISSING": "Invitations are not set up in this application.";
  "unavailable.IDEMPOTENCY_KEY_INVALID": "Changes are unavailable: invalid request key.";
  "invalid.COMMAND_INVALID": "Some values are not valid.";
  "error.generic": "Something went wrong.";
  "error.NOT_FOUND_OR_DENIED": "The resource was not found, or you are not allowed to do that.";
  "error.FORBIDDEN": "You are not allowed to do that.";
  "error.NOT_TENANT_MEMBER": "That person is not a member of this workspace.";
  "error.ROLE_NOT_ALLOWED": "That role cannot be given here.";
  "error.SELF_PROMOTION": "You cannot change your own access.";
  "error.OWNER_TRANSFER_REQUIRED": "The owner's access can only change through an ownership transfer.";
  "error.GROUP_CANNOT_OWN": "A group cannot own a resource.";
  "error.MEMBER_ALREADY_EXISTS": "That person already has access.";
  "error.INVITATION_EXPIRED": "The invitation expiry must be in the future.";
  "error.INVITATION_RECIPIENT_INVALID": "That recipient is not valid.";
  "error.INVITATION_UNAVAILABLE": "That invitation is no longer available.";
  "error.INVITATION_RECIPIENT_MISMATCH": "That invitation is for someone else.";
  "error.MEMBERSHIP_EXPIRY_INVALID": "The access end date is not valid.";
  "error.CONFLICT": "Something changed at the same time. Reload and try again.";
  "error.POLICY_GENERATION_CHANGED": "Access rules changed. Reload and try again.";
  "error.TENANT_ROLES_CHANGED": "Roles changed. Reload and try again.";
  "error.POLICY_UNAVAILABLE": "Access rules are temporarily unavailable.";
  "error.UNAUTHENTICATED": "Your session has ended. Sign in again.";
  "error.CSRF": "The request was rejected. Reload the page.";
  "error.INVALID_REQUEST": "The request was not valid.";
  "error.TIMEOUT": "The server did not answer in time.";
  "error.NETWORK": "The server could not be reached.";
  "error.UNEXPECTED_RESPONSE": "The server sent an unexpected answer.";
  "error.INTERNAL": "The server had a problem.";
}>;

failureMessageKey

function failureMessageKey(code: string): SharingMessageKey;

interpolate

function interpolate(template: string, params: SharingMessageParams): string;

SharingMessageFormatter

type SharingMessageFormatter = (key: SharingMessageKey, params: SharingMessageParams) => string;

SharingMessageKey

type SharingMessageKey = keyof typeof DEFAULT_MESSAGES;

SharingMessageParams

type SharingMessageParams = Readonly<Record<string, string | number>>;

SharingMessages

type SharingMessages = {
  readonly [K in SharingMessageKey]: string;
};

createSharingMutationRunner

function createSharingMutationRunner(options: SharingMutationRunnerOptions): SharingMutationRunner;

DuplicateRiskAcknowledger

type DuplicateRiskAcknowledger = (intent: {
  readonly intentId: string;
  readonly kind: SharingKitCommandKind;
  readonly createdAt: number;
  readonly sentAt: number;
}) => boolean | Promise<boolean>;

InvitationHandoff

interface InvitationHandoff {
  readonly copyLink?: () => void | Promise<void>;
}

InvitationIssuedCallback

type InvitationIssuedCallback = (invitation: IssuedInvitation) => InvitationHandoff | undefined | Promise<InvitationHandoff | undefined>;

InvitationOutcome

type InvitationOutcome = {
  readonly delivery: "delivered";
  readonly invitationId: string;
} | {
  readonly delivery: "copy_available";
  readonly invitationId: string;
  readonly copyLink: () => Promise<boolean>;
} | {
  readonly delivery: "failed";
  readonly invitationId: string;
} | {
  readonly delivery: "token_lost";
};

IssuedInvitation

interface IssuedInvitation {
  readonly resource: SharingResource;
  readonly invitationId: string;
  readonly token: string;
}

MutationBlockReason

type MutationBlockReason = RetryBlockReason | "UNRESOLVED_INTENT" | "IN_FLIGHT" | "ABANDONED_NEEDS_RESOLUTION" | "RETRY_COMMAND_UNAVAILABLE" | "COMMAND_MISMATCH" | "RESOURCE_UNAVAILABLE" | "NOT_FOUND" | "RESOLVER_MISSING" | "STORAGE_FAULT" | "ACKNOWLEDGEMENT_REQUIRED";

OutcomeResolution

type OutcomeResolution = "applied" | "not_applied" | "unknown";

OutcomeResolver

type OutcomeResolver = (query: {
  readonly intentId: string;
  readonly idempotencyKey: string;
  readonly kind: SharingKitCommandKind;
  readonly createdAt: number;
  readonly sentAt: number;
}) => OutcomeResolution | Promise<OutcomeResolution>;

RetryCommandStore

interface RetryCommandStore {
  save(intentId: string, command: ProjectedCommand): void | Promise<void>;
  load(intentId: string): unknown;
  delete(intentId: string): void | Promise<void>;
}

SharingMutationOutcome

type SharingMutationOutcome = {
  readonly status: "applied";
  readonly kind: SharingKitCommandKind;
  readonly intentId: string;
  readonly code: "APPLIED" | "ALREADY_APPLIED" | "RESOLVED_APPLIED";
  readonly sharingRevision?: string;
  readonly invitation?: InvitationOutcome;
  readonly recordRetained?: true;
} | {
  readonly status: "not_applied";
  readonly kind: SharingKitCommandKind;
  readonly intentId: string;
  readonly code: string;
} | {
  readonly status: "unknown";
  readonly kind: SharingKitCommandKind;
  readonly intentId: string;
  readonly code: string;
  readonly retryRefusedCode?: string;
  readonly concurrentAttempt?: true;
  readonly settlementFailed?: true;
} | {
  readonly status: "blocked";
  readonly reason: MutationBlockReason;
  readonly kind?: SharingKitCommandKind;
  readonly intentId?: string;
  readonly intentStatus?: IntentStatus;
} | {
  readonly status: "storage_fault";
  readonly kind: SharingKitCommandKind;
  readonly intentId: string;
  readonly code: string;
} | {
  readonly status: "abandoned";
  readonly kind: SharingKitCommandKind;
  readonly intentId: string;
} | {
  readonly status: "released";
  readonly kind: SharingKitCommandKind;
  readonly intentId: string;
} | {
  readonly status: "unavailable";
  readonly code: SharingKitUnavailableCode;
  readonly kind?: SharingKitCommandKind;
} | {
  readonly status: "invalid";
  readonly code: "COMMAND_INVALID";
};

SharingMutationRunner

interface SharingMutationRunner {
  submit(scope: SharingScope, command: unknown): Promise<SharingMutationOutcome>;
  retry(scope: SharingScope, resource: SharingResource, intentId: string, options?: {
    readonly command?: unknown;
  }): Promise<SharingMutationOutcome>;
  reconcile(scope: SharingScope, resource: SharingResource, intentId: string): Promise<SharingMutationOutcome>;
  abandon(scope: SharingScope, resource: SharingResource, intentId: string): Promise<SharingMutationOutcome>;
  release(scope: SharingScope, resource: SharingResource, intentId: string): Promise<SharingMutationOutcome>;
  unresolved(scope: SharingScope, resource: SharingResource): Promise<readonly UnresolvedIntent[]>;
  readonly capabilities: {
    readonly retry: boolean;
    readonly resolve: boolean;
    readonly release: boolean;
  };
}

SharingMutationRunnerOptions

interface SharingMutationRunnerOptions {
  readonly client: SharingKitClient;
  readonly registry: IntentRegistry;
  readonly onInvitationIssued?: InvitationIssuedCallback;
  readonly resolveOutcome?: OutcomeResolver;
  readonly retryCommands?: RetryCommandStore;
  readonly acknowledgeDuplicateRisk?: DuplicateRiskAcknowledger;
  readonly onChanged?: (scope: SharingScope, resource: SharingResource) => void;
  readonly now?: () => number;
}

UnresolvedIntent

interface UnresolvedIntent {
  readonly intentId: string;
  readonly kind: SharingKitCommandKind;
  readonly status: IntentStatus;
  readonly createdAt: number;
  readonly sentAt: number;
  readonly attempts: number;
  readonly inFlight: boolean;
  readonly storageFault?: true;
  readonly retryBlocked?: RetryBlockReason | "IN_FLIGHT" | "ABANDONED_NEEDS_RESOLUTION";
}

commandFromProjection

function commandFromProjection(projected: ProjectedCommand, idempotencyKey: string): AnyCommand;

IntentIdentity

interface IntentIdentity {
  readonly intentId: string;
  readonly resourceDigest: string;
}

intentIdentity

function intentIdentity(scope: SharingScope, projected: ProjectedCommand): Promise<IntentIdentity>;

MAX_INVITATION_EMAIL_LENGTH

const MAX_INVITATION_EMAIL_LENGTH = 320;

MAX_OPAQUE_ID_LENGTH

const MAX_OPAQUE_ID_LENGTH = 128;

ProjectedCommand

type ProjectedCommand = {
  readonly kind: "grantRole";
  readonly resource: SharingResource;
  readonly subject: SubjectRef;
  readonly role: string;
  readonly expiresAt?: number;
} | {
  readonly kind: "changeRole";
  readonly resource: SharingResource;
  readonly subject: SubjectRef;
  readonly role: string;
  readonly expiresAt?: number | null;
} | {
  readonly kind: "revokeMember";
  readonly resource: SharingResource;
  readonly subject: SubjectRef;
} | {
  readonly kind: "transferOwnership";
  readonly resource: SharingResource;
  readonly to: SubjectRef;
  readonly formerOwnerRole: string | null;
} | {
  readonly kind: "issueInvitation";
  readonly resource: SharingResource;
  readonly recipient: {
    readonly type: "subject";
    readonly subject: SubjectRef;
  } | {
    readonly type: "email";
    readonly email: string;
  };
  readonly role: string;
  readonly expiresAt: number;
  readonly membershipExpiresAt?: number;
} | {
  readonly kind: "revokeInvitation";
  readonly resource: SharingResource;
  readonly invitationId: string;
};

projectCommand

function projectCommand(command: unknown): ProjectedCommand;

SharingKitCommand

type SharingKitCommand = WithoutKey<Exclude<AnyCommand, {
  readonly kind: "acceptInvitation";
}>>;

SharingKitCommandKind

type SharingKitCommandKind = SharingKitCommand["kind"];

baseScopeKey

function baseScopeKey(scope: SharingScope): string;

normalizeScope

function normalizeScope(scope: SharingScope): SharingScope;

scopeKey

function scopeKey(scope: SharingScope, resource: SharingResource): string;

SharingResource

interface SharingResource {
  readonly type: string;
  readonly id: string;
}

SharingScope

interface SharingScope {
  readonly actor: string;
  readonly tenant: string;
  readonly policy: string;
  readonly context?: string;
}

SubjectRef

interface SubjectRef {
  readonly type: string;
  readonly id: string;
}

On this page

InstallUse the componentsWhat the package handles for youHeadless usage (@rolebook/react/core)APIExports of @rolebook/reactConfirmDialogConfirmDialogPropsuseAnnouncerAuditLogAuditLogPropsDirectoryEntryDirectorySearchSharingContextValueSharingProviderSharingProviderPropsuseSharingContextSharingMutationsuseAuditLoguseOffereduseSharingAccessuseSharingMessagesuseSharingMutationsIntentPanelIntentPanelPropsInviteMemberInviteMemberPropsMembersListMembersListPropsRoleOptionOwnershipTransferOwnershipTransferPropsExports of @rolebook/react/coreACCESS_LOADINGcreateSharingAccessStorehintsFromNO_HINTSSharingAccessStateSharingAccessStoreSharingAccessStoreOptionsSharingActionHintsSharingActionMapSharingHintAUDIT_LOADINGreadAuditPageSharingAuditStatecanonicalJsonsha256HexerrorCodeprovesNotAppliedSharingKitClientdescribeOutcomeOutcomeAnnouncementSharingCommandErrorSharingKitUnavailableCodeSharingKitUnavailableErrorcreateBrowserIntentStorecreateMemoryIntentStorecreateWebStorageIntentStoreIntentLockManagerIntentStoreIntentWebStorageBeginResultcreateIntentRegistryIDEMPOTENCY_KEY_PATTERNIntentRecordIntentRegistryIntentRegistryOptionsIntentStatusparseIntentRecordRetryBlockReasonretryBlockRetryWindowcreateMessageFormatterDEFAULT_MESSAGESfailureMessageKeyinterpolateSharingMessageFormatterSharingMessageKeySharingMessageParamsSharingMessagescreateSharingMutationRunnerDuplicateRiskAcknowledgerInvitationHandoffInvitationIssuedCallbackInvitationOutcomeIssuedInvitationMutationBlockReasonOutcomeResolutionOutcomeResolverRetryCommandStoreSharingMutationOutcomeSharingMutationRunnerSharingMutationRunnerOptionsUnresolvedIntentcommandFromProjectionIntentIdentityintentIdentityMAX_INVITATION_EMAIL_LENGTHMAX_OPAQUE_ID_LENGTHProjectedCommandprojectCommandSharingKitCommandSharingKitCommandKindbaseScopeKeynormalizeScopescopeKeySharingResourceSharingScopeSubjectRef