Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions .agents/skills/hypercerts-org-sdk/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: hypercerts-org-sdk
description: "Write Hypercerts and Certified records (org.hypercerts.*, app.certified.*) to a PDS from an app with @hypercerts-org/sdk: setting up the SDK context from an authenticated @atproto/lex Client, choosing the right operation and subpath, uploading blobs, and handling write errors without duplicates. Use when app code imports @hypercerts-org/sdk, or the user wants to create, link or write hypercert-related records from an app. Not for changing the SDK's own source."
metadata:
author: hypercerts-org
version: "4"
version: "5"
---

# @hypercerts-org/sdk
Expand Down Expand Up @@ -40,11 +40,22 @@ export const context = createSDKContext({ client: new Client(session) });

Make a new context when the signed-in account changes. Records are always written to the account behind `client`.

To read another account's record (a `{ uri }` that is not in your repo), the SDK looks up that account's DID document to find its PDS. By default it uses its own resolver and keeps each document in memory for up to an hour per context. If the app has an `@atproto/oauth-client` (or `@atproto/oauth-client-node`) client, pass its resolver to reuse the cache it already has:

```ts
export const context = createSDKContext({
client: new Client(session),
didResolver: oauthClient.identityResolver, // the resolver, not `oauthClient` itself
});
```

`didResolver` accepts any object with `resolve(did)` that returns a DID document or `{ didDoc }`.

## 3. Import from subpaths

| Import from | Exports |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@hypercerts-org/sdk` | `createSDKContext`, `SDKContext` |
| `@hypercerts-org/sdk` | `createSDKContext`, `SDKContext`, `DidDocumentResolver` |
| `@hypercerts-org/sdk/activity` | `createActivity`, `createRights`, `createContribution`, `createContributorInformation`, `WriteError`, `WriteRejectedError`, `WriteOutcomeUnknownError`, `WriteResultMismatchError`, input/result types |
| `@hypercerts-org/sdk/actor` | `createProfile`, `ProfileAlreadyExistsError`, `RecordAlreadyExistsError`, the same `Write*` errors, `ProfileInput` |
| `@hypercerts-org/sdk/location` | `createLocation`, the same `Write*` errors, `LocationInput`, `LocationValue` |
Expand Down Expand Up @@ -178,6 +189,7 @@ try {
## Pitfalls

- `createSDKContext({ client: session })` or passing an `@atproto/api` `Agent` throws. Wrap it: `new Client(session)`.
- `didResolver: oauthClient` throws. Pass `oauthClient.identityResolver`.
- Passing an `uploadBlob` result as `image` throws. Pass the `Blob`/`File`.
- Retrying blindly after `WriteOutcomeUnknownError` duplicates every record under new keys. The exception is a call whose records all have a fixed key and are only created if absent: `createProfile` and `createVocabularyTag`. `createOrganization` is also safe to repeat: the organization exists at most once, so a second call creates it or throws `OrganizationAlreadyExistsError`. `createFeature`, `createCollection` and `createWorkScopeTag` are not safe to repeat.
- An item of `createCollection` is `{ activity }`, `{ feature }`, `{ collection }` or `{ uri }`, never a bare Activity input; `{ uri }` must be an Activity, Feature or Collection.
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/hypercerts-org-sdk/references/collection.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ collection.items[3]; // { uri, cid, type: "activity", created: false }
```

