From 1e03dc3fdb02de2831358d13fcf53150bf54ad6e Mon Sep 17 00:00:00 2001 From: kzoeps Date: Tue, 10 Nov 2026 13:31:09 +0600 Subject: [PATCH 1/2] sdk/context: add attachment, measurement, evaluation and acknowledgement creators Adds createAttachment, createMeasurement, createEvaluation and createAcknowledgement at @hypercerts-org/sdk/context. New locations, tags and measurements are created in the same applyWrites as the record that points at them; existing { uri } records are reused unchanged. Attachment description is string-only until the shared long-description helper lands. --- .agents/skills/hypercerts-org-sdk/SKILL.md | 13 +- .../hypercerts-org-sdk/references/context.md | 150 ++++++++ .changeset/context-records.md | 9 + packages/sdk/package.json | 4 + .../context-records/build-acknowledgement.ts | 151 ++++++++ .../src/context-records/build-attachment.ts | 214 +++++++++++ .../src/context-records/build-evaluation.ts | 183 ++++++++++ .../src/context-records/build-measurement.ts | 195 ++++++++++ .../create-acknowledgement.test.ts | 268 ++++++++++++++ .../context-records/create-attachment.test.ts | 324 +++++++++++++++++ .../context-records/create-evaluation.test.ts | 334 ++++++++++++++++++ .../create-measurement.test.ts | 214 +++++++++++ packages/sdk/src/context-records/index.ts | 33 ++ packages/sdk/src/context-records/score.ts | 53 +++ packages/sdk/src/context-records/shared.ts | 83 +++++ 15 files changed, 2223 insertions(+), 5 deletions(-) create mode 100644 .agents/skills/hypercerts-org-sdk/references/context.md create mode 100644 .changeset/context-records.md create mode 100644 packages/sdk/src/context-records/build-acknowledgement.ts create mode 100644 packages/sdk/src/context-records/build-attachment.ts create mode 100644 packages/sdk/src/context-records/build-evaluation.ts create mode 100644 packages/sdk/src/context-records/build-measurement.ts create mode 100644 packages/sdk/src/context-records/create-acknowledgement.test.ts create mode 100644 packages/sdk/src/context-records/create-attachment.test.ts create mode 100644 packages/sdk/src/context-records/create-evaluation.test.ts create mode 100644 packages/sdk/src/context-records/create-measurement.test.ts create mode 100644 packages/sdk/src/context-records/index.ts create mode 100644 packages/sdk/src/context-records/score.ts create mode 100644 packages/sdk/src/context-records/shared.ts diff --git a/.agents/skills/hypercerts-org-sdk/SKILL.md b/.agents/skills/hypercerts-org-sdk/SKILL.md index a0624f9..d07a6d1 100644 --- a/.agents/skills/hypercerts-org-sdk/SKILL.md +++ b/.agents/skills/hypercerts-org-sdk/SKILL.md @@ -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: "7" --- # @hypercerts-org/sdk @@ -51,6 +51,7 @@ Make a new context when the signed-in account changes. Records are always writte | `@hypercerts-org/sdk/tag` | `createVocabularyTag`, `createWorkScopeTag`, `RecordAlreadyExistsError`, the same `Write*` errors, input/result types | | `@hypercerts-org/sdk/feature` | `createFeature`, `RecordAlreadyExistsError`, the same `Write*` errors, `FeatureInput`, `CreateFeatureResult`, `LeafletDocument` | | `@hypercerts-org/sdk/organization` | `createOrganization`, `OrganizationAlreadyExistsError`, `RecordAlreadyExistsError`, the same `Write*` errors, `OrganizationInput`, `CreateOrganizationInput`, `CreateOrganizationResult`, `LeafletDocument` | +| `@hypercerts-org/sdk/context` | `createAttachment`, `createMeasurement`, `createEvaluation`, `createAcknowledgement`, `RecordAlreadyExistsError`, the same `Write*` errors, input/result types | | `@hypercerts-org/sdk/blob` | `uploadBlob` | | `@hypercerts-org/sdk/collection` | `createCollection`, `createActivityInCollection`, `RecordAlreadyExistsError`, `WriteError`, `WriteRejectedError`, `WriteOutcomeUnknownError`, `WriteResultMismatchError`, input/result types | @@ -69,16 +70,18 @@ Operations are grouped by domain, each under its own subpath. Read the domain's | Feature (`org.hypercerts.entity.feature`, with its tags and locations) | `@hypercerts-org/sdk/feature` | [references/feature.md](references/feature.md) | | Collection (create a Collection with items; add a new Activity to an existing Collection) | `@hypercerts-org/sdk/collection` | [references/collection.md](references/collection.md) | | Organization (`app.certified.actor.organization`, with its profile and locations) | `@hypercerts-org/sdk/organization` | [references/organization.md](references/organization.md) | +| Context (attachments, measurements, evaluations, acknowledgements) | `@hypercerts-org/sdk/context` | [references/context.md](references/context.md) | -Three things to know before opening a reference: +Things to know before opening a reference: - `createProfile` needs an OAuth scope with both `create` and `update` on `app.certified.actor.profile`. With only `create` it fails with `WriteRejectedError` (403). - `location: { uri }` inside a location is a link to external data; a whole location given as `{ uri }` in `createActivity` reuses an existing record. - `createOrganization` takes the name, avatar, banner and website in `profileIfMissing`, not in `organization`, and an existing location as `{ uri }`, never a bare string. +- `createAttachment`, `createMeasurement`, `createEvaluation` and `createAcknowledgement` take a subject as `{ uri }`, never a bare string, and a measured value or score as a decimal string, never a number. ## 5. Images and files -- `create*` operations upload `Blob`/`File` values for you (`image`, `attachment`, a profile's `avatar` and `banner`, a location's `{ blob }`). Pass the file, not an upload result. +- `create*` operations upload `Blob`/`File` values for you (`image`, a rights record's `attachment`, `content` of `createAttachment` and `createEvaluation`, a profile's `avatar` and `banner`, a location's `{ blob }`). Pass the file, not an upload result. - A string is stored as a URL and never fetched. - Use `uploadBlob` only when writing a record yourself with the client: @@ -107,7 +110,7 @@ Uploads happen before the write and are not rolled back, so a call that throws c Order of work: validate input → read `{ uri }` records → upload blobs → validate against lexicons → one write. The SDK never retries. -The three write errors are exported from `@hypercerts-org/sdk/activity`, `/actor`, `/location`, `/tag`, `/feature`, `/collection` and `/organization` and extend `WriteError`. Every `WriteError` has `attempted`: the URI and CID of every record in the request, in request order: for `createActivity` the Activity is last; for `createActivityInCollection` the Collection is last and the Activity is just before it; for `createCollection` the Collection is last, after the records it points at; for `createOrganization` the organization is last. `instanceof WriteError` catches all three. +The three write errors are exported from `@hypercerts-org/sdk/activity`, `/actor`, `/location`, `/tag`, `/feature`, `/collection`, `/context` and `/organization` and extend `WriteError`. Every `WriteError` has `attempted`: the URI and CID of every record in the request, in request order: for `createActivity` the Activity is last; for `createActivityInCollection` the Collection is last and the Activity is just before it; for `createCollection` the Collection is last, after the records it points at; for `createOrganization` the organization is last. `instanceof WriteError` catches all three. | Error | Meaning | What to do | | -------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------- | @@ -188,6 +191,6 @@ try { ## Verify -1. Imports come only from `@hypercerts-org/sdk`, `.../activity`, `.../actor`, `.../collection`, `.../feature`, `.../location`, `.../organization`, `.../tag` or `.../blob`. +1. Imports come only from `@hypercerts-org/sdk`, `.../activity`, `.../actor`, `.../collection`, `.../context`, `.../feature`, `.../location`, `.../organization`, `.../tag` or `.../blob`. 2. `tsc --noEmit` passes. The input types catch wrong field names and shapes. 3. `com.atproto.repo.getRecord` on each returned `uri` returns the record, and any references it holds match the URIs and CIDs the SDK returned. diff --git a/.agents/skills/hypercerts-org-sdk/references/context.md b/.agents/skills/hypercerts-org-sdk/references/context.md new file mode 100644 index 0000000..66e4625 --- /dev/null +++ b/.agents/skills/hypercerts-org-sdk/references/context.md @@ -0,0 +1,150 @@ +# Context domain (`@hypercerts-org/sdk/context`) + +Read [../SKILL.md](../SKILL.md) first for setup, blob uploads and error handling. Every example assumes `context` from `createSDKContext`. + +| Function | Creates | Returns (`created: true` and a field only when the input had it) | +| ----------------------- | ---------------------------------------- | ----------------------------------------------------------------- | +| `createAttachment` | `org.hypercerts.context.attachment` | `{ uri, cid, created, subjects?, location?, tags? }` | +| `createMeasurement` | `org.hypercerts.context.measurement` | `{ uri, cid, created, subjects?, locations? }` | +| `createEvaluation` | `org.hypercerts.context.evaluation` | `{ uri, cid, created, subject?, measurements?, location? }` | +| `createAcknowledgement` | `org.hypercerts.context.acknowledgement` | `{ uri, cid, created, subject, context? }` | + +Each reference in the result is `{ uri, cid, created }`: `created: false` for an existing `{ uri }` record, with the CID it was pinned at. + +All four write a TID-keyed record to the signed-in account's repo. The first three also create the new locations, tags and measurements they are given, in the **same** `applyWrites` as the record (all of it exists afterwards, or none); with nothing new to create, the call is a write of one record. For the location and tag fields see [location.md](location.md) and [tag.md](tag.md). + +## Linking to records + +| Input | Meaning | +| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | +| `{ uri }` in `subjects`, `subject` | An existing record of **any** type. Read for its CID, stored as a strong reference, never modified. | +| `{ uri }` in `location`, `locations`, `tags`, `measurements` | An existing record of that field's type (`app.certified.location`, `org.hypercerts.vocab.tag`, `org.hypercerts.context.measurement`). Another type throws `TypeError`. | +| The fields of a record, in those same four | A new record, created in the same write. Never mixed with `uri`. | +| A string in `content`, an acknowledgement's `context` | A URL/URI stored as it is, never fetched, no CID. | +| A `Blob`/`File` in `content` | Uploaded for you before the write (any type, up to 10 MB; a `Blob` needs a `type`). | + +A subject is not limited to an Activity and is not changed: it does not learn about the attachment, measurement or evaluation, and nothing here links an existing record to its subject afterwards. Subject URIs must use a DID, not a handle. A bare string where `{ uri }` is required throws `TypeError`. + +## createAttachment + +```ts +import { createAttachment } from "@hypercerts-org/sdk/context"; + +const attachment = await createAttachment(context, { + title: "Field survey, June 2026", + contentType: "evidence", // update | report | audit | evidence | testimonial | methodology, others allowed + subjects: [{ uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8" }], + content: [reportFile, "https://example.org/survey/2026-06"], // uploaded, stored as a URL + tags: [ + { category: "evidence-kind", key: "survey", name: "Survey", status: "accepted" }, // new + { uri: "at://did:plc:abc123/org.hypercerts.vocab.tag/land-cover.wetland" }, // existing + ], + location: { lpVersion: "1.0", srs: "http://www.opengis.net/def/crs/OGC/1.3/CRS84", locationType: "coordinate-decimal", location: { string: "90.17,27.47" } }, + capturedAt: "2026-06-12T09:30:00+06:00", +}); +attachment.tags?.[0]; // { uri, cid, created: true } +``` + +- `subjects` is optional: omit it for an attachment recorded before the claim it supports. +- `description` is a string (stored as `descriptionString`). Leaflet documents and `{ uri }` descriptions are not supported. +- A new tag's key is `.`; the SDK reads it first and a taken key throws `RecordAlreadyExistsError` with nothing written. Pass `{ uri }` to reuse a tag. + +## createMeasurement + +```ts +import { createMeasurement } from "@hypercerts-org/sdk/context"; + +const measurement = await createMeasurement(context, { + metric: "Forest area restored", + unit: "hectares", + value: "1234.56", // a decimal string, never a number + subjects: [{ uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8" }], + startDate: "2026-01-01T00:00:00.000Z", + endDate: "2026-06-30T00:00:00.000Z", + measurers: ["did:plc:abc123"], + locations: [{ uri: "at://did:plc:abc123/app.certified.location/3k2a4b5c6d7e8" }], // or new location data +}); +measurement.locations?.[0]; // { uri, cid, created: false } +``` + +- `value` must be a decimal string: `"1234.56"`, `"-3"`, `"0.10"`. A JavaScript number, `"1,234"` and `"1e3"` throw `TypeError`. The string is stored exactly as written. +- `measurers` (and an evaluation's `evaluators`) are DIDs stored as declared data: no proof the account took part or consents, nobody is notified. +- `endDate` before `startDate` throws. `methodURI` and `evidenceURI` entries are URIs, stored and never fetched. + +## createEvaluation + +```ts +import { createEvaluation } from "@hypercerts-org/sdk/context"; + +const evaluation = await createEvaluation(context, { + evaluators: ["did:plc:abc123"], // required, not defaulted to the signed-in account + summary: "The restoration meets its stated targets.", + subject: { uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8" }, + score: { min: "0", max: "5", value: "4.2" }, + measurements: [ + { metric: "Forest area restored", unit: "hectares", value: "1234.56" }, // new, same fields as createMeasurement + { uri: "at://did:plc:abc123/org.hypercerts.context.measurement/3k2a4b5c6d7e8" }, // existing + ], +}); +evaluation.measurements; // [{ uri, cid, created: true }, { uri, cid, created: false }] +``` + +- A new measurement may bring its own new `locations`, created in the same write and reported under `evaluation.measurements[i].locations`. A new measurement's `subjects` are not filled in from the evaluation's `subject`. +- `score` values are decimal strings and are compared exactly: `value` must be from `min` to `max` inclusive, or the call throws. +- `content` and `location` work as in `createAttachment`. + +## createAcknowledgement + +```ts +import { createAcknowledgement } from "@hypercerts-org/sdk/context"; + +await createAcknowledgement(context, { + subject: { uri: "at://did:plc:abc123/org.hypercerts.claim.contributorInformation/3k2a4b5c6d7e8" }, + context: { uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e9" }, // pinned by CID + acknowledged: true, // false records a rejection + comment: "Happy to be listed.", +}); +``` + +- Always written to the **signed-in** account's repo; there is no way to write one for another account. The SDK does not check the account's relationship to the subject. +- `context` is optional: a string is stored as a URI with no CID (lightweight); `{ uri }` is stored as a strong reference pinned to the CID read before the write. Use `{ uri }` when the version matters. +- No `location` or `tags`. Acknowledging the same subject twice creates two records. + +## Fields + +| Field | Used by | Type | Notes | +| - | - | - | - | +| `title` | attachment | `string` | Required, ≤ 256. | +| `subjects` | attachment, measurement | `{ uri }[]` | ≤ 100, any record type. | +| `contentType` | attachment | `string` | ≤ 64. | +| `content` | attachment, evaluation | `(Blob \| string)[]` | ≤ 100. Files uploaded, strings are URLs. | +| `shortDescription`, `description`, `langs` | attachment | `string`, `string`, `string[]` | `description` is a plain string only. | +| `location` | attachment, evaluation | new location or `{ uri }` | | +| `tags` | attachment | new vocabulary tags or `{ uri }`, ≤ 20 | | +| `capturedAt` | attachment | ISO 8601 with timezone | Not `createdAt`; omit if unknown. | +| `metric`, `unit`, `value` | measurement | `string` | All required; `value` is a decimal string. | +| `startDate`, `endDate` | measurement | ISO 8601 | `endDate` not before `startDate`. | +| `locations` | measurement | new locations or `{ uri }`, ≤ 100 | | +| `methodType`, `methodURI`, `evidenceURI`, `measurers`, `comment` | measurement | `string`, `string`, `string[]`, DID `string[]`, `string` | | +| `evaluators` | evaluation | DID `string[]` | Required, ≤ 1000. | +| `summary` | evaluation | `string` | Required, ≤ 5000. | +| `subject` | evaluation, acknowledgement | `{ uri }` | Required for an acknowledgement. | +| `measurements` | evaluation | new measurements or `{ uri }` | ≤ 100. | +| `score` | evaluation | `{ min, max, value }` decimal strings | | +| `acknowledged` | acknowledgement | `boolean` | Required. | +| `context`, `comment` | acknowledgement | `string \| { uri }`, `string` | | +| `createdAt` | all | ISO 8601 | Defaults to the time of the call. Nested new records get the call's time. | + +Not supported: `signatures`, `shortDescriptionFacets`, `commentFacets`, and a non-string attachment `description`. + +## Failures + +Input errors, unresolved or wrongly typed `{ uri }` records and files the lexicon would reject fail before anything is sent. Files are uploaded before the write and are not rolled back: after a failed write they stay unreferenced. `WriteRejectedError` means nothing was created. After `WriteOutcomeUnknownError` the records may exist and `attempted` lists every URI (the primary record is last). Calling again would create new records under new keys: check the URIs first. The SDK never retries. + +## Pitfalls + +- `subjects: ["at://..."]` and `subject: "at://..."` throw. Wrap it: `{ uri: "at://..." }`. +- `value: 5` and `score: { value: 3 }` throw. Pass strings. +- A new measurement inside `createEvaluation` is created every call; to attach an existing measurement pass `{ uri }`. A `{ uri }` of an Activity in `measurements` throws. +- An acknowledgement's `context` string is not read or pinned. Pass `{ uri }` to pin the version. +- A `File` with no `type` cannot be uploaded: wrap it, `new Blob([file], { type: "application/pdf" })`. diff --git a/.changeset/context-records.md b/.changeset/context-records.md new file mode 100644 index 0000000..16991d5 --- /dev/null +++ b/.changeset/context-records.md @@ -0,0 +1,9 @@ +--- +"@hypercerts-org/sdk": minor +--- + +- Add `createAttachment`, `createMeasurement`, `createEvaluation` and `createAcknowledgement` at `@hypercerts-org/sdk/context`. +- Attachments and evaluations upload `Blob` content for you; subjects are `{ uri }` of any existing record and are never modified. +- Locations, vocabulary tags and measurements are new data or `{ uri }`, and are created in the same `applyWrites` as the record that points at them. +- Measured values and scores are decimal strings; a JavaScript number throws instead of being converted. +- Acknowledgements are always written to the signed-in account's repo. diff --git a/packages/sdk/package.json b/packages/sdk/package.json index e5c1ae2..a5e3b85 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -31,6 +31,10 @@ "types": "./dist/collection/index.d.ts", "default": "./dist/collection/index.js" }, + "./context": { + "types": "./dist/context-records/index.d.ts", + "default": "./dist/context-records/index.js" + }, "./feature": { "types": "./dist/feature/index.d.ts", "default": "./dist/feature/index.js" diff --git a/packages/sdk/src/context-records/build-acknowledgement.ts b/packages/sdk/src/context-records/build-acknowledgement.ts new file mode 100644 index 0000000..9371d3e --- /dev/null +++ b/packages/sdk/src/context-records/build-acknowledgement.ts @@ -0,0 +1,151 @@ +import { l, type UriString } from "@atproto/lex"; +import * as acknowledgement from "@hypercerts-org/lexicon/org/hypercerts/context/acknowledgement"; +import * as defs from "@hypercerts-org/lexicon/org/hypercerts/defs"; +import { optionalText } from "../internal/input.js"; +import { type RecordKind, recordKind } from "../internal/record-kind.js"; +import { + type ExistingRecord, + isExistingRecord, + type SupportingRecordRef, +} from "../internal/slots.js"; +import { creatorOf, existingRecordInput, existingRecordReference } from "./shared.js"; + +/** The data of a new `org.hypercerts.context.acknowledgement` record. */ +export interface AcknowledgementInput { + /** + * The record being acknowledged: `{ uri }` of an existing record of any type (an Activity, a + * contributor-information record, an evaluation, ...). Pinned by the CID read before the write + * and never modified. + */ + subject: ExistingRecord; + /** `true` to acknowledge the relationship, `false` to reject it. */ + acknowledged: boolean; + /** + * What the acknowledgement is in the context of, for example the Collection that includes an + * Activity, or the Activity that includes a contributor: + * - a string is stored as a URI as it is: a lightweight reference that is never fetched and has + * no CID, so it does not pin a version; + * - `{ uri }` of an existing record is stored as a strong reference, pinned by the CID read + * before the write, so the acknowledgement says which version of it was meant. + */ + context?: string | ExistingRecord | undefined; + /** An optional plain-text comment. At most 10000 characters and 1000 graphemes. */ + comment?: string | undefined; + /** An ISO 8601 date-time. Defaults to the time of the call. */ + createdAt?: string | undefined; +} + +/** + * The result of {@link createAcknowledgement}: the new Acknowledgement's URI and CID with + * `created: true`, and the CIDs of the records it points at. + * + * @remarks + * `subject` is always present, and `context` only when the input's `context` was `{ uri }`. Both + * have `created: false`: an acknowledgement creates no record besides itself. + */ +export interface CreateAcknowledgementResult extends SupportingRecordRef { + /** The subject with the CID it was pinned at. */ + subject: SupportingRecordRef; + /** The context with the CID it was pinned at, when `context` was `{ uri }`. */ + context?: SupportingRecordRef; +} + +const contextInput = l.custom( + (value): value is string | ExistingRecord => typeof value === "string" || isExistingRecord(value), + "must be a URI string, stored as it is, or { uri } of an existing record, stored as a strong reference", +); + +const acknowledgementKind: RecordKind = recordKind( + acknowledgement.main, + { + subject: existingRecordInput, + acknowledged: l.boolean(), + context: l.optional(contextInput), + comment: optionalText, + }, + { + // A `{ uri }` arrives here already stored as a strong reference (see `typed` below). + context: (_build, _field, value: string | object) => + Promise.resolve( + typeof value === "string" ? defs.uri.build({ uri: value as UriString }) : value, + ), + }, + { + references: { + subject: existingRecordReference, + // Only `{ uri }` is a reference. The union has the strong reference as a member, so it is + // stored with its `$type`. + context: { kind: undefined, many: false, when: isExistingRecord, typed: true }, + }, + }, +); + +/** + * Creates an Acknowledgement (`org.hypercerts.context.acknowledgement`), the acknowledging side + * of a link between two records, in the authenticated account's repo. + * + * @remarks + * The acknowledgement is always written to the signed-in account's repo. There is no way to write + * one on behalf of another account, and the SDK does not check that the account has any + * relationship to the subject: that is for whoever reads the acknowledgement to judge. The + * acknowledged record is not modified and does not learn about it. + * + * `subject` is `{ uri }` of an existing record of any type; the SDK reads it for its current CID + * and stores a strong reference. `acknowledged: false` records a rejection. `context` is a URI + * string, stored as it is and never fetched, or `{ uri }` of an existing record, stored as a strong + * reference pinned to its current CID; use `{ uri }` when the acknowledgement should name the + * version it was about. Both alternatives are optional. + * + * The record key is a new TID chosen by the SDK, so acknowledging the same subject twice creates + * two records; nothing is looked up or deduplicated. `createdAt` defaults to the time of the call. + * An acknowledgement has no location or tag fields. + * + * Not supported: the lexicon's `signatures`. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated; the record is created in that account's repo. + * @param input - The acknowledgement. See {@link AcknowledgementInput}. + * @returns The new record's URI and CID with `created: true`, and the CIDs its `subject` and + * `{ uri }` `context` were pinned at. See {@link CreateAcknowledgementResult}. + * @throws {@link TypeError} If `input` has an unknown field, a `subject` that is not `{ uri }`, an + * `acknowledged` that is not a boolean, a `context` that is neither a string nor `{ uri }` (or + * combines `uri` with other fields), or any value the lexicon does not allow, for example a + * `context` string that is not a URI. The message names the field. Nothing was written. + * @throws {@link Error} If the client is not authenticated, or the `subject` or `context` record + * cannot be read. Nothing was written. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the record + * may or may not exist. It carries the URI to check; the SDK does not retry, because a retry would + * create a second acknowledgement under a new key if the first attempt had succeeded. + * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK + * computed. + * + * @example A contributor acknowledges being included in an Activity + * ```ts + * import { createAcknowledgement } from "@hypercerts-org/sdk/context"; + * + * // `context` comes from createSDKContext, signed in as the contributor. + * const acknowledgement = await createAcknowledgement(context, { + * subject: { uri: "at://did:plc:abc123/org.hypercerts.claim.contributorInformation/3k2a4b5c6d7e8" }, + * context: { uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e9" }, // pinned by CID + * acknowledged: true, + * }); + * console.log(acknowledgement.uri, acknowledgement.subject); // { uri, cid, created: false } + * ``` + * + * @example Rejecting, with a lightweight context + * ```ts + * import { createAcknowledgement } from "@hypercerts-org/sdk/context"; + * + * await createAcknowledgement(context, { + * subject: { uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e9" }, + * context: "at://did:plc:abc123/org.hypercerts.collection/3k2a4b5c6d7e8", // a URI, not pinned + * acknowledged: false, + * comment: "This activity is not part of our collection.", + * }); + * ``` + */ +export const createAcknowledgement = creatorOf( + "createAcknowledgement", + acknowledgementKind, +); diff --git a/packages/sdk/src/context-records/build-attachment.ts b/packages/sdk/src/context-records/build-attachment.ts new file mode 100644 index 0000000..4524227 --- /dev/null +++ b/packages/sdk/src/context-records/build-attachment.ts @@ -0,0 +1,214 @@ +import { l } from "@atproto/lex"; +import * as attachment from "@hypercerts-org/lexicon/org/hypercerts/context/attachment"; +import * as defs from "@hypercerts-org/lexicon/org/hypercerts/defs"; +import { optionalText } from "../internal/input.js"; +import { type RecordKind, recordKind, references } from "../internal/record-kind.js"; +import type { ExistingRecord, SupportingRecordRef } from "../internal/slots.js"; +import type { LocationInput } from "../location/build-location.js"; +import { + type VocabularyTagInput, + type VocabularyTagResult, + vocabularyTagKind, +} from "../tag/build-tag.js"; +import { + contentInput, + contentTransform, + creatorOf, + existingRecordsReference, + locationReference, +} from "./shared.js"; + +/** The data of a new `org.hypercerts.context.attachment` record. */ +export interface AttachmentInput { + /** A display title, for example `Impact Assessment Report`. At most 256 characters. */ + title: string; + /** + * The records the attachment is about, at most 100, each `{ uri }` of an existing record of any + * type: an Activity, a Collection, a measurement, an evaluation, another attachment, an account + * profile. Pinned by the CID read before the write and never modified. Omit it for an attachment + * recorded before the claim it will support. + */ + subjects?: readonly ExistingRecord[] | undefined; + /** + * The kind of attachment, for example `update`, `report`, `audit`, `evidence`, `testimonial` or + * `methodology`. Other values are accepted. At most 64 characters. + */ + contentType?: string | undefined; + /** + * The files and links in the attachment, at most 100, in order: each `Blob` or `File` (up to + * 10 MB, any type) is uploaded by the SDK, and each string is stored as a URL and never fetched. + */ + content?: readonly (Blob | string)[] | undefined; + /** A summary for previews. At most 3000 characters and 300 graphemes. */ + shortDescription?: string | undefined; + /** A long description as plain text or Markdown. */ + description?: string | undefined; + /** Languages of the text fields as BCP-47 tags (up to three), for example `["en"]`. */ + langs?: readonly string[] | undefined; + /** + * Where the attachment's subject matter occurred: the data of a new location or `{ uri }` of an + * existing one. + */ + location?: LocationInput | ExistingRecord | undefined; + /** + * The vocabulary tags that classify the attachment, at most 20, all applying at once: each entry + * is the data of a new vocabulary tag, which gets the record key `.`, or `{ uri }` + * of an existing one. + */ + tags?: readonly (VocabularyTagInput | ExistingRecord)[] | undefined; + /** + * An ISO 8601 date-time with a timezone: when the attached material was captured, for example + * when a photo was taken. Not `createdAt`; omit it when it is unknown. + */ + capturedAt?: string | undefined; + /** An ISO 8601 date-time. Defaults to the time of the call. */ + createdAt?: string | undefined; +} + +/** + * The result of {@link createAttachment}: the new Attachment's URI and CID with `created: true`, + * and the results for the records it points at. + * + * @remarks + * `subjects`, `location` and `tags` mirror the input and appear only when the input had them. + * Each entry belongs to the input entry at the same index, whether it was created or reused, and + * a new tag nested in a new tag (`broader`) is reported under it. Filter on `created` for only the + * records this call wrote. + */ +export interface CreateAttachmentResult extends SupportingRecordRef { + /** The subjects with the CIDs they were pinned at. `created` is `false` for each. */ + subjects?: readonly SupportingRecordRef[]; + /** The location. */ + location?: SupportingRecordRef; + /** The vocabulary tags, in input order. */ + tags?: readonly VocabularyTagResult[]; +} + +const attachmentKind: RecordKind = recordKind( + attachment.main, + { + title: l.string(), + contentType: optionalText, + content: contentInput, + shortDescription: optionalText, + description: optionalText, + langs: l.optional(l.array(l.string())), + capturedAt: optionalText, + }, + { + content: contentTransform, + description: (_build, _field, value: string) => + Promise.resolve(defs.descriptionString.build({ value })), + }, + { + references: { + subjects: existingRecordsReference, + location: locationReference, + tags: references.many(() => vocabularyTagKind), + }, + }, +); + +/** + * Creates an Attachment (`org.hypercerts.context.attachment`), commentary, evidence or documents + * about other records, together with the location and tags it needs, in one atomic write. + * + * @remarks + * The record key is a new TID chosen by the SDK, and `createdAt` defaults to the time of the call. + * + * `subjects` is optional and is not limited to Activities: each entry is `{ uri }` of an existing + * record of any type. The SDK reads each one for its current CID and stores a strong reference + * to it. The subjects are never modified and do not learn about the attachment; nothing links an + * existing attachment to a subject afterwards. + * + * `content` takes files and links in one array. A `Blob` or `File` is uploaded before the write + * and needs a `type` (wrap a `File` that has none: `new Blob([file], { type })`); a string is + * stored as a URL and never fetched. `location` and each `tags` entry is either a new record's + * fields or `{ uri }` of an existing record of the right type, which is reused as it is. A new tag + * can have its own `broader` and `supersededBy` tags (see {@link createVocabularyTag}). Nothing is + * deduplicated, and order is kept. + * + * A new tag's record key is `.`, so the SDK checks first that no such tag exists and + * throws {@link RecordAlreadyExistsError} if one does. To use an existing tag, pass its `uri`. + * + * Everything is created in one write: all the records exist afterwards, or none do. An attachment + * with no new location or tag is a write of one record. One write holds at most 200 records. The + * OAuth session needs `create` on the attachment, tag and location collections it writes to. + * + * Files are uploaded before the write and outside it. If the write fails, they are left unused and + * the PDS may or may not delete them later. A lexicon rule that rejects the record (for example + * more than 100 `content` entries) is found only after the uploads. + * + * Not supported: the lexicon's `signatures` and `shortDescriptionFacets`, a `description` that is + * not a string, and a blob that was uploaded already. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated; the records are created in that account's repo. + * @param input - The attachment and the records it needs. See {@link AttachmentInput}. + * @returns The new Attachment's URI and CID with `created: true`, and the references of its + * location and tags. See {@link CreateAttachmentResult}. + * @throws {@link TypeError} If `input` has an unknown field, a `content` entry that is neither a + * `Blob` nor a string, a file the lexicon does not allow (over 10 MB), a mixed or wrongly typed + * entry (a `tags` URI that points at another record type, `{ uri }` combined with record fields, + * a `subjects` entry that is not `{ uri }`), two new tags with the same key, more new records than + * one write holds, or any value the lexicon does not allow. The message names the field. Nothing + * was written. Blobs may already have been uploaded when a lexicon rule rejects a record. + * @throws {@link Error} If the client is not authenticated, a `subjects` or other existing record + * cannot be read, the key of a new tag cannot be checked, or an upload fails. Nothing was written. + * @throws {@link RecordAlreadyExistsError} If a new tag's key is taken. Nothing was written. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). None of the records + * was created and nothing needs cleaning up. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS (network + * failure, timeout, a server error), so the records may or may not exist. It lists every URI that + * was attempted. The SDK does not retry, because a retry would create a second Attachment under a + * new key if the first attempt had succeeded. Check the URIs, then decide. + * @throws {@link WriteResultMismatchError} If the PDS reported different URIs or CIDs than the SDK + * computed. + * + * @example An evidence report with a file, a link, a new tag and a new location + * ```ts + * import { createAttachment } from "@hypercerts-org/sdk/context"; + * + * // `context` comes from createSDKContext; `report` is a File from an . + * const attachment = await createAttachment(context, { + * title: "Field survey, June 2026", + * contentType: "evidence", + * subjects: [{ uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8" }], + * content: [report, "https://example.org/survey/2026-06"], // uploaded, stored as a URL + * tags: [ + * { category: "evidence-kind", key: "survey", name: "Survey", status: "accepted" }, // created + * { uri: "at://did:plc:abc123/org.hypercerts.vocab.tag/land-cover.wetland" }, // reused + * ], + * location: { + * lpVersion: "1.0", + * srs: "http://www.opengis.net/def/crs/OGC/1.3/CRS84", + * locationType: "coordinate-decimal", + * location: { string: "90.17,27.47" }, + * }, // created + * capturedAt: "2026-06-12T09:30:00+06:00", + * }); + * console.log(attachment.uri, attachment.tags?.[0]); // { uri, cid, created: true } + * ``` + * + * @example An attachment with no subject, recorded before the claim it will support + * ```ts + * import { createAttachment } from "@hypercerts-org/sdk/context"; + * + * await createAttachment(context, { title: "Baseline photos", content: ["https://example.org/photos"] }); + * ``` + * + * @example A subject is `{ uri }`, not a bare string + * ```ts + * import { createAttachment } from "@hypercerts-org/sdk/context"; + * + * await createAttachment(context, { + * title: "Comment", + * // TypeError: subjects[0] must be { uri } of an existing record + * subjects: ["at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8"], + * }); + * ``` + */ +export const createAttachment = creatorOf( + "createAttachment", + attachmentKind, +); diff --git a/packages/sdk/src/context-records/build-evaluation.ts b/packages/sdk/src/context-records/build-evaluation.ts new file mode 100644 index 0000000..b3cf284 --- /dev/null +++ b/packages/sdk/src/context-records/build-evaluation.ts @@ -0,0 +1,183 @@ +import { l } from "@atproto/lex"; +import * as evaluation from "@hypercerts-org/lexicon/org/hypercerts/context/evaluation"; +import { type RecordKind, recordKind, references } from "../internal/record-kind.js"; +import type { ExistingRecord, SupportingRecordRef } from "../internal/slots.js"; +import type { LocationInput } from "../location/build-location.js"; +import { + type MeasurementInput, + type MeasurementResult, + measurementKind, +} from "./build-measurement.js"; +import { type EvaluationScore, scoreInput } from "./score.js"; +import { + contentInput, + contentTransform, + creatorOf, + didListInput, + didListTransform, + existingRecordReference, + locationReference, +} from "./shared.js"; + +/** The data of a new `org.hypercerts.context.evaluation` record. */ +export interface EvaluationInput { + /** + * DIDs of the evaluators, at most 1000. Declared data: it is not proof that those accounts wrote + * or agree with the evaluation, and nothing is sent to them. The SDK does not default it to the + * signed-in account. + */ + evaluators: readonly string[]; + /** A brief summary. At most 5000 characters and 1000 graphemes. */ + summary: string; + /** + * What is being evaluated: `{ uri }` of an existing record of any type (an Activity, a + * measurement, a contribution, ...). Pinned by the CID read before the write and never modified. + */ + subject?: ExistingRecord | undefined; + /** + * Detailed reports or methodology, at most 100, in order: each `Blob` or `File` (up to 10 MB, any + * type) is uploaded by the SDK, and each string is stored as a URL and never fetched. + */ + content?: readonly (Blob | string)[] | undefined; + /** + * The measurements the evaluation is based on, at most 100: each entry is the data of a new + * measurement (created in the same write, with its own new `locations`) or `{ uri }` of an + * existing `org.hypercerts.context.measurement`, reused as it is. + */ + measurements?: readonly (MeasurementInput | ExistingRecord)[] | undefined; + /** An overall score. See {@link EvaluationScore}. */ + score?: EvaluationScore | undefined; + /** + * For a georeferenced evaluation: the data of a new location or `{ uri }` of an existing one. + */ + location?: LocationInput | ExistingRecord | undefined; + /** An ISO 8601 date-time. Defaults to the time of the call. */ + createdAt?: string | undefined; +} + +/** + * The result of {@link createEvaluation}: the new Evaluation's URI and CID with `created: true`, + * and the results for the records it points at. + * + * @remarks + * `subject`, `measurements` and `location` mirror the input and appear only when the input had + * them. `measurements[i]` belongs to the input entry at the same index, whether it was created or + * reused, and a new measurement reports its own `locations`. Filter on `created` for only the + * records this call wrote. + */ +export interface CreateEvaluationResult extends SupportingRecordRef { + /** The subject with the CID it was pinned at. `created` is `false`. */ + subject?: SupportingRecordRef; + /** The measurements, in input order. */ + measurements?: readonly MeasurementResult[]; + /** The location. */ + location?: SupportingRecordRef; +} + +const evaluationKind: RecordKind = recordKind( + evaluation.main, + { + evaluators: didListInput, + summary: l.string(), + content: contentInput, + score: l.optional(scoreInput), + }, + { evaluators: didListTransform, content: contentTransform }, + { + references: { + subject: existingRecordReference, + measurements: references.many(() => measurementKind), + location: locationReference, + }, + }, +); + +/** + * Creates an Evaluation (`org.hypercerts.context.evaluation`), an assessment of a record such as + * an Activity, together with the measurements and location it needs, in one atomic write. + * + * @remarks + * The record key is a new TID chosen by the SDK, and `createdAt` defaults to the time of the call. + * + * Each `measurements` entry is either a new measurement's fields (see {@link MeasurementInput}), + * created in the same write together with its own new locations, or `{ uri }` of an existing + * measurement, which is reused as it is. The two can be mixed. The measurements' own `subjects` are + * not filled in from the evaluation's `subject`. `location` is a new location's fields or `{ uri }` + * of an existing one. Nothing is deduplicated, and order is kept. + * + * `subject` is `{ uri }` of an existing record of any type; it is pinned by its current CID and + * never modified, and does not learn about the evaluation. `evaluators` are DIDs stored as given: + * they are not proof that those accounts wrote or agree with the evaluation, and nobody is + * notified. `score` takes decimal strings and is checked exactly, without JavaScript numbers: + * `value` must be from `min` to `max`, inclusive. + * + * `content` takes files and links in one array. A `Blob` or `File` is uploaded before the write and + * needs a `type`; a string is stored as a URL and never fetched. + * + * Everything is created in one write: all the records exist afterwards, or none do. An evaluation + * with no new measurement or location is a write of one record. One write holds at most 200 + * records. The OAuth session needs `create` on the evaluation, measurement and location collections + * it writes to. + * + * Files are uploaded before the write and outside it. If the write fails, they are left unused and + * the PDS may or may not delete them later. A lexicon rule that rejects the record is found only + * after the uploads. + * + * Not supported: the lexicon's `signatures`. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated; the records are created in that account's repo. + * @param input - The evaluation and the records it needs. See {@link EvaluationInput}. + * @returns The new Evaluation's URI and CID with `created: true`, and the references of its + * measurements (with their locations) and location. See {@link CreateEvaluationResult}. + * @throws {@link TypeError} If `input` has an unknown field, an `evaluators` entry that is not a + * DID, a `score` that is not decimal strings or has a `value` outside `min` to `max`, a mixed or + * wrongly typed entry (a `measurements` URI that points at another record type, `{ uri }` combined + * with record fields), more new records than one write holds, or any value the lexicons do not + * allow. The message names the field. Nothing was written. Blobs may already have been uploaded + * when a lexicon rule rejects a record. + * @throws {@link Error} If the client is not authenticated, an existing record cannot be read, or + * an upload fails. Nothing was written. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). None of the records + * was created and nothing needs cleaning up. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS (network + * failure, timeout, a server error), so the records may or may not exist. It lists every URI that + * was attempted. The SDK does not retry, because a retry would create duplicates under new keys + * if the first attempt had succeeded. Check the URIs, then decide. + * @throws {@link WriteResultMismatchError} If the PDS reported different URIs or CIDs than the SDK + * computed. + * + * @example An evaluation with a new measurement, an existing one and a score + * ```ts + * import { createEvaluation } from "@hypercerts-org/sdk/context"; + * + * // `context` comes from createSDKContext. + * const evaluation = await createEvaluation(context, { + * evaluators: ["did:plc:abc123"], + * summary: "The restoration meets its stated targets.", + * subject: { uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8" }, + * score: { min: "0", max: "5", value: "4.2" }, + * content: ["https://example.org/reports/2026-evaluation.pdf"], + * measurements: [ + * { metric: "Forest area restored", unit: "hectares", value: "1234.56" }, // created + * { uri: "at://did:plc:abc123/org.hypercerts.context.measurement/3k2a4b5c6d7e8" }, // reused + * ], + * }); + * console.log(evaluation.uri, evaluation.measurements?.[0]); // { uri, cid, created: true } + * ``` + * + * @example A score outside its scale is rejected + * ```ts + * import { createEvaluation } from "@hypercerts-org/sdk/context"; + * + * await createEvaluation(context, { + * evaluators: ["did:plc:abc123"], + * summary: "Strong results.", + * score: { min: "0", max: "5", value: "7" }, // TypeError: must have a value from min to max + * }); + * ``` + */ +export const createEvaluation = creatorOf( + "createEvaluation", + evaluationKind, +); diff --git a/packages/sdk/src/context-records/build-measurement.ts b/packages/sdk/src/context-records/build-measurement.ts new file mode 100644 index 0000000..2550163 --- /dev/null +++ b/packages/sdk/src/context-records/build-measurement.ts @@ -0,0 +1,195 @@ +import { l } from "@atproto/lex"; +import * as measurement from "@hypercerts-org/lexicon/org/hypercerts/context/measurement"; +import { dateRange, optionalText } from "../internal/input.js"; +import { type RecordKind, recordKind } from "../internal/record-kind.js"; +import type { ExistingRecord, SupportingRecordRef } from "../internal/slots.js"; +import type { LocationInput } from "../location/build-location.js"; +import { + creatorOf, + decimalString, + didListInput, + didListTransform, + existingRecordsReference, + locationsReference, +} from "./shared.js"; + +/** The data of a new `org.hypercerts.context.measurement` record. */ +export interface MeasurementInput { + /** The metric being measured, for example `Forest area restored`. At most 500 characters. */ + metric: string; + /** The unit of `value`, for example `hectares`, `kg CO₂e` or `%`. At most 50 characters. */ + unit: string; + /** + * The measured value as a decimal number written as a string, for example `"1234.56"` or `"-3"`. + * At most 500 characters. A JavaScript number is rejected, not converted, so no precision is + * lost; exponent notation (`"1e3"`) and thousands separators (`"1,234"`) are rejected too. + */ + value: string; + /** + * The records the measurement is about, at most 100, each `{ uri }` of an existing record of any + * type (an Activity, a Collection, a Feature, ...). Pinned by the CID read before the write and + * never modified. + */ + subjects?: readonly ExistingRecord[] | undefined; + /** An ISO 8601 date-time: when the measurement began. */ + startDate?: string | undefined; + /** + * An ISO 8601 date-time, not before `startDate`: when the measurement ended. For a one-time + * measurement the lexicon asks for the same value as `startDate`. + */ + endDate?: string | undefined; + /** + * Where the measurement was taken, at most 100: each entry is the data of a new location or + * `{ uri }` of an existing one. + */ + locations?: readonly (LocationInput | ExistingRecord)[] | undefined; + /** A short identifier for the methodology. At most 30 characters. */ + methodType?: string | undefined; + /** A URI to the methodology documentation, standard or procedure. Stored as written, never fetched. */ + methodURI?: string | undefined; + /** URIs to evidence or the underlying data, at most 50. Stored as written, never fetched. */ + evidenceURI?: readonly string[] | undefined; + /** + * DIDs of the entities that performed the measurement, at most 100. Declared data: it is not + * proof that those accounts took part or agree, and nothing is sent to them. + */ + measurers?: readonly string[] | undefined; + /** A short comment, suitable for previews. At most 3000 characters and 300 graphemes. */ + comment?: string | undefined; + /** An ISO 8601 date-time. Defaults to the time of the call. */ + createdAt?: string | undefined; +} + +/** + * The result of {@link createMeasurement}, and what {@link createEvaluation} reports for each of its + * measurements: the measurement's URI and CID with whether the call created it, and the locations + * of a new one. + * + * @remarks + * `subjects` and `locations` mirror the input and appear only on a measurement this call created + * and only when its input had them. Each entry belongs to the input entry at the same index, + * whether it was created or reused. The measurement {@link createMeasurement} returns is always + * new (`created: true`). + */ +export interface MeasurementResult extends SupportingRecordRef { + /** The subjects with the CIDs they were pinned at. `created` is `false` for each. */ + subjects?: readonly SupportingRecordRef[]; + /** The locations, in input order. */ + locations?: readonly SupportingRecordRef[]; +} + +/** + * The kind of a measurement. Shared by {@link createMeasurement} and by the `measurements` of + * {@link createEvaluation}, so a measurement is built the same way in both. + */ +export const measurementKind: RecordKind = recordKind( + measurement.main, + { + metric: l.string(), + unit: l.string(), + value: decimalString, + startDate: optionalText, + endDate: optionalText, + methodType: optionalText, + methodURI: optionalText, + evidenceURI: l.optional(l.array(l.string())), + measurers: l.optional(didListInput), + comment: optionalText, + }, + { measurers: didListTransform }, + { + refinements: [dateRange], + references: { + subjects: existingRecordsReference, + locations: locationsReference, + }, + }, +); + +/** + * Creates a measurement (`org.hypercerts.context.measurement`), a measured value that other + * records can be evidence for, together with the locations it needs, in one atomic write. + * + * @remarks + * The record key is a new TID chosen by the SDK, and `createdAt` defaults to the time of the call. + * + * `value` is a decimal string, stored exactly as written: a JavaScript number throws instead of + * being converted, so `"0.10"` stays `"0.10"` and a long value loses no digits. + * + * Each `locations` entry is either a new location's fields or `{ uri }` of an existing location, + * which is reused as it is. Each `subjects` entry is `{ uri }` of an existing record of any type; + * it is pinned by its current CID and never modified, and the subject does not learn about the + * measurement. Nothing is deduplicated, and order is kept. `measurers` are DIDs stored as given: + * they are not proof that those accounts took part, and nobody is notified. + * + * To measure and evaluate in one call, pass the measurement's fields in `measurements` of + * {@link createEvaluation}. + * + * Everything is created in one write: all the records exist afterwards, or none do. A measurement + * with no new location is a write of one record. One write holds at most 200 records. The OAuth + * session needs `create` on the measurement and location collections it writes to. + * + * Not supported: the lexicon's `signatures` and `commentFacets`. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated; the records are created in that account's repo. + * @param input - The measurement and the locations it needs. See {@link MeasurementInput}. + * @returns The new Measurement's URI and CID with `created: true`, and the references of its + * locations in input order. See {@link MeasurementResult}. + * @throws {@link TypeError} If `input` has an unknown field, a `value` that is not a decimal + * string (a number, `"1,234"`, `"1e3"`), an `endDate` before its `startDate`, a `measurers` entry + * that is not a DID, a mixed or wrongly typed entry (a `locations` URI that points at another + * record type, `{ uri }` combined with record fields), more new records than one write holds, or + * any value the lexicon does not allow. The message names the field. Nothing was written. Blobs + * may already have been uploaded when a lexicon rule rejects a record. + * @throws {@link Error} If the client is not authenticated, an existing record cannot be read, or + * an upload fails. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). None of the records + * was created and nothing needs cleaning up. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS (network + * failure, timeout, a server error), so the records may or may not exist. It lists every URI that + * was attempted. The SDK does not retry, because a retry would create duplicates under new keys + * if the first attempt had succeeded. Check the URIs, then decide. + * @throws {@link WriteResultMismatchError} If the PDS reported different URIs or CIDs than the SDK + * computed. + * + * @example + * ```ts + * import { createMeasurement } from "@hypercerts-org/sdk/context"; + * + * // `context` comes from createSDKContext. + * const measurement = await createMeasurement(context, { + * metric: "Forest area restored", + * unit: "hectares", + * value: "1234.56", // a string, not a number + * subjects: [{ uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8" }], + * startDate: "2026-01-01T00:00:00.000Z", + * endDate: "2026-06-30T00:00:00.000Z", + * measurers: ["did:plc:abc123"], + * locations: [ + * { + * lpVersion: "1.0", + * srs: "http://www.opengis.net/def/crs/OGC/1.3/CRS84", + * locationType: "coordinate-decimal", + * location: { string: "90.17,27.47" }, + * }, // created too + * ], + * }); + * console.log(measurement.uri, measurement.locations?.[0]); // { uri, cid, created: true } + * ``` + * + * @example A number is rejected, not converted + * ```ts + * import { createMeasurement } from "@hypercerts-org/sdk/context"; + * + * await createMeasurement(context, { + * metric: "Trees planted", + * unit: "trees", + * value: 5000, // TypeError: must be a decimal number written as a string + * }); + * ``` + */ +export const createMeasurement = creatorOf( + "createMeasurement", + measurementKind, +); diff --git a/packages/sdk/src/context-records/create-acknowledgement.test.ts b/packages/sdk/src/context-records/create-acknowledgement.test.ts new file mode 100644 index 0000000..b7e8b9b --- /dev/null +++ b/packages/sdk/src/context-records/create-acknowledgement.test.ts @@ -0,0 +1,268 @@ +import { Client, isTidString } from "@atproto/lex"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createSDKContext } from "../context.js"; +import { CID, DID, json } from "../test-utils/fake-pds.js"; +import { fakeRepo, methods, refTo, writeOf } from "../test-utils/fake-repo.js"; +import { + type AcknowledgementInput, + createAcknowledgement, + WriteOutcomeUnknownError, + WriteRejectedError, +} from "./index.js"; + +const ACKNOWLEDGEMENT = "org.hypercerts.context.acknowledgement"; +const CONTRIBUTOR = "org.hypercerts.claim.contributorInformation"; +const ACTIVITY = "org.hypercerts.claim.activity"; +const APPLY = "com.atproto.repo.applyWrites"; + +const uriOf = (collection: string, rkey = "3k2a4b5c6d7e8") => `at://${DID}/${collection}/${rkey}`; +const subject = uriOf(CONTRIBUTOR); +const activity = uriOf(ACTIVITY, "3k2a4b5c6d7e9"); + +describe("createAcknowledgement", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("acknowledges a subject with a pinned context, as the signed-in account", async () => { + const { context, requests, creates } = fakeRepo({ + existing: { [subject]: CID, [activity]: CID }, + }); + + const result = await createAcknowledgement(context, { + subject: { uri: subject }, + context: { uri: activity }, + acknowledged: true, + comment: "Happy to be listed.", + createdAt: "2026-07-01T00:00:00.000Z", + }); + + // The two records are read, then one record is written to the signed-in account's repo. + expect(methods(requests)).toEqual([ + "com.atproto.repo.getRecord", + "com.atproto.repo.getRecord", + APPLY, + ]); + const body = JSON.parse(new TextDecoder().decode(requests.at(-1)?.body)); + expect(body.repo).toBe(DID); + expect(creates[0]).toHaveLength(1); + const write = writeOf(creates[0] ?? [], ACKNOWLEDGEMENT); + expect(isTidString(write.rkey)).toBe(true); + expect(write.value).toEqual({ + $type: ACKNOWLEDGEMENT, + subject: { uri: subject, cid: CID }, + context: { $type: "com.atproto.repo.strongRef", uri: activity, cid: CID }, + acknowledged: true, + comment: "Happy to be listed.", + createdAt: "2026-07-01T00:00:00.000Z", + }); + expect(result).toEqual({ + ...refTo(write), + created: true, + subject: { uri: subject, cid: CID, created: false }, + context: { uri: activity, cid: CID, created: false }, + }); + }); + + it("acknowledges another account's record but writes to the signed-in account's repo", async () => { + const owner = "did:plc:ewvi7nxzyoun6zhxrhs64oiz"; + const theirs = uriOf(ACTIVITY).replace(DID, owner); + // The owner's PDS is found from their DID document and read without the client. + vi.stubGlobal("fetch", async (input: Request | string | URL) => { + const url = input instanceof Request ? input.url : String(input); + if (url.startsWith("https://plc.directory/")) { + return json(200, { + id: owner, + service: [ + { + id: "#atproto_pds", + type: "AtprotoPersonalDataServer", + serviceEndpoint: "https://owner-pds.test", + }, + ], + }); + } + return json(200, { uri: theirs, cid: CID, value: {} }); + }); + const { context, requests, creates } = fakeRepo(); + + const result = await createAcknowledgement(context, { + subject: { uri: theirs }, + acknowledged: true, + }); + + // Only the write goes through the client, and it targets the signed-in account's repo. + expect(methods(requests)).toEqual([APPLY]); + expect(JSON.parse(new TextDecoder().decode(requests[0]?.body)).repo).toBe(DID); + expect(result.uri.startsWith(`at://${DID}/${ACKNOWLEDGEMENT}/`)).toBe(true); + expect(writeOf(creates[0] ?? [], ACKNOWLEDGEMENT).value.subject).toEqual({ + uri: theirs, + cid: CID, + }); + }); + + it("records a rejection", async () => { + const { context, creates } = fakeRepo({ existing: { [subject]: CID } }); + + const result = await createAcknowledgement(context, { + subject: { uri: subject }, + acknowledged: false, + }); + + const { value } = writeOf(creates[0] ?? [], ACKNOWLEDGEMENT); + expect(value).toMatchObject({ subject: { uri: subject, cid: CID }, acknowledged: false }); + expect(value.context).toBeUndefined(); + expect(value.comment).toBeUndefined(); + expect(result.context).toBeUndefined(); + }); + + it("stores a context string as a URI, without reading it", async () => { + const collection = uriOf("org.hypercerts.collection"); + const { context, requests, creates } = fakeRepo({ existing: { [subject]: CID } }); + + await createAcknowledgement(context, { + subject: { uri: subject }, + context: collection, + acknowledged: true, + }); + + // Only the subject is read: a lightweight context has no CID to look up. + expect(methods(requests)).toEqual(["com.atproto.repo.getRecord", APPLY]); + expect(writeOf(creates[0] ?? [], ACKNOWLEDGEMENT).value.context).toEqual({ + $type: "org.hypercerts.defs#uri", + uri: collection, + }); + }); + + it("accepts a subject of any record type and does not modify it", async () => { + const { context, creates, updates, puts } = fakeRepo({ + existing: { [activity]: CID }, + }); + + await createAcknowledgement(context, { subject: { uri: activity }, acknowledged: true }); + + expect(creates[0]).toHaveLength(1); + expect(updates.flat()).toEqual([]); + expect(puts).toEqual([]); + }); + + it.each<[string, Record, RegExp]>([ + ["a subject that is a bare string", { subject }, /must be \{ uri \}.* at \$\.subject/], + ["no subject", { subject: undefined }, / at \$\.subject/], + [ + "a subject with a handle authority", + { subject: { uri: "at://alice.example/a.b/c" } }, + /subject/, + ], + [ + "an acknowledged that is not a boolean", + { acknowledged: "yes" }, + /Expected boolean value type/, + ], + ["no acknowledged", { acknowledged: undefined }, / at \$\.acknowledged/], + ["a context that is a number", { context: 5 }, /must be a URI string.* at \$\.context/], + [ + "a context URI mixed with other fields", + { context: { uri: activity, cid: CID } }, + /context combines `uri` with other fields/, + ], + [ + "a repo to write to", + { repo: "did:plc:other" }, + /Allowed fields: subject, acknowledged, context/, + ], + [ + "a location", + { location: { uri: activity } }, + /Allowed fields: subject, acknowledged, context/, + ], + ])("sends nothing for %s", async (_, fields, message) => { + const { context, requests } = fakeRepo({ existing: { [subject]: CID } }); + const input = { subject: { uri: subject }, acknowledged: true, ...fields }; + + await expect( + createAcknowledgement(context, input as unknown as AcknowledgementInput), + ).rejects.toThrow(message); + + expect(requests).toHaveLength(0); + }); + + it.each<[string, Record]>([ + ["a context string that is not a URI", { context: "not a uri" }], + ["a comment over the lexicon's limit", { comment: "x".repeat(10_001) }], + ])("writes nothing for %s", async (_, fields) => { + const { context, requests } = fakeRepo({ existing: { [subject]: CID } }); + const input = { subject: { uri: subject }, acknowledged: true, ...fields }; + + await expect(createAcknowledgement(context, input)).rejects.toThrow( + /input is not a valid org\.hypercerts\.context\.acknowledgement record/, + ); + + // The subject was read to build its reference, but nothing was written. + expect(methods(requests)).toEqual(["com.atproto.repo.getRecord"]); + }); + + it("writes nothing when the subject cannot be resolved", async () => { + const { context, requests } = fakeRepo(); + + await expect( + createAcknowledgement(context, { subject: { uri: subject }, acknowledged: true }), + ).rejects.toThrow(/cannot resolve .*the record was not found/); + + expect(methods(requests)).toEqual(["com.atproto.repo.getRecord"]); + }); + + it("fails before sending anything when the client is not authenticated", async () => { + const requests: string[] = []; + const client = new Client({ + fetchHandler: async (path) => { + requests.push(path); + return json(200, {}); + }, + }); + + await expect( + createAcknowledgement(createSDKContext({ client }), { + subject: { uri: subject }, + acknowledged: true, + }), + ).rejects.toThrow(/createAcknowledgement: the client is not authenticated/); + + expect(requests).toEqual([]); + }); +}); + +describe("createAcknowledgement when the write fails", () => { + const input = { subject: { uri: subject }, acknowledged: true }; + + it("reports a definite rejection and does not retry", async () => { + const { context, requests } = fakeRepo({ + existing: { [subject]: CID }, + applyWrites: () => json(400, { error: "InvalidRequest", message: "Bad record" }), + }); + + const error = await createAcknowledgement(context, input).catch((e) => e); + + expect(error).toBeInstanceOf(WriteRejectedError); + expect(methods(requests).filter((m) => m === APPLY)).toHaveLength(1); + }); + + it("reports an unknown outcome with the attempted URI and does not retry", async () => { + const { context, requests } = fakeRepo({ + existing: { [subject]: CID }, + applyWrites: () => json(500, {}), + }); + + const error = await createAcknowledgement(context, input).catch((e) => e); + + expect(error).toBeInstanceOf(WriteOutcomeUnknownError); + const sent = JSON.parse(new TextDecoder().decode(requests.at(-1)?.body)).writes[0] as { + collection: string; + rkey: string; + }; + expect(error.attempted.map((ref: { uri: string }) => ref.uri)).toEqual([ + `at://${DID}/${sent.collection}/${sent.rkey}`, + ]); + expect(methods(requests).filter((m) => m === APPLY)).toHaveLength(1); + }); +}); diff --git a/packages/sdk/src/context-records/create-attachment.test.ts b/packages/sdk/src/context-records/create-attachment.test.ts new file mode 100644 index 0000000..eb23347 --- /dev/null +++ b/packages/sdk/src/context-records/create-attachment.test.ts @@ -0,0 +1,324 @@ +import { isTidString } from "@atproto/lex"; +import { describe, expect, it } from "vitest"; +import { CID, DID, json } from "../test-utils/fake-pds.js"; +import { fakeRepo, methods, refTo, writeOf } from "../test-utils/fake-repo.js"; +import { + type AttachmentInput, + createAttachment, + RecordAlreadyExistsError, + WriteOutcomeUnknownError, + WriteRejectedError, +} from "./index.js"; + +const ATTACHMENT = "org.hypercerts.context.attachment"; +const ACTIVITY = "org.hypercerts.claim.activity"; +const VOCAB = "org.hypercerts.vocab.tag"; +const WORKSCOPE = "org.hypercerts.workscope.tag"; +const LOCATION = "app.certified.location"; + +const uriOf = (collection: string, rkey = "3k2a4b5c6d7e8") => `at://${DID}/${collection}/${rkey}`; +const tag = (category: string, key: string) => ({ category, key, name: key, status: "accepted" }); +const location = { + lpVersion: "1.0", + srs: "http://www.opengis.net/def/crs/OGC/1.3/CRS84", + locationType: "coordinate-decimal", + location: { string: "27.47,90.17" }, +}; +const pdf = () => new Blob(["report"], { type: "application/pdf" }); +const GET_RECORD = "com.atproto.repo.getRecord"; +const UPLOAD = "com.atproto.repo.uploadBlob"; +const APPLY = "com.atproto.repo.applyWrites"; + +describe("createAttachment", () => { + it("creates an attachment with subjects, content, a new location and new and existing tags in one write", async () => { + const activity = uriOf(ACTIVITY); + const existingTag = uriOf(VOCAB, "land-cover.wetland"); + const { context, requests, creates, updates } = fakeRepo({ + existing: { [activity]: CID, [existingTag]: CID }, + }); + + const result = await createAttachment(context, { + title: "Field survey", + subjects: [{ uri: activity }], + contentType: "evidence", + content: [pdf(), "https://example.org/survey"], + shortDescription: "June survey", + description: "# Findings", + langs: ["en"], + location, + tags: [ + { ...tag("evidence-kind", "survey"), broader: [tag("evidence-kind", "all")] }, + { uri: existingTag }, + ], + capturedAt: "2026-06-12T09:30:00+06:00", + createdAt: "2026-06-13T00:00:00.000Z", + }); + + // Existing records are read, the file is uploaded, then everything is written in one request. + expect(methods(requests).sort()).toEqual( + [GET_RECORD, GET_RECORD, GET_RECORD, GET_RECORD, UPLOAD, APPLY].sort(), + ); + expect(methods(requests).at(-1)).toBe(APPLY); + expect(methods(requests).indexOf(UPLOAD)).toBeLessThan(methods(requests).indexOf(APPLY)); + expect(updates.flat()).toEqual([]); + const writes = creates[0] ?? []; + // The location, the tags with a tag's broader tag first, then the Attachment. + expect(writes.map((write) => write.collection)).toEqual([LOCATION, VOCAB, VOCAB, ATTACHMENT]); + const attachment = writeOf(writes, ATTACHMENT); + expect(isTidString(attachment.rkey)).toBe(true); + const [newLocation, , survey] = writes.slice(0, 3).map(refTo); + expect(attachment.value).toEqual({ + $type: ATTACHMENT, + title: "Field survey", + subjects: [{ uri: activity, cid: CID }], + contentType: "evidence", + content: [ + { + $type: "org.hypercerts.defs#smallBlob", + blob: { $type: "blob", ref: expect.anything(), mimeType: "application/pdf", size: 6 }, + }, + { $type: "org.hypercerts.defs#uri", uri: "https://example.org/survey" }, + ], + shortDescription: "June survey", + description: { $type: "org.hypercerts.defs#descriptionString", value: "# Findings" }, + langs: ["en"], + location: newLocation, + tags: [survey, { uri: existingTag, cid: CID }], + capturedAt: "2026-06-12T09:30:00+06:00", + createdAt: "2026-06-13T00:00:00.000Z", + }); + expect(result).toEqual({ + ...refTo(attachment), + created: true, + subjects: [{ uri: activity, cid: CID, created: false }], + location: { ...newLocation, created: true }, + tags: [ + { + ...survey, + created: true, + broader: [{ ...refTo(writes[1] ?? attachment), created: true }], + }, + { uri: existingTag, cid: CID, created: false }, + ], + }); + }); + + it("creates an attachment with no subject, no content and nothing else as a single write", async () => { + const { context, requests, creates } = fakeRepo(); + + const result = await createAttachment(context, { title: "Baseline photos" }); + + expect(methods(requests)).toEqual([APPLY]); + expect(creates[0]).toHaveLength(1); + const write = writeOf(creates[0] ?? [], ATTACHMENT); + expect(write.value).toEqual({ + $type: ATTACHMENT, + title: "Baseline photos", + createdAt: expect.stringMatching(/^\d{4}-\d\d-\d\dT.*Z$/), + }); + expect(result).toEqual({ ...refTo(write), created: true }); + }); + + it("accepts a subject of any record type", async () => { + const subjects = [ + uriOf("app.certified.actor.profile", "self"), + uriOf("org.hypercerts.context.evaluation"), + uriOf("org.hypercerts.context.attachment"), + uriOf("org.hypercerts.collection"), + ]; + const { context, creates } = fakeRepo({ + existing: Object.fromEntries(subjects.map((uri) => [uri, CID])), + }); + + await createAttachment(context, { + title: "Comment", + subjects: subjects.map((uri) => ({ uri })), + }); + + expect(writeOf(creates[0] ?? [], ATTACHMENT).value.subjects).toEqual( + subjects.map((uri) => ({ uri, cid: CID })), + ); + }); + + it("keeps the order of the content and uploads each file", async () => { + const { context, requests, creates } = fakeRepo(); + + await createAttachment(context, { + title: "Files", + content: ["https://example.org/a", pdf(), "https://example.org/b"], + }); + + expect(methods(requests)).toEqual([UPLOAD, APPLY]); + expect( + (writeOf(creates[0] ?? [], ATTACHMENT).value.content as { $type: string }[]).map( + (item) => item.$type, + ), + ).toEqual([ + "org.hypercerts.defs#uri", + "org.hypercerts.defs#smallBlob", + "org.hypercerts.defs#uri", + ]); + }); + + it("reuses an existing location by URI without writing it", async () => { + const existingLocation = uriOf(LOCATION); + const { context, creates } = fakeRepo({ existing: { [existingLocation]: CID } }); + + const result = await createAttachment(context, { + title: "Photo", + location: { uri: existingLocation }, + }); + + expect(creates[0]).toHaveLength(1); + expect(writeOf(creates[0] ?? [], ATTACHMENT).value.location).toEqual({ + uri: existingLocation, + cid: CID, + }); + expect(result.location).toEqual({ uri: existingLocation, cid: CID, created: false }); + }); + + it.each<[string, Record, RegExp]>([ + [ + "a subject that is a bare string", + { subjects: [uriOf(ACTIVITY)] }, + /subjects\[0\] must be \{ uri \} of an existing record/, + ], + [ + "a subject mixed with other fields", + { subjects: [{ uri: uriOf(ACTIVITY), title: "x" }] }, + /subjects\[0\] combines `uri` with other fields/, + ], + [ + "a work-scope tag where a vocabulary tag is held", + { tags: [{ uri: uriOf(WORKSCOPE) }] }, + /tags\[0\] points at a record of type org\.hypercerts\.workscope\.tag, but this field holds org\.hypercerts\.vocab\.tag/, + ], + [ + "a vocabulary tag where a location is held", + { location: { uri: uriOf(VOCAB, "a.b") } }, + /location points at a record of type org\.hypercerts\.vocab\.tag, but this field holds app\.certified\.location/, + ], + [ + "a content entry that is a number", + { content: [5] }, + /must be a Blob or File.*\$\.content\[0\]/, + ], + ["a misspelled field", { subject: [] }, /Allowed fields: title, contentType, content/], + ["a missing title", { title: undefined }, /invalid input: .*title/], + [ + "a title the lexicon rejects", + { title: "x".repeat(257) }, + /input is not a valid org\.hypercerts\.context\.attachment record/, + ], + [ + "a capturedAt without a timezone", + { capturedAt: "2026-06-12" }, + /input is not a valid org\.hypercerts\.context\.attachment record/, + ], + [ + "a new location the lexicon rejects", + { location: { ...location, locationType: "x".repeat(21) } }, + /location is not a valid app\.certified\.location record/, + ], + [ + "two new tags with the same key", + { tags: [tag("a", "b"), tag("a", "b")] }, + /input\.tags\[0\] and input\.tags\[1\] are both new org\.hypercerts\.vocab\.tag records with the key a\.b/, + ], + ])("sends nothing for %s", async (_, fields, message) => { + const { context, requests } = fakeRepo(); + const input = { title: "Attachment", ...fields }; + + await expect(createAttachment(context, input as unknown as AttachmentInput)).rejects.toThrow( + message, + ); + + expect(requests).toHaveLength(0); + }); + + it("reads subjects before uploading anything, and writes nothing when one cannot be resolved", async () => { + const { context, requests } = fakeRepo(); + + await expect( + createAttachment(context, { + title: "Report", + subjects: [{ uri: uriOf(ACTIVITY) }], + content: [pdf()], + }), + ).rejects.toThrow(/cannot resolve .*the record was not found/); + + expect(methods(requests)).toEqual([GET_RECORD]); + }); + + it("checks that a new tag's key is free before uploading, and writes nothing when it is taken", async () => { + const taken = uriOf(VOCAB, "evidence-kind.survey"); + const { context, requests } = fakeRepo({ existing: { [taken]: CID } }); + + const error = await createAttachment(context, { + title: "Report", + content: [pdf()], + tags: [tag("evidence-kind", "survey")], + }).catch((e) => e); + + expect(error).toBeInstanceOf(RecordAlreadyExistsError); + expect(error.uri).toBe(taken); + expect(methods(requests)).toEqual([GET_RECORD]); + }); + + it("does not upload a file the lexicon would reject", async () => { + const { context, requests } = fakeRepo(); + const tooBig = new Blob([new Uint8Array(10 * 1024 * 1024 + 1)], { type: "application/pdf" }); + + await expect(createAttachment(context, { title: "Big", content: [tooBig] })).rejects.toThrow( + /content\[0\] cannot be stored as a blob.*Nothing was uploaded/, + ); + + expect(requests).toHaveLength(0); + }); + + it("does not write when an upload fails, and names the content entry", async () => { + const { context, requests } = fakeRepo({ uploadBlob: () => json(500, { error: "Internal" }) }); + + await expect( + createAttachment(context, { title: "Report", content: ["https://example.org/a", pdf()] }), + ).rejects.toThrow(/createAttachment: could not upload input\.content\[1\]/); + + expect(methods(requests)).toEqual([UPLOAD]); + }); +}); + +describe("createAttachment when the write fails", () => { + const input: AttachmentInput = { + title: "Report", + location, + tags: [tag("evidence-kind", "survey")], + }; + const attempted = (body: Uint8Array | undefined) => + ( + JSON.parse(new TextDecoder().decode(body)).writes as { collection: string; rkey: string }[] + ).map((w) => `at://${DID}/${w.collection}/${w.rkey}`); + + it("reports a definite rejection and does not retry", async () => { + const { context, requests } = fakeRepo({ + applyWrites: () => json(400, { error: "InvalidRequest", message: "Bad record" }), + }); + + const error = await createAttachment(context, input).catch((e) => e); + + expect(error).toBeInstanceOf(WriteRejectedError); + expect(error).toMatchObject({ status: 400, code: "InvalidRequest" }); + expect(methods(requests).filter((m) => m === APPLY)).toHaveLength(1); + }); + + it("reports an unknown outcome with every attempted URI and does not retry", async () => { + const { context, requests } = fakeRepo({ applyWrites: () => json(500, {}) }); + + const error = await createAttachment(context, input).catch((e) => e); + + expect(error).toBeInstanceOf(WriteOutcomeUnknownError); + const sent = requests.find((request) => request.path.endsWith("applyWrites")); + expect(error.attempted.map((ref: { uri: string }) => ref.uri)).toEqual(attempted(sent?.body)); + expect(error.attempted).toHaveLength(3); + expect(methods(requests).filter((m) => m === APPLY)).toHaveLength(1); + }); +}); diff --git a/packages/sdk/src/context-records/create-evaluation.test.ts b/packages/sdk/src/context-records/create-evaluation.test.ts new file mode 100644 index 0000000..84d5e77 --- /dev/null +++ b/packages/sdk/src/context-records/create-evaluation.test.ts @@ -0,0 +1,334 @@ +import { isTidString } from "@atproto/lex"; +import { describe, expect, it } from "vitest"; +import { CID, DID, json } from "../test-utils/fake-pds.js"; +import { fakeRepo, methods, refTo, writeOf } from "../test-utils/fake-repo.js"; +import { + createEvaluation, + type EvaluationInput, + WriteOutcomeUnknownError, + WriteRejectedError, +} from "./index.js"; + +const EVALUATION = "org.hypercerts.context.evaluation"; +const MEASUREMENT = "org.hypercerts.context.measurement"; +const ACTIVITY = "org.hypercerts.claim.activity"; +const LOCATION = "app.certified.location"; +const APPLY = "com.atproto.repo.applyWrites"; +const UPLOAD = "com.atproto.repo.uploadBlob"; + +const uriOf = (collection: string, rkey = "3k2a4b5c6d7e8") => `at://${DID}/${collection}/${rkey}`; +const location = (name: string) => ({ + lpVersion: "1.0", + srs: "http://www.opengis.net/def/crs/OGC/1.3/CRS84", + locationType: "coordinate-decimal", + location: { string: "27.47,90.17" }, + name, +}); +const base = { evaluators: ["did:plc:abc123"], summary: "Meets its targets." }; +const measurement = { metric: "Forest area restored", unit: "hectares", value: "1234.56" }; + +describe("createEvaluation", () => { + it("creates an evaluation with new and existing measurements, a new location and every field in one write", async () => { + const activity = uriOf(ACTIVITY); + const existingMeasurement = uriOf(MEASUREMENT); + const { context, requests, creates, updates } = fakeRepo({ + existing: { [activity]: CID, [existingMeasurement]: CID }, + }); + + const result = await createEvaluation(context, { + evaluators: ["did:plc:abc123", "did:plc:def456"], + summary: "Meets its targets.", + subject: { uri: activity }, + content: [new Blob(["report"], { type: "application/pdf" }), "https://example.org/report"], + measurements: [ + { ...measurement, measurers: ["did:plc:abc123"], locations: [location("plot")] }, + { uri: existingMeasurement }, + ], + score: { min: "0", max: "5", value: "4.2" }, + location: location("site"), + createdAt: "2026-07-01T00:00:00.000Z", + }); + + // Existing records are read, the file is uploaded, then everything is written in one request. + const sent = methods(requests); + expect(sent.filter((m) => m === APPLY)).toHaveLength(1); + expect(sent.at(-1)).toBe(APPLY); + expect(sent.indexOf(UPLOAD)).toBeGreaterThan(-1); + expect(updates.flat()).toEqual([]); + const writes = creates[0] ?? []; + // The measurement's location, the measurement, the evaluation's location, then the Evaluation. + expect(writes.map((write) => write.collection)).toEqual([ + LOCATION, + MEASUREMENT, + LOCATION, + EVALUATION, + ]); + const [plot, newMeasurement, site] = writes.slice(0, 3).map(refTo); + expect(writes[1]?.value).toEqual({ + $type: MEASUREMENT, + ...measurement, + measurers: [{ did: "did:plc:abc123" }], + locations: [plot], + // A nested record's createdAt is the time of the call, not the Evaluation's own createdAt. + createdAt: expect.stringMatching(/^\d{4}-\d\d-\d\dT.*Z$/), + }); + const evaluation = writeOf(writes, EVALUATION); + expect(isTidString(evaluation.rkey)).toBe(true); + expect(evaluation.value).toEqual({ + $type: EVALUATION, + evaluators: [{ did: "did:plc:abc123" }, { did: "did:plc:def456" }], + summary: "Meets its targets.", + subject: { uri: activity, cid: CID }, + content: [ + { + $type: "org.hypercerts.defs#smallBlob", + blob: { $type: "blob", ref: expect.anything(), mimeType: "application/pdf", size: 6 }, + }, + { $type: "org.hypercerts.defs#uri", uri: "https://example.org/report" }, + ], + measurements: [newMeasurement, { uri: existingMeasurement, cid: CID }], + score: { min: "0", max: "5", value: "4.2" }, + location: site, + createdAt: "2026-07-01T00:00:00.000Z", + }); + expect(result).toEqual({ + ...refTo(evaluation), + created: true, + subject: { uri: activity, cid: CID, created: false }, + measurements: [ + { ...newMeasurement, created: true, locations: [{ ...plot, created: true }] }, + { uri: existingMeasurement, cid: CID, created: false }, + ], + location: { ...site, created: true }, + }); + }); + + it("creates a bare evaluation as a single write", async () => { + const { context, requests, creates } = fakeRepo(); + + const result = await createEvaluation(context, base); + + expect(methods(requests)).toEqual([APPLY]); + expect(creates[0]).toHaveLength(1); + const write = writeOf(creates[0] ?? [], EVALUATION); + expect(write.value).toEqual({ + $type: EVALUATION, + evaluators: [{ did: "did:plc:abc123" }], + summary: "Meets its targets.", + createdAt: expect.stringMatching(/^\d{4}-\d\d-\d\dT.*Z$/), + }); + expect(result).toEqual({ ...refTo(write), created: true }); + }); + + it("only reuses existing measurements, without writing them", async () => { + const [first, second] = [ + uriOf(MEASUREMENT, "3k2a4b5c6d7e7"), + uriOf(MEASUREMENT, "3k2a4b5c6d7e9"), + ]; + const { context, creates } = fakeRepo({ existing: { [first]: CID, [second]: CID } }); + + const result = await createEvaluation(context, { + ...base, + measurements: [{ uri: first }, { uri: second }], + }); + + expect(creates[0]).toHaveLength(1); + expect(writeOf(creates[0] ?? [], EVALUATION).value.measurements).toEqual([ + { uri: first, cid: CID }, + { uri: second, cid: CID }, + ]); + expect(result.measurements).toEqual([ + { uri: first, cid: CID, created: false }, + { uri: second, cid: CID, created: false }, + ]); + }); + + it("reuses an existing location by URI without writing it", async () => { + const existingLocation = uriOf(LOCATION); + const { context, creates } = fakeRepo({ existing: { [existingLocation]: CID } }); + + const result = await createEvaluation(context, { + ...base, + location: { uri: existingLocation }, + }); + + expect(creates[0]).toHaveLength(1); + expect(writeOf(creates[0] ?? [], EVALUATION).value.location).toEqual({ + uri: existingLocation, + cid: CID, + }); + expect(result.location).toEqual({ uri: existingLocation, cid: CID, created: false }); + }); + + it("builds a nested measurement as createMeasurement does", async () => { + const { context, creates } = fakeRepo(); + + await createEvaluation(context, { ...base, measurements: [{ ...measurement, value: "0.10" }] }); + + // Same record shape, key type and value handling as the standalone creator. + const written = writeOf(creates[0] ?? [], MEASUREMENT); + expect(isTidString(written.rkey)).toBe(true); + expect(written.value.value).toBe("0.10"); + }); + + it.each<[string, { min: string; max: string; value: string }]>([ + ["the minimum", { min: "0", max: "5", value: "0" }], + ["the maximum", { min: "0", max: "5", value: "5" }], + ["trailing zeros", { min: "0.10", max: "5", value: "0.1" }], + ["a negative scale", { min: "-5", max: "5", value: "-4.5" }], + ])("accepts a score at %s", async (_, score) => { + const { context, creates } = fakeRepo(); + + await createEvaluation(context, { ...base, score }); + + expect(writeOf(creates[0] ?? [], EVALUATION).value.score).toEqual(score); + }); + + it.each<[string, { min: string; max: string; value: string }]>([ + ["above the maximum", { min: "0", max: "5", value: "5.01" }], + ["below the minimum", { min: "0", max: "5", value: "-0.01" }], + ["below a negative minimum", { min: "-5", max: "5", value: "-5.5" }], + ])("rejects a score %s", async (_, score) => { + const { context, requests } = fakeRepo(); + + await expect(createEvaluation(context, { ...base, score })).rejects.toThrow( + /must have a value from min to max/, + ); + + expect(requests).toHaveLength(0); + }); + + it("does not lose precision comparing long scores", async () => { + const { context } = fakeRepo(); + const score = { min: "0", max: "12345678901234567890.1", value: "12345678901234567890.2" }; + + await expect(createEvaluation(context, { ...base, score })).rejects.toThrow( + /must have a value from min to max/, + ); + }); + + it.each<[string, Record, RegExp]>([ + ["no evaluators", { evaluators: undefined }, / at \$\.evaluators/], + [ + "an evaluator that is not a DID", + { evaluators: ["alice.example"] }, + /Invalid DID.*evaluators\[0\]/, + ], + [ + "a score with a number", + { score: { min: "0", max: "5", value: 3 } }, + /decimal number written as a string/, + ], + ["a score missing its max", { score: { min: "0", value: "3" } }, /max/], + ["a score on a reversed scale", { score: { min: "5", max: "0", value: "3" } }, /min to max/], + ["a subject that is a bare string", { subject: uriOf(ACTIVITY) }, /subject must be \{ uri \}/], + [ + "a measurement URI of another record type", + { measurements: [{ uri: uriOf(ACTIVITY) }] }, + /measurements\[0\] points at a record of type org\.hypercerts\.claim\.activity, but this field holds org\.hypercerts\.context\.measurement/, + ], + [ + "a measurement URI mixed with measurement fields", + { measurements: [{ uri: uriOf(MEASUREMENT), ...measurement }] }, + /measurements\[0\] combines `uri` with other fields/, + ], + [ + "a new measurement with a number value", + { measurements: [{ ...measurement, value: 5 }] }, + /decimal number written as a string/, + ], + [ + "a new measurement with a misspelled field", + { measurements: [{ ...measurement, metrik: "x" }] }, + /measurements\[0\].*Allowed fields: metric, unit, value/, + ], + [ + "a new location of the wrong shape", + { location: { ...location("x"), location: { url: "https://example.org" } } }, + /location.*must be \{ uri: string \}/, + ], + [ + "a location URI of another record type", + { location: { uri: uriOf(MEASUREMENT) } }, + /location points at a record of type org\.hypercerts\.context\.measurement, but this field holds app\.certified\.location/, + ], + ["a misspelled field", { sumary: "x" }, /Allowed fields: evaluators, summary, content/], + [ + "a summary the lexicon rejects", + { summary: "x".repeat(5001) }, + /input is not a valid org\.hypercerts\.context\.evaluation record/, + ], + ])("sends nothing for %s", async (_, fields, message) => { + const { context, requests } = fakeRepo(); + + await expect( + createEvaluation(context, { ...base, ...fields } as unknown as EvaluationInput), + ).rejects.toThrow(message); + + expect(requests).toHaveLength(0); + }); + + it("reads existing measurements before uploading, and writes nothing when one is missing", async () => { + const { context, requests } = fakeRepo(); + + await expect( + createEvaluation(context, { + ...base, + content: [new Blob(["x"], { type: "application/pdf" })], + measurements: [{ uri: uriOf(MEASUREMENT) }], + }), + ).rejects.toThrow(/cannot resolve .*the record was not found/); + + expect(methods(requests)).toEqual(["com.atproto.repo.getRecord"]); + }); + + it("does not write when an upload fails", async () => { + const { context, requests } = fakeRepo({ uploadBlob: () => json(500, { error: "Internal" }) }); + + await expect( + createEvaluation(context, { + ...base, + measurements: [measurement], + content: [new Blob(["x"], { type: "application/pdf" })], + }), + ).rejects.toThrow(/createEvaluation: could not upload input\.content\[0\]/); + + expect(methods(requests)).toEqual([UPLOAD]); + }); +}); + +describe("createEvaluation when the write fails", () => { + const input: EvaluationInput = { + ...base, + measurements: [{ ...measurement, locations: [location("plot")] }], + }; + + it("reports a definite rejection and does not retry", async () => { + const { context, requests } = fakeRepo({ + applyWrites: () => json(400, { error: "InvalidRequest", message: "Bad record" }), + }); + + const error = await createEvaluation(context, input).catch((e) => e); + + expect(error).toBeInstanceOf(WriteRejectedError); + expect(error.message).toMatch(/the 3 records were not created/); + expect(methods(requests)).toEqual([APPLY]); + }); + + it("reports an unknown outcome with every attempted URI and does not retry", async () => { + const { context, requests } = fakeRepo({ applyWrites: () => json(500, {}) }); + + const error = await createEvaluation(context, input).catch((e) => e); + + expect(error).toBeInstanceOf(WriteOutcomeUnknownError); + const sent = JSON.parse(new TextDecoder().decode(requests[0]?.body)).writes as { + collection: string; + rkey: string; + }[]; + expect(error.attempted.map((ref: { uri: string }) => ref.uri)).toEqual( + sent.map((w) => `at://${DID}/${w.collection}/${w.rkey}`), + ); + expect(error.attempted).toHaveLength(3); + expect(methods(requests)).toEqual([APPLY]); + }); +}); diff --git a/packages/sdk/src/context-records/create-measurement.test.ts b/packages/sdk/src/context-records/create-measurement.test.ts new file mode 100644 index 0000000..b07ae5f --- /dev/null +++ b/packages/sdk/src/context-records/create-measurement.test.ts @@ -0,0 +1,214 @@ +import { isTidString } from "@atproto/lex"; +import { describe, expect, it } from "vitest"; +import { CID, DID, json } from "../test-utils/fake-pds.js"; +import { fakeRepo, methods, refTo, writeOf } from "../test-utils/fake-repo.js"; +import { + createMeasurement, + type MeasurementInput, + WriteOutcomeUnknownError, + WriteRejectedError, +} from "./index.js"; + +const MEASUREMENT = "org.hypercerts.context.measurement"; +const ACTIVITY = "org.hypercerts.claim.activity"; +const LOCATION = "app.certified.location"; + +const uriOf = (collection: string, rkey = "3k2a4b5c6d7e8") => `at://${DID}/${collection}/${rkey}`; +const location = { + lpVersion: "1.0", + srs: "http://www.opengis.net/def/crs/OGC/1.3/CRS84", + locationType: "coordinate-decimal", + location: { string: "27.47,90.17" }, +}; +const base = { metric: "Forest area restored", unit: "hectares", value: "1234.56" }; +const APPLY = "com.atproto.repo.applyWrites"; + +describe("createMeasurement", () => { + it("creates a measurement with every field, a new and an existing location, in one write", async () => { + const activity = uriOf(ACTIVITY); + const existingLocation = uriOf(LOCATION); + const { context, requests, creates } = fakeRepo({ + existing: { [activity]: CID, [existingLocation]: CID }, + }); + + const result = await createMeasurement(context, { + ...base, + subjects: [{ uri: activity }], + startDate: "2026-01-01T00:00:00.000Z", + endDate: "2026-06-30T00:00:00.000Z", + locations: [{ uri: existingLocation }, location], + methodType: "remote-sensing", + methodURI: "https://example.org/method", + evidenceURI: ["https://example.org/data.csv", uriOf("org.hypercerts.claim.evidence")], + measurers: ["did:plc:abc123", "did:plc:def456"], + comment: "Season one.", + createdAt: "2026-07-01T00:00:00.000Z", + }); + + expect(methods(requests).at(-1)).toBe(APPLY); + expect(methods(requests).filter((m) => m === APPLY)).toHaveLength(1); + const writes = creates[0] ?? []; + expect(writes.map((write) => write.collection)).toEqual([LOCATION, MEASUREMENT]); + const measurement = writeOf(writes, MEASUREMENT); + expect(isTidString(measurement.rkey)).toBe(true); + const newLocation = refTo(writeOf(writes, LOCATION)); + expect(measurement.value).toEqual({ + $type: MEASUREMENT, + ...base, + subjects: [{ uri: activity, cid: CID }], + startDate: "2026-01-01T00:00:00.000Z", + endDate: "2026-06-30T00:00:00.000Z", + locations: [{ uri: existingLocation, cid: CID }, newLocation], + methodType: "remote-sensing", + methodURI: "https://example.org/method", + evidenceURI: ["https://example.org/data.csv", uriOf("org.hypercerts.claim.evidence")], + measurers: [{ did: "did:plc:abc123" }, { did: "did:plc:def456" }], + comment: "Season one.", + createdAt: "2026-07-01T00:00:00.000Z", + }); + expect(result).toEqual({ + ...refTo(measurement), + created: true, + subjects: [{ uri: activity, cid: CID, created: false }], + locations: [ + { uri: existingLocation, cid: CID, created: false }, + { ...newLocation, created: true }, + ], + }); + }); + + it("creates a bare measurement as a single write", async () => { + const { context, requests, creates } = fakeRepo(); + + const result = await createMeasurement(context, base); + + expect(methods(requests)).toEqual([APPLY]); + expect(creates[0]).toHaveLength(1); + const write = writeOf(creates[0] ?? [], MEASUREMENT); + expect(write.value.subjects).toBeUndefined(); + expect(result).toEqual({ ...refTo(write), created: true }); + }); + + it.each(["0.10", "-3", "007", "12345678901234567890.123456789"])( + "stores the value %s exactly as written", + async (value) => { + const { context, creates } = fakeRepo(); + + await createMeasurement(context, { ...base, value }); + + expect(writeOf(creates[0] ?? [], MEASUREMENT).value.value).toBe(value); + }, + ); + + it("does not modify its subjects", async () => { + const activity = uriOf(ACTIVITY); + const { context, creates, updates, puts } = fakeRepo({ existing: { [activity]: CID } }); + + await createMeasurement(context, { ...base, subjects: [{ uri: activity }] }); + + expect(creates[0]).toHaveLength(1); + expect(updates.flat()).toEqual([]); + expect(puts).toEqual([]); + }); + + it.each<[string, Record, RegExp]>([ + [ + "a number as the value", + { value: 1234.56 }, + /decimal number written as a string.* at \$\.value/, + ], + [ + "a value with a thousands separator", + { value: "1,234" }, + /decimal number written as a string/, + ], + ["a value in exponent notation", { value: "1e3" }, /decimal number written as a string/], + ["an empty value", { value: "" }, /decimal number written as a string/], + [ + "an end date before the start date", + { startDate: "2026-02-01T00:00:00Z", endDate: "2026-01-01T00:00:00Z" }, + /endDate before its startDate/, + ], + [ + "a measurer that is not a DID", + { measurers: ["alice.example"] }, + /Invalid DID.*measurers\[0\]/, + ], + [ + "a subject that is a bare string", + { subjects: [uriOf(ACTIVITY)] }, + /subjects\[0\] must be \{ uri \} of an existing record/, + ], + [ + "a location URI of another record type", + { locations: [{ uri: uriOf(ACTIVITY) }] }, + /locations\[0\] points at a record of type org\.hypercerts\.claim\.activity, but this field holds app\.certified\.location/, + ], + [ + "a location URI mixed with location fields", + { locations: [{ uri: uriOf(LOCATION), ...location }] }, + /locations\[0\] combines `uri` with other fields/, + ], + ["a misspelled field", { metrik: "x" }, /Allowed fields: metric, unit, value/], + [ + "a unit the lexicon rejects", + { unit: "x".repeat(51) }, + /input is not a valid org\.hypercerts\.context\.measurement record/, + ], + [ + "a methodURI that is not a URI", + { methodURI: "not a uri" }, + /input is not a valid org\.hypercerts\.context\.measurement record/, + ], + ])("sends nothing for %s", async (_, fields, message) => { + const { context, requests } = fakeRepo(); + + await expect( + createMeasurement(context, { ...base, ...fields } as unknown as MeasurementInput), + ).rejects.toThrow(message); + + expect(requests).toHaveLength(0); + }); + + it("reads existing records before writing, and writes nothing when one is missing", async () => { + const { context, requests } = fakeRepo(); + + await expect( + createMeasurement(context, { ...base, subjects: [{ uri: uriOf(ACTIVITY) }] }), + ).rejects.toThrow(/cannot resolve .*the record was not found/); + + expect(methods(requests)).toEqual(["com.atproto.repo.getRecord"]); + }); +}); + +describe("createMeasurement when the write fails", () => { + it("reports a definite rejection and does not retry", async () => { + const { context, requests } = fakeRepo({ + applyWrites: () => json(400, { error: "InvalidRequest", message: "Bad record" }), + }); + + const error = await createMeasurement(context, base).catch((e) => e); + + expect(error).toBeInstanceOf(WriteRejectedError); + expect(methods(requests)).toEqual([APPLY]); + }); + + it("reports an unknown outcome with every attempted URI and does not retry", async () => { + const { context, requests } = fakeRepo({ applyWrites: () => json(500, {}) }); + + const error = await createMeasurement(context, { ...base, locations: [location] }).catch( + (e) => e, + ); + + expect(error).toBeInstanceOf(WriteOutcomeUnknownError); + const sent = JSON.parse(new TextDecoder().decode(requests[0]?.body)).writes as { + collection: string; + rkey: string; + }[]; + expect(error.attempted.map((ref: { uri: string }) => ref.uri)).toEqual( + sent.map((w) => `at://${DID}/${w.collection}/${w.rkey}`), + ); + expect(error.attempted).toHaveLength(2); + expect(methods(requests)).toEqual([APPLY]); + }); +}); diff --git a/packages/sdk/src/context-records/index.ts b/packages/sdk/src/context-records/index.ts new file mode 100644 index 0000000..0ee5a22 --- /dev/null +++ b/packages/sdk/src/context-records/index.ts @@ -0,0 +1,33 @@ +// Entry point for @hypercerts-org/sdk/context. +export type { StrongRef } from "../internal/resolve-record-ref.js"; +export type { ExistingRecord, SupportingRecordRef } from "../internal/slots.js"; +export { + RecordAlreadyExistsError, + WriteError, + WriteOutcomeUnknownError, + WriteRejectedError, + WriteResultMismatchError, +} from "../internal/submit-writes.js"; +export type { LocationInput } from "../location/build-location.js"; +export type { VocabularyTagInput, VocabularyTagResult } from "../tag/build-tag.js"; +export { + type AcknowledgementInput, + type CreateAcknowledgementResult, + createAcknowledgement, +} from "./build-acknowledgement.js"; +export { + type AttachmentInput, + type CreateAttachmentResult, + createAttachment, +} from "./build-attachment.js"; +export { + type CreateEvaluationResult, + createEvaluation, + type EvaluationInput, +} from "./build-evaluation.js"; +export { + createMeasurement, + type MeasurementInput, + type MeasurementResult, +} from "./build-measurement.js"; +export type { EvaluationScore } from "./score.js"; diff --git a/packages/sdk/src/context-records/score.ts b/packages/sdk/src/context-records/score.ts new file mode 100644 index 0000000..a95c945 --- /dev/null +++ b/packages/sdk/src/context-records/score.ts @@ -0,0 +1,53 @@ +import { l } from "@atproto/lex"; +import { strictObject } from "../internal/input.js"; +import { decimalString } from "./shared.js"; + +/** + * An overall score on a numeric scale. All three are decimal strings, for example + * `{ min: "0", max: "5", value: "3.7" }`. + */ +export interface EvaluationScore { + /** The lowest value of the scale. At most 50 characters. */ + min: string; + /** The highest value of the scale, not below `min`. At most 50 characters. */ + max: string; + /** The score, from `min` to `max` inclusive. At most 50 characters. */ + value: string; +} + +/** + * Orders two decimal strings by value, exactly: no JavaScript number is involved, so `"0.1"` and + * `"0.10"` are equal and 30-digit values compare correctly. Both must match `decimalString`. + * Negative when `a < b`, zero when equal, positive when `a > b`. + */ +export function compareDecimals(a: string, b: string): number { + const [x, y] = [parseDecimal(a), parseDecimal(b)]; + const scale = Math.max(x.fraction.length, y.fraction.length); + const scaled = ({ negative, whole, fraction }: Decimal) => + BigInt(`${negative ? "-" : ""}${whole}${fraction.padEnd(scale, "0")}`); + const difference = scaled(x) - scaled(y); + if (difference === 0n) return 0; + return difference < 0n ? -1 : 1; +} + +interface Decimal { + negative: boolean; + whole: string; + fraction: string; +} + +function parseDecimal(value: string): Decimal { + const negative = value.startsWith("-"); + const [whole = "", fraction = ""] = (negative ? value.slice(1) : value).split("."); + return { negative, whole, fraction }; +} + +/** Input schema of an {@link EvaluationScore}: decimal strings with `value` from `min` to `max`. */ +export const scoreInput = l.refine( + strictObject({ min: decimalString, max: decimalString, value: decimalString }), + { + check: ({ min, max, value }: EvaluationScore) => + compareDecimals(min, value) <= 0 && compareDecimals(value, max) <= 0, + message: "must have a value from min to max, inclusive", + }, +); diff --git a/packages/sdk/src/context-records/shared.ts b/packages/sdk/src/context-records/shared.ts new file mode 100644 index 0000000..97bf314 --- /dev/null +++ b/packages/sdk/src/context-records/shared.ts @@ -0,0 +1,83 @@ +import { l } from "@atproto/lex"; +import { createRecordTree, type StandaloneCreator } from "../internal/create-record.js"; +import { blobOrUrl } from "../internal/input.js"; +import { mediaValue } from "../internal/media.js"; +import { + type FieldTransform, + type RecordKind, + type ReferenceField, + references, +} from "../internal/record-kind.js"; +import { type ExistingRecord, isExistingRecord } from "../internal/slots.js"; +import { locationKind } from "../location/build-location.js"; + +// What more than one of the context records have in common: `content`, DID lists, decimal strings, +// links to other records, and the way a creator is bound to its kind. + +/** Input schema of an optional `content` array: files to upload and URLs to keep. */ +export const contentInput = l.optional(l.array(blobOrUrl)); + +/** + * The `recordKind` transform of a `content` array: each `Blob` is uploaded as `smallBlob` and each + * string kept as `org.hypercerts.defs#uri`, in the order given. + */ +export const contentTransform: FieldTransform = (build, field, value: readonly (Blob | string)[]) => + Promise.all(value.map((item, i) => mediaValue(build, `${field}[${i}]`, item, "blob"))); + +/** A list of DIDs, for example `["did:plc:abc123"]`. */ +export const didListInput = l.array(l.string({ format: "did" })); + +/** + * The `recordKind` transform of a DID list: the lexicon stores each DID as an + * `app.certified.defs#did` object. + */ +export const didListTransform: FieldTransform = (_build, _field, dids: readonly string[]) => + Promise.resolve(dids.map((did) => ({ did }))); + +const DECIMAL = /^-?\d+(\.\d+)?$/; + +/** + * A decimal number written as a string, for example `"1234.56"` or `"-3"`. The lexicons store + * measured values and scores as numeric strings so that no precision is lost; this rejects a + * JavaScript number (which would be converted silently) and text such as `"1,234"` or `"1e3"`. + * The string is kept as written. Its length is left to the lexicon. + */ +export const decimalString = l.custom( + (value): value is string => typeof value === "string" && DECIMAL.test(value), + 'must be a decimal number written as a string, such as "1234.56" or "-3", not a JavaScript number', +); + +/** + * Input schema of a field that is `{ uri }` of an existing record, of any type. For a required + * link: an optional one is declared by its `ReferenceField` alone. + */ +export const existingRecordInput = l.custom( + isExistingRecord, + 'must be { uri } of an existing record, for example { uri: "at://did:plc:abc123/org.hypercerts.claim.activity/3k2a4b5c6d7e8" }', +); + +/** A field that holds one existing record of any type: `{ uri }`, stored as a strong reference. */ +export const existingRecordReference: ReferenceField = { kind: undefined, many: false }; + +/** A field that holds an array of existing records of any type: `{ uri }` entries. */ +export const existingRecordsReference: ReferenceField = { kind: undefined, many: true }; + +/** A field that holds one location: the data of a new one or `{ uri }` of an existing one. */ +export const locationReference: ReferenceField = references.one(() => locationKind); + +/** A field that holds an array of locations: each the data of a new one or `{ uri }` of an existing one. */ +export const locationsReference: ReferenceField = references.many(() => locationKind); + +/** + * The public creator of a record kind: creates the record and every new record it points at in one + * write (see `createRecordTree`) and returns the record's reference with the results for the + * records it points at. `TResult` is the creator's public result type, which declares that shape. + * `operation` is the public function's name, used in error messages. + */ +export const creatorOf = + ( + operation: string, + kind: RecordKind, + ): StandaloneCreator => + (context, input) => + createRecordTree(context, operation, kind, input); From 1e88cc1ad6e18d8d8d4fae44e37c048596edd499 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Tue, 10 Nov 2026 19:38:52 +0600 Subject: [PATCH 2/2] sdk/context: describe uploads and write errors in the short form --- .../hypercerts-org-sdk/references/context.md | 6 ++++-- .../context-records/build-acknowledgement.ts | 8 ++++---- .../sdk/src/context-records/build-attachment.ts | 17 ++++++++--------- .../sdk/src/context-records/build-evaluation.ts | 16 +++++++--------- .../src/context-records/build-measurement.ts | 12 ++++++------ 5 files changed, 29 insertions(+), 30 deletions(-) diff --git a/.agents/skills/hypercerts-org-sdk/references/context.md b/.agents/skills/hypercerts-org-sdk/references/context.md index 66e4625..fd8a322 100644 --- a/.agents/skills/hypercerts-org-sdk/references/context.md +++ b/.agents/skills/hypercerts-org-sdk/references/context.md @@ -21,7 +21,7 @@ All four write a TID-keyed record to the signed-in account's repo. The first thr | `{ uri }` in `location`, `locations`, `tags`, `measurements` | An existing record of that field's type (`app.certified.location`, `org.hypercerts.vocab.tag`, `org.hypercerts.context.measurement`). Another type throws `TypeError`. | | The fields of a record, in those same four | A new record, created in the same write. Never mixed with `uri`. | | A string in `content`, an acknowledgement's `context` | A URL/URI stored as it is, never fetched, no CID. | -| A `Blob`/`File` in `content` | Uploaded for you before the write (any type, up to 10 MB; a `Blob` needs a `type`). | +| A `Blob`/`File` in `content` | Uploaded for you (any type, up to 10 MB; a `Blob` needs a `type`). | A subject is not limited to an Activity and is not changed: it does not learn about the attachment, measurement or evaluation, and nothing here links an existing record to its subject afterwards. Subject URIs must use a DID, not a handle. A bare string where `{ uri }` is required throws `TypeError`. @@ -139,7 +139,9 @@ Not supported: `signatures`, `shortDescriptionFacets`, `commentFacets`, and a no ## Failures -Input errors, unresolved or wrongly typed `{ uri }` records and files the lexicon would reject fail before anything is sent. Files are uploaded before the write and are not rolled back: after a failed write they stay unreferenced. `WriteRejectedError` means nothing was created. After `WriteOutcomeUnknownError` the records may exist and `attempted` lists every URI (the primary record is last). Calling again would create new records under new keys: check the URIs first. The SDK never retries. +Input errors, unresolved or wrongly typed `{ uri }` records and files the lexicon would reject fail before anything is sent. See [Handle failures](../SKILL.md#6-handle-failures) for the write errors. After `WriteOutcomeUnknownError` the primary record is last in `attempted`, and calling again would create new records under new keys: check the URIs first. + +Files (`content`, a new tag's `referenceDocument`, a new location's `{ blob }`) are uploaded before the write and are not rolled back if it fails; see [Uploads are not part of the atomic write](../SKILL.md#uploads-are-not-part-of-the-atomic-write). ## Pitfalls diff --git a/packages/sdk/src/context-records/build-acknowledgement.ts b/packages/sdk/src/context-records/build-acknowledgement.ts index 9371d3e..9be4764 100644 --- a/packages/sdk/src/context-records/build-acknowledgement.ts +++ b/packages/sdk/src/context-records/build-acknowledgement.ts @@ -113,10 +113,10 @@ const acknowledgementKind: RecordKind = recordKind( * `context` string that is not a URI. The message names the field. Nothing was written. * @throws {@link Error} If the client is not authenticated, or the `subject` or `context` record * cannot be read. Nothing was written. - * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the record - * may or may not exist. It carries the URI to check; the SDK does not retry, because a retry would - * create a second acknowledgement under a new key if the first attempt had succeeded. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create a second acknowledgement under a new key if the first attempt had + * succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK * computed. * diff --git a/packages/sdk/src/context-records/build-attachment.ts b/packages/sdk/src/context-records/build-attachment.ts index 4524227..6489a5b 100644 --- a/packages/sdk/src/context-records/build-attachment.ts +++ b/packages/sdk/src/context-records/build-attachment.ts @@ -135,9 +135,10 @@ const attachmentKind: RecordKind = recordKind( * with no new location or tag is a write of one record. One write holds at most 200 records. The * OAuth session needs `create` on the attachment, tag and location collections it writes to. * - * Files are uploaded before the write and outside it. If the write fails, they are left unused and - * the PDS may or may not delete them later. A lexicon rule that rejects the record (for example - * more than 100 `content` entries) is found only after the uploads. + * Files (`Blob` or `File` values) are uploaded: the `content` entries, a new tag's + * `referenceDocument` and a new location's `{ blob }`. Blobs are uploaded before the write and are + * not rolled back if it fails; see {@link uploadBlob}. A lexicon rule that rejects a record (for + * example more than 100 `content` entries) is found only after the uploads. * * Not supported: the lexicon's `signatures` and `shortDescriptionFacets`, a `description` that is * not a string, and a blob that was uploaded already. @@ -156,12 +157,10 @@ const attachmentKind: RecordKind = recordKind( * @throws {@link Error} If the client is not authenticated, a `subjects` or other existing record * cannot be read, the key of a new tag cannot be checked, or an upload fails. Nothing was written. * @throws {@link RecordAlreadyExistsError} If a new tag's key is taken. Nothing was written. - * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). None of the records - * was created and nothing needs cleaning up. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS (network - * failure, timeout, a server error), so the records may or may not exist. It lists every URI that - * was attempted. The SDK does not retry, because a retry would create a second Attachment under a - * new key if the first attempt had succeeded. Check the URIs, then decide. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create a second Attachment under a new key if the first attempt had + * succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported different URIs or CIDs than the SDK * computed. * diff --git a/packages/sdk/src/context-records/build-evaluation.ts b/packages/sdk/src/context-records/build-evaluation.ts index b3cf284..f1b6a97 100644 --- a/packages/sdk/src/context-records/build-evaluation.ts +++ b/packages/sdk/src/context-records/build-evaluation.ts @@ -119,9 +119,10 @@ const evaluationKind: RecordKind = recordKind( * records. The OAuth session needs `create` on the evaluation, measurement and location collections * it writes to. * - * Files are uploaded before the write and outside it. If the write fails, they are left unused and - * the PDS may or may not delete them later. A lexicon rule that rejects the record is found only - * after the uploads. + * Files (`Blob` or `File` values) are uploaded: the `content` entries and a `{ blob }` in a new + * location, whether it is the evaluation's or a new measurement's. Blobs are uploaded before the + * write and are not rolled back if it fails; see {@link uploadBlob}. A lexicon rule that rejects a + * record is found only after the uploads. * * Not supported: the lexicon's `signatures`. * @@ -138,12 +139,9 @@ const evaluationKind: RecordKind = recordKind( * when a lexicon rule rejects a record. * @throws {@link Error} If the client is not authenticated, an existing record cannot be read, or * an upload fails. Nothing was written. - * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). None of the records - * was created and nothing needs cleaning up. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS (network - * failure, timeout, a server error), so the records may or may not exist. It lists every URI that - * was attempted. The SDK does not retry, because a retry would create duplicates under new keys - * if the first attempt had succeeded. Check the URIs, then decide. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create duplicates under new keys if the first attempt had succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported different URIs or CIDs than the SDK * computed. * diff --git a/packages/sdk/src/context-records/build-measurement.ts b/packages/sdk/src/context-records/build-measurement.ts index 2550163..eb45c39 100644 --- a/packages/sdk/src/context-records/build-measurement.ts +++ b/packages/sdk/src/context-records/build-measurement.ts @@ -129,6 +129,9 @@ export const measurementKind: RecordKind = recordKind( * with no new location is a write of one record. One write holds at most 200 records. The OAuth * session needs `create` on the measurement and location collections it writes to. * + * A `{ blob }` in a new location is uploaded. Blobs are uploaded before the write and are not + * rolled back if it fails; see {@link uploadBlob}. + * * Not supported: the lexicon's `signatures` and `commentFacets`. * * @param context - The shared context from {@link createSDKContext}. Its client must be @@ -144,12 +147,9 @@ export const measurementKind: RecordKind = recordKind( * may already have been uploaded when a lexicon rule rejects a record. * @throws {@link Error} If the client is not authenticated, an existing record cannot be read, or * an upload fails. - * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). None of the records - * was created and nothing needs cleaning up. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS (network - * failure, timeout, a server error), so the records may or may not exist. It lists every URI that - * was attempted. The SDK does not retry, because a retry would create duplicates under new keys - * if the first attempt had succeeded. Check the URIs, then decide. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create duplicates under new keys if the first attempt had succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported different URIs or CIDs than the SDK * computed. *