- An item is **exactly one** of `{ activity }`, `{ feature }`, `{ collection }` (the data of a new record, same input as `createActivity`, `createFeature` and `createCollection`) or `{ uri }`, plus an optional `weight`. The SDK never guesses from the fields: a bare Activity (`{ title, shortDescription }`) is a `TypeError`.
- `{ uri }` must be an Activity, Feature or Collection with a DID (`at://<did>/<collection>/<rkey>`). It is read for its CID and reused unchanged; it may belong to another account if public. Another record type, or a handle, is a `TypeError` naming the item.
- `{ uri }` must be an Activity, Feature or Collection with a DID (`at://<did>/<collection>/<rkey>`). It is read for its CID and reused unchanged; it may belong to another account if public. Another account's PDS is found with the context's `didResolver` ([SKILL.md](../SKILL.md#2-create-the-context-once)). Another record type, or a handle, is a `TypeError` naming the item.
- `weight` is a positive decimal string (`"2"`, `"0.50"`), stored exactly as you pass it. Weights need not add up to anything.
- Order is kept. Nothing is deduplicated or searched for: the same `{ uri }` twice gives two items, the same data twice gives two records.
- `location` and `tags` take new records or `{ uri }` like in `createFeature`. A new tag's key is `<category>.<key>`: a taken key throws `RecordAlreadyExistsError` before anything is uploaded or written, and two new tags with the same key anywhere in the call are a `TypeError` (create it first and pass its `uri`).
Expand Down
6 changes: 6 additions & 0 deletions .changeset/did-resolver-cache.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@hypercerts-org/sdk": minor
---

- Cache DID lookups per context, so repeated reads of another account's record no longer fetch from plc.directory each time.
- Add the `didResolver` option to `createSDKContext` and the `DidDocumentResolver` type. Pass `oauthClient.identityResolver` or your own resolver.
2 changes: 1 addition & 1 deletion docs/e2e-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pnpm test:e2e
- The tests leave their records and blobs in the two accounts. Each test counts records only around its own call, so earlier runs do not matter. Destroy the sandbox (`deno task sandbox destroy --accept-destructive`) to start clean.
- An account has one profile, so the `createProfile` tests delete the first account's profile (the `self` record) before each test.
- A vocabulary tag's key is chosen by the caller and cannot be reused, so the tag tests give every tag a key that is different on every run.
- To reuse another account's record, the SDK finds that account's PDS in the `plc.directory` DID document, and it cannot be pointed at another directory. The sandbox's accounts exist only in its own PLC directory, so `e2e/plc.ts` redirects requests for `https://plc.directory` to `SDK_E2E_PLC_URL` while those tests run.
- To reuse another account's record, the SDK finds that account's PDS in the `plc.directory` DID document, and its default DID resolver cannot be pointed at another directory (an application can pass its own `didResolver`). The sandbox's accounts exist only in its own PLC directory, so `e2e/plc.ts` redirects requests for `https://plc.directory` to `SDK_E2E_PLC_URL` while those tests run.
- One test uploads a 6 MiB file and expects the PDS to refuse it, which relies on the PDS's default upload limit of 5 MiB (`PDS_BLOB_UPLOAD_LIMIT`). Raise that limit in the sandbox and the test fails.
- The test files run one after the other because the tests count the records of the two shared accounts.

Expand Down
1 change: 1 addition & 0 deletions packages/sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"@hypercerts-org/lexicon": "^2.0.1"
},
"devDependencies": {
"@atproto-labs/identity-resolver": "0.4.13",
"@atproto/lex": "0.4.4",
"@hypercerts-org/lexicon": "2.0.1"
},
Expand Down
32 changes: 32 additions & 0 deletions packages/sdk/src/context.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Client } from "@atproto/lex";
import { createDidResolver, type DidResolver, DidResolverCommon } from "@atproto-labs/did-resolver";
import type { IdentityResolver } from "@atproto-labs/identity-resolver";
import { describe, expect, it } from "vitest";
import { createSDKContext } from "./context.js";

Expand Down Expand Up @@ -47,4 +49,34 @@ describe("createSDKContext", () => {
expect(create).toThrow(/new Client\(session\)/);
},
);

it("accepts a DidResolver or an oauth client's IdentityResolver as they are", () => {
// These assignments are the test: they fail to compile if either type stops fitting.
const didResolvers: DidResolver<"plc" | "web">[] = [
new DidResolverCommon(),
createDidResolver({}),
];
const identityResolver: IdentityResolver = {
resolve: () => Promise.reject(new Error("not called")),
};

for (const didResolver of [...didResolvers, identityResolver]) {
expect(createSDKContext({ client, didResolver }).didResolver).toBe(didResolver);
}
});

it.each([
["the oauth client instead of its identityResolver", { identityResolver: { resolve() {} } }],
["a function", () => undefined],
])(
"rejects a didResolver that is %s with a message that says how to fix it",
(_, didResolver) => {
// @ts-expect-error Deliberately not a `DidDocumentResolver`.
const create = () => createSDKContext({ client, didResolver });

expect(create).toThrow(TypeError);
expect(create).toThrow(/`didResolver` must be an object with a resolve\(did\) method/);
expect(create).toThrow(/oauthClient\.identityResolver/);
},
);
});
88 changes: 75 additions & 13 deletions packages/sdk/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import type { Client } from "@atproto/lex";
import type { AtprotoDid, AtprotoDidDocument } from "@atproto-labs/did-resolver";
import { describeValue } from "./internal/describe.js";
import { createDefaultDidResolver } from "./internal/resolve-pds.js";

/**
* Shared context passed as the first argument to every SDK operation.
*
* @remarks
* Create it once with {@link createSDKContext} and reuse it for every call. It is frozen and
* holds only the application's client: no session, credentials or HTTP client of its own.
* Create a new context when the application replaces its client, for example after signing in
* as another account.
* holds only the application's client and a DID resolver: no session, credentials or HTTP client
* of its own. Create a new context when the application replaces its client, for example after
* signing in as another account.
*
* @example
* ```ts
Expand All @@ -20,6 +22,28 @@ import { describeValue } from "./internal/describe.js";
export interface SDKContext {
/** The application's `@atproto/lex` client. Operations send all their requests through it. */
readonly client: Client;
/**
* Finds the DID document of an account other than the client's, to locate its PDS. The
* resolver passed to {@link createSDKContext}, or the SDK's cached default.
*/
readonly didResolver: DidDocumentResolver;
}

/**
* Resolves a DID to its DID document.
*
* @remarks
* Both of these satisfy it as they are:
* - an `@atproto-labs/did-resolver` `DidResolver`, which returns the document;
* - an `@atproto/oauth-client` `IdentityResolver` (`oauthClient.identityResolver`), which returns
* `{ did, didDoc, handle }`.
*
* The SDK only calls `resolve` with a `did:plc` or `did:web` DID and reads the PDS from the
* `#atproto_pds` service of the document. It does not check that the document's `id` is the DID
* it asked for, so the resolver is trusted to do that.
*/
export interface DidDocumentResolver {
resolve(did: AtprotoDid): Promise<AtprotoDidDocument | { readonly didDoc: AtprotoDidDocument }>;
}

/** Options for {@link createSDKContext}. */
Expand All @@ -32,6 +56,22 @@ export interface CreateSDKContextOptions {
* `new Client(session)` first.
*/
client: Client;
/**
* Resolves a DID to its DID document. Pass `oauthClient.identityResolver` or your own resolver
* to reuse its cache and settings; defaults to a resolver that reads `did:plc` from
* plc.directory and `did:web` from the domain, and keeps documents in memory for up to an hour.
*
* @remarks
* Used to find the PDS of another account when an operation reads a record that account owns
* (an `{ uri }` of someone else's record). Operations on the client's own repository never
* call it.
*
* The default is created per context, so every call that uses the same context shares its
* cache, and a document is not fetched again until it expires. A new context starts with an
* empty cache. Failed lookups are not cached. The default has no way to be pointed at another
* PLC directory; pass a resolver for that.
*/
didResolver?: DidDocumentResolver;
}

/**
Expand All @@ -50,10 +90,11 @@ export interface CreateSDKContextOptions {
* `ERR_PNPM_IGNORED_BUILDS` for `core-js` until `core-js: false` is added to `allowBuilds` in
* `pnpm-workspace.yaml`.
*
* @param options - The application's client.
* @returns A frozen {@link SDKContext} holding `options.client`.
* @param options - The application's client and, optionally, a DID resolver.
* @returns A frozen {@link SDKContext} holding `options.client` and the DID resolver.
* @throws {@link TypeError} If `client` is missing or has no `xrpc()` method, for example a raw
* OAuth session or an `@atproto/api` agent.
* OAuth session or an `@atproto/api` agent, or if `didResolver` is given without a `resolve()`
* method, for example the OAuth client itself instead of `oauthClient.identityResolver`.
*
* @example
* ```ts
Expand All @@ -64,6 +105,15 @@ export interface CreateSDKContextOptions {
* export const context = createSDKContext({ client: new Client(session) });
* ```
*
* @example Reusing the OAuth client's resolver and its cache
* ```ts
* // `oauthClient` is the application's `@atproto/oauth-client` client; `session` comes from it.
* export const context = createSDKContext({
* client: new Client(session),
* didResolver: oauthClient.identityResolver,
* });
* ```
*
* @example Passing the session directly throws
* ```ts
* createSDKContext({ client: session }); // TypeError: wrap it with `new Client(session)`
Expand All @@ -72,7 +122,9 @@ export interface CreateSDKContextOptions {
export function createSDKContext(options: CreateSDKContextOptions): SDKContext {
const client: unknown = options?.client;
assertClient(client);
return Object.freeze({ client });
const didResolver = options.didResolver ?? createDefaultDidResolver();
if (!hasMethod(didResolver, "resolve")) throw notADidResolver(didResolver);
return Object.freeze({ client, didResolver });
}

// Duck-typed instead of `instanceof Client`: an application can end up with more than one
Expand All @@ -81,15 +133,25 @@ export function createSDKContext(options: CreateSDKContextOptions): SDKContext {
// built on `xrpc`, so it is the one method any real client has. A session or agent has no
// `xrpc` method, and the legacy `@atproto/api` agent exposes `xrpc` as an object.
function assertClient(value: unknown): asserts value is Client {
const hasXrpcMethod =
typeof value === "object" &&
value !== null &&
"xrpc" in value &&
typeof value.xrpc === "function";
if (hasXrpcMethod) return;
if (hasMethod(value, "xrpc")) return;
throw new TypeError(
`createSDKContext: \`client\` must be an @atproto/lex Client (an object with an xrpc() method), but received ${describeValue(value)}. ` +
"The SDK does not accept sessions or agents because authentication stays in your application. " +
"Authenticate first, then pass `new Client(session)` (imported from @atproto/lex) as `client`.",
);
}

// Duck-typed for the same reason as `assertClient`. The common mistake is passing the OAuth client
// itself, which has no `resolve` method; its resolver is `oauthClient.identityResolver`.
function notADidResolver(value: unknown): TypeError {
return new TypeError(
`createSDKContext: \`didResolver\` must be an object with a resolve(did) method, but received ${describeValue(value)}. ` +
"Pass `oauthClient.identityResolver` or a DID resolver from @atproto-labs/did-resolver, or leave it out to use the SDK's cached default.",
);
}

function hasMethod(value: unknown, name: string): boolean {
return (
typeof value === "object" && value !== null && typeof Reflect.get(value, name) === "function"
);
}
2 changes: 1 addition & 1 deletion packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Public entry point for @hypercerts-org/sdk.
// Operations are added by the domain cards and imported through their own subpath exports.
// Keep this file free of imports that pull in operations, so the root entry stays tree-shakeable.
export type { CreateSDKContextOptions, SDKContext } from "./context.js";
export type { CreateSDKContextOptions, DidDocumentResolver, SDKContext } from "./context.js";
export { createSDKContext } from "./context.js";
33 changes: 26 additions & 7 deletions packages/sdk/src/internal/resolve-pds.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,48 @@
import type { DidString } from "@atproto/lex";
import {
createDidResolver,
DidCacheMemory,
DidError,
DidResolverCommon,
extractPdsUrl,
isAtprotoDid,
} from "@atproto-labs/did-resolver";
import type { DidDocumentResolver, SDKContext } from "../context.js";
import { describeError } from "./describe.js";

/**
* The resolver a context uses when the application does not supply one: `did:plc` from
* plc.directory and `did:web` from the domain, with its own in-memory cache and one shared lookup
* for concurrent requests for the same DID.
*
* Internal. Each context gets its own, so documents are shared by the calls of one context only.
*/
export function createDefaultDidResolver(): DidDocumentResolver {
return createDidResolver({
didCache: new DidCacheMemory(),
// Looked up when the request is made, not now, so replacing the global `fetch` after the
// context exists (a test stub, for example) still takes effect.
fetch: (input, init) => globalThis.fetch(input, init),
});
}

/**
* Finds the PDS that hosts `did`'s repository from its DID document.
*
* Internal. Supports `did:plc` (read from plc.directory) and `did:web`, the methods atproto
* allows. Uses the global `fetch` and does not cache.
* Internal. Supports `did:plc` and `did:web`, the methods atproto allows, and asks
* `context.didResolver` for the document, so repeated lookups are as cached as that resolver is.
*
* Throws Error when the DID method is not supported, the document cannot be fetched or is
* invalid, or it lists no atproto PDS.
*/
export async function resolvePds(did: DidString): Promise<URL> {
export async function resolvePds(context: SDKContext, did: DidString): Promise<URL> {
if (!isAtprotoDid(did)) {
throw new Error(`cannot resolve the PDS of ${did}: only did:plc and did:web are supported.`);
}
try {
// Created per call so the global `fetch` is looked up when the request is made.
const document = await new DidResolverCommon().resolve(did);
return extractPdsUrl(document);
// An IdentityResolver (oauthClient.identityResolver) wraps the document; a DidResolver
// returns it as is.
const resolved = await context.didResolver.resolve(did);
return extractPdsUrl("didDoc" in resolved ? resolved.didDoc : resolved);
} catch (error) {
throw new Error(`cannot resolve the PDS of ${did}: ${describeDidError(error)}.`, {
cause: error,
Expand Down
Loading
Loading