techne-sdk 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The client context, its `TechneProvider` and `useTechne` (re-exported by `techne-sdk/react`). Its own
3
+ * module, not in the package's exports, so `techne-sdk/react` and `techne-sdk/react/query` share one context
4
+ * and `react/query` never loads `useEvent`.
5
+ */
6
+ import { type ReactNode } from 'react';
7
+ import type { Techne } from '../connect.js';
8
+ export declare const TechneContext: import("react").Context<Techne | null>;
9
+ /** `<TechneProvider>` over a client made elsewhere. */
10
+ export interface TechneProviderProps {
11
+ techne: Techne;
12
+ children?: ReactNode;
13
+ }
14
+ /** Makes `techne` (what `connect`, `connectHosted` or `connectAnonymous` answers) the client every hook
15
+ * below it reads through. */
16
+ export declare function TechneProvider({ techne, children }: TechneProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<Techne | null>>;
17
+ /** The client of the nearest `TechneProvider`. */
18
+ export declare function useTechne(): Techne;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The client context, its `TechneProvider` and `useTechne` (re-exported by `techne-sdk/react`). Its own
3
+ * module, not in the package's exports, so `techne-sdk/react` and `techne-sdk/react/query` share one context
4
+ * and `react/query` never loads `useEvent`.
5
+ */
6
+ import { createContext, createElement, useContext } from 'react';
7
+ export const TechneContext = createContext(null);
8
+ /** Makes `techne` (what `connect`, `connectHosted` or `connectAnonymous` answers) the client every hook
9
+ * below it reads through. */
10
+ export function TechneProvider({ techne, children }) {
11
+ return createElement(TechneContext.Provider, { value: techne }, children);
12
+ }
13
+ /** The client of the nearest `TechneProvider`. */
14
+ export function useTechne() {
15
+ const techne = useContext(TechneContext);
16
+ if (!techne)
17
+ throw new Error('techne-sdk/react: no TechneProvider above this component (wrap the app in <TechneProvider techne={techne}>)');
18
+ return techne;
19
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * techne-sdk/react — the client in React: `TechneProvider` (the client every hook below it reads through),
3
+ * `useTechne`, and `useEvent` (one commons event or place as its versions, `techne-sdk/versions`), as in
4
+ * 0.3.3. Needs React only.
5
+ *
6
+ * The client's reads as hooks over TanStack Query (`useRecordQuery`, `useRecord`, `useVersions`) are
7
+ * `techne-sdk/react/query`, so an app without `@tanstack/react-query` still loads this module.
8
+ *
9
+ * This module never signs in: it does not import `techne-sdk/auth`, so an app holding its own client
10
+ * (Beacon's `connectHosted`) ships no OAuth client. Sign in with `techne-sdk/auth`, then hand
11
+ * `connect(session)` to `<TechneProvider techne=…>`.
12
+ */
13
+ export { TechneProvider, useTechne, type TechneProviderProps } from './context.js';
14
+ export { useEvent, type UseEvent, type UseEventOptions } from '../versions/react.js';
@@ -0,0 +1,14 @@
1
+ /**
2
+ * techne-sdk/react — the client in React: `TechneProvider` (the client every hook below it reads through),
3
+ * `useTechne`, and `useEvent` (one commons event or place as its versions, `techne-sdk/versions`), as in
4
+ * 0.3.3. Needs React only.
5
+ *
6
+ * The client's reads as hooks over TanStack Query (`useRecordQuery`, `useRecord`, `useVersions`) are
7
+ * `techne-sdk/react/query`, so an app without `@tanstack/react-query` still loads this module.
8
+ *
9
+ * This module never signs in: it does not import `techne-sdk/auth`, so an app holding its own client
10
+ * (Beacon's `connectHosted`) ships no OAuth client. Sign in with `techne-sdk/auth`, then hand
11
+ * `connect(session)` to `<TechneProvider techne=…>`.
12
+ */
13
+ export { TechneProvider, useTechne } from './context.js';
14
+ export { useEvent } from '../versions/react.js';
@@ -0,0 +1,75 @@
1
+ import { QueryClient, type UseQueryResult } from '@tanstack/react-query';
2
+ import type { GetOpts, Page, QueryOpts, Versions } from '../connect.js';
3
+ import type { Include, IncludeOf, Item, ItemFor, RecordOfQuery, RecordOfUri } from '../item.js';
4
+ import type { Query } from '../query/index.js';
5
+ import { fieldConflict, versionPill, type EventState, type VersionEntry } from '../versions/index.js';
6
+ /** The QueryClient the hooks use when the app has no `QueryClientProvider`: one per app, made on first
7
+ * use, with TanStack's defaults. An app with its own client never touches it. */
8
+ export declare function defaultQueryClient(): QueryClient;
9
+ /** TanStack's result for a read of `R`, with `data` the SDK's `D` (each state of the union kept). */
10
+ export type ReadResult<R, D> = UseQueryResult<R> extends infer S ? (S extends {
11
+ data: infer X;
12
+ } ? Omit<S, 'data'> & {
13
+ data: X extends R ? D : undefined;
14
+ } : never) : never;
15
+ /** What every hook takes beside the read's own options. */
16
+ export interface HookOptions {
17
+ /** `false` holds the read (TanStack's `enabled`). */
18
+ enabled?: boolean;
19
+ /** `false` keeps the hook off the cache's updates and refetches while the component is mounted but hidden
20
+ * (a screen behind another), still drawing what it last had (TanStack's `subscribed`). */
21
+ subscribed?: boolean;
22
+ }
23
+ export type UseRecordQueryOptions = QueryOpts & HookOptions;
24
+ export type UseRecordQuery<T, I extends Include = 'valid'> = ReadResult<Page<T, I>, ItemFor<T, I>[]> & {
25
+ /** The whole page (`cursor` for the next one; `count` and `capped` when asked with `count`). */
26
+ page: Page<T, I> | undefined;
27
+ };
28
+ /**
29
+ * One page of a query document, `data` its items. Typed by the query: `useRecordQuery(Place.query(…))`
30
+ * answers `ValidItem<Place>[]`, and with `include: 'all'` (adding pending and invalid items) `Item<Place>[]`.
31
+ * `count`, `cursor`, `limit` and `params` are `techne.query`'s.
32
+ */
33
+ export declare function useRecordQuery<Q extends Query, O extends UseRecordQueryOptions = {}>(q: Q, options?: O): UseRecordQuery<RecordOfQuery<Q>, IncludeOf<O>>;
34
+ export type UseRecordOptions = GetOpts & HookOptions;
35
+ /**
36
+ * One record (`techne.get`), `data` its item, or `null` when nothing is there (or, unless `include: 'all'`,
37
+ * when what is there is not valid). Typed by the URI (`Uri<Place>` answers `ValidItem<Place>`; a bare string
38
+ * `unknown`). `prefer: 'mine'` the user's own version, `exact: true` exactly that record. A `null` or
39
+ * `undefined` uri reads nothing.
40
+ */
41
+ export declare function useRecord<U extends string, O extends UseRecordOptions = {}>(uri: U | null | undefined, options?: O): UseQueryResult<ItemFor<RecordOfUri<U>, IncludeOf<O>> | null>;
42
+ export type UseVersions<T> = Omit<UseQueryResult<Versions<T> | null>, 'data'> & {
43
+ /** The record: its composed record as served, or once a version is selected, that version's own values
44
+ * with their text decoded (`eventState`; same uri and verdict: it is still the thing asked for). Draw an
45
+ * unselected record through `decodeTextFields` too. `null` when nothing is there, `undefined` until read. */
46
+ item: Item<T> | null | undefined;
47
+ /** `eventState(data, selected)`, the Rust state the versions views draw (`versionGroups`, the sheet's
48
+ * rows, a field's values). `null` until read, and for a record with no versions (one answered privately). */
49
+ state: EventState | null;
50
+ /** Every version as the versions sheet lists them (`state.versions`), `showing`, `differs` and `same`
51
+ * relative to what is shown. Empty until read. */
52
+ versions: VersionEntry[];
53
+ /** Each field whose ranked versions disagree, and how many values they give (the composition's, whatever
54
+ * is shown). */
55
+ conflicts: Record<string, number>;
56
+ /** The version selected (its uri), or `null` for the composition. */
57
+ selected: string | null;
58
+ /** Show the version `uri`; `null` goes back to the composition. A uri not among the versions is ignored,
59
+ * and a selection a refetch drops is cleared. Resets when the hook's uri changes. */
60
+ select: (uri: string | null) => void;
61
+ /** The version speaking first: the one selected, else the composition's byline. */
62
+ byline: VersionEntry | null;
63
+ /** The version pill's props (`versionPill`, its defaults): the count while the versions conflict, who a
64
+ * picked version is from; `null` otherwise. */
65
+ pill: ReturnType<typeof versionPill>;
66
+ /** The field-conflict badge's props for one field or several (`fieldConflict`), `null` under 2. */
67
+ conflict: (field: string | readonly string[]) => ReturnType<typeof fieldConflict>;
68
+ };
69
+ /**
70
+ * A record as its versions (`techne.versions`): the composed item, every version and the conflicts, and
71
+ * the person's selection of another version, all from the Rust `eventState` over the platform's answer.
72
+ * `useRecord` and `useRecordQuery` never carry versions; this is the hook for a versions pill, a
73
+ * field-conflict badge and a versions sheet.
74
+ */
75
+ export declare function useVersions<U extends string>(uri: U | null | undefined, options?: HookOptions): UseVersions<RecordOfUri<U>>;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * techne-sdk/react/query — the client's reads as React hooks (SDK1), thin wrappers over its options forms
3
+ * (`techne.queryOptions`, `getOptions`, `versionsOptions`) with TanStack Query.
4
+ *
5
+ * ```tsx
6
+ * <TechneProvider techne={connect(session, platformDid)}><App /></TechneProvider>
7
+ *
8
+ * const places = useRecordQuery(Place.query({ text: { matches: 'cafe' } })) // data: ValidItem<Place>[]
9
+ * const place = useRecord(places.data?.[0]?.uri) // data: ValidItem<Place> | null
10
+ * const v = useVersions(place.data?.uri) // item, versions, select…
11
+ * ```
12
+ *
13
+ * Each hook answers TanStack's result (`isPending`, `error`, `refetch`, …) with `data` as the SDK's
14
+ * items. The reads go to the app's own QueryClient when a `QueryClientProvider` is above, so they share
15
+ * its cache, focus and invalidation (their keys start `['techne', …]` and end with the viewer's DID); with
16
+ * none, to one default client the SDK keeps (`defaultQueryClient()`). `@tanstack/react-query` is an optional peer dependency: only
17
+ * an app that imports this module needs it (`techne-sdk/react` does not).
18
+ *
19
+ * `useRecordQuery` and `useRecord` never carry versions; `useVersions` is the one read that does.
20
+ *
21
+ * This module never signs in: it does not import `techne-sdk/auth`, so an app holding its own client
22
+ * (Beacon's `connectHosted`) ships no OAuth client. Sign in with `techne-sdk/auth`, then hand
23
+ * `connect(session)` to `<TechneProvider techne=…>`. A test (`react.test.mjs`) holds this module's
24
+ * imports off auth.
25
+ *
26
+ * `TechneProvider` and `useTechne` are `techne-sdk/react`'s (React only); this module is the one that needs TanStack.
27
+ */
28
+ import { useCallback, useContext, useMemo, useState } from 'react';
29
+ import { QueryClient, QueryClientContext, useQuery } from '@tanstack/react-query';
30
+ import { conflictsOf, eventState, fieldConflict, versionPill } from '../versions/index.js';
31
+ import { useTechne } from './context.js';
32
+ let fallback;
33
+ /** The QueryClient the hooks use when the app has no `QueryClientProvider`: one per app, made on first
34
+ * use, with TanStack's defaults. An app with its own client never touches it. */
35
+ export function defaultQueryClient() {
36
+ if (!fallback) {
37
+ fallback = new QueryClient();
38
+ // What a QueryClientProvider does on mount: refetch on focus and reconnect.
39
+ fallback.mount();
40
+ }
41
+ return fallback;
42
+ }
43
+ /** The app's QueryClient when a provider is above, else the default one. Reads TanStack's context
44
+ * directly (its `useQueryClient` throws without a provider). */
45
+ function useClient() {
46
+ return useContext(QueryClientContext) ?? defaultQueryClient();
47
+ }
48
+ /** `result` with its `data` replaced and `extra` added. The one cast in this module: TanStack's result is a
49
+ * union over its states, and a spread of it loses which `data` goes with which status, so the caller's type
50
+ * (built over that union, {@link ReadResult}) is asserted here. */
51
+ function reshaped(result, fields = {}) {
52
+ return { ...result, ...fields };
53
+ }
54
+ /**
55
+ * One page of a query document, `data` its items. Typed by the query: `useRecordQuery(Place.query(…))`
56
+ * answers `ValidItem<Place>[]`, and with `include: 'all'` (adding pending and invalid items) `Item<Place>[]`.
57
+ * `count`, `cursor`, `limit` and `params` are `techne.query`'s.
58
+ */
59
+ export function useRecordQuery(q, options = {}) {
60
+ const { enabled, subscribed, ...opts } = options;
61
+ const techne = useTechne();
62
+ const result = useQuery({ ...techne.queryOptions(q, opts), enabled, subscribed }, useClient());
63
+ return reshaped(result, { data: result.data?.items, page: result.data });
64
+ }
65
+ /**
66
+ * One record (`techne.get`), `data` its item, or `null` when nothing is there (or, unless `include: 'all'`,
67
+ * when what is there is not valid). Typed by the URI (`Uri<Place>` answers `ValidItem<Place>`; a bare string
68
+ * `unknown`). `prefer: 'mine'` the user's own version, `exact: true` exactly that record. A `null` or
69
+ * `undefined` uri reads nothing.
70
+ */
71
+ export function useRecord(uri, options = {}) {
72
+ const { enabled = true, subscribed, ...opts } = options;
73
+ const techne = useTechne();
74
+ // `opts` is `O` less the hook's own options, which TypeScript cannot carry through `IncludeOf`.
75
+ return reshaped(useQuery({ ...techne.getOptions((uri ?? ''), opts), enabled: enabled && Boolean(uri), subscribed }, useClient()));
76
+ }
77
+ const NO_VERSIONS = [];
78
+ /**
79
+ * A record as its versions (`techne.versions`): the composed item, every version and the conflicts, and
80
+ * the person's selection of another version, all from the Rust `eventState` over the platform's answer.
81
+ * `useRecord` and `useRecordQuery` never carry versions; this is the hook for a versions pill, a
82
+ * field-conflict badge and a versions sheet.
83
+ */
84
+ export function useVersions(uri, options = {}) {
85
+ const { enabled = true, subscribed } = options;
86
+ const techne = useTechne();
87
+ const { data: answer, ...result } = useQuery({ ...techne.versionsOptions((uri ?? '')), enabled: enabled && Boolean(uri), subscribed }, useClient());
88
+ const raw = answer?.data ?? null;
89
+ const known = useCallback((v) => raw?.versions.some((x) => x.uri === v) ?? false, [raw]);
90
+ // A selection belongs to one uri: kept with it, so a new uri draws nothing of the old selection, not
91
+ // even for one frame, and dropped when the uri changes (React's state update during render), so coming
92
+ // back to the first uri starts from the composition. A selection the answer no longer lists (a refetch
93
+ // dropped that version) is dropped the same way, so it never comes back with a later answer.
94
+ const [selection, setSelection] = useState({ uri, selected: null });
95
+ let selected = selection.uri === uri ? selection.selected : null;
96
+ if (selection.uri !== uri || (selected !== null && !known(selected))) {
97
+ setSelection({ uri, selected: null });
98
+ selected = null;
99
+ }
100
+ const select = useCallback((next) => {
101
+ if (next === null || known(next))
102
+ setSelection({ uri, selected: next });
103
+ }, [uri, known]);
104
+ const state = useMemo(() => (raw && selected ? eventState(raw, selected) : (answer?.state ?? null)), [raw, selected, answer]);
105
+ const derived = useMemo(() => {
106
+ const byline = state?.versions.find((v) => v.showing) ?? null;
107
+ // A selected version shows its own values as the thing asked for. Its record is the platform's copy of
108
+ // the same thing, a `T` as much as the composition is (an invalid item's stays `unknown`).
109
+ const item = answer && selected && byline ? { ...answer.item, record: byline.record } : answer
110
+ ? answer.item
111
+ : answer;
112
+ return { item, byline, conflicts: conflictsOf(state), versions: state?.versions ?? NO_VERSIONS, pill: state ? versionPill(state) : null };
113
+ }, [state, answer, selected]);
114
+ const conflict = useCallback((field) => (state ? fieldConflict(state, field) : null), [state]);
115
+ return reshaped(result, { ...derived, state, selected, select, conflict });
116
+ }
@@ -0,0 +1,60 @@
1
+ import type { Clients } from '../connect.js';
2
+ import type { OutputSchema as GetVersionsOutput } from '../generated/types/pub/techne/draft/commons/getVersions.js';
3
+ import { type Include, type IncludeOf, type Item, type ItemFor, type RecordOfQuery, type RecordOfUri } from '../item.js';
4
+ import { type ComposePoster, type Param, type Query, type QueryReader } from '../query/index.js';
5
+ import { type EventState, type VersionEntry } from '../versions/index.js';
6
+ /** What `techne.query` takes beside the query document. */
7
+ export interface QueryOpts {
8
+ /** `valid` (the default) or `all` (adds pending and invalid items). */
9
+ include?: Include;
10
+ /** Also count what the query answers this caller (the page gains `count` and `capped`). */
11
+ count?: boolean;
12
+ /** The previous page's cursor. */
13
+ cursor?: string;
14
+ /** The page size; default the query's `limit`, else the platform's. */
15
+ limit?: number;
16
+ /** The query's `$param` values. */
17
+ params?: Readonly<Record<string, Param>>;
18
+ }
19
+ /** One page of a query: {@link ValidItem}s by default, any {@link Item} with `include` `'all'`. */
20
+ export interface Page<T = unknown, I extends Include = 'valid'> {
21
+ items: ItemFor<T, I>[];
22
+ /** Pass it back as `cursor` for the next page; absent on the last. */
23
+ cursor: string | undefined;
24
+ /** Asked with `count`: how many records the query answers this caller (before `include`). */
25
+ count: number | undefined;
26
+ /** Asked with `count`: counting stopped at the platform's cap. */
27
+ capped: boolean | undefined;
28
+ }
29
+ /** What `techne.get` takes. */
30
+ export interface GetOpts {
31
+ /** `valid` (the default: a record that is not valid answers `null`) or `all` (any verdict). */
32
+ include?: Include;
33
+ /** `mine`: the signed-in user's own version when they have one, else the curated record. */
34
+ prefer?: 'mine';
35
+ /** Exactly the record at the URI, never another copy. */
36
+ exact?: boolean;
37
+ }
38
+ /** A record as its versions. */
39
+ export interface Versions<T = unknown> {
40
+ /** The record answered: the curated record, or the record itself when nothing curates it. */
41
+ item: Item<T>;
42
+ /** Every version, ranked and grouped as the versions sheet lists them (`state.versions`). Empty for a record
43
+ * answered privately. */
44
+ versions: VersionEntry[];
45
+ /** Each field whose ranked versions disagree, and how many values they give (from `state.fields`). Empty
46
+ * for a record answered privately. */
47
+ conflicts: Record<string, number>;
48
+ /** The platform's `getVersions` answer, what `eventState` reads (`null` for a record answered privately). */
49
+ data: GetVersionsOutput | null;
50
+ /** `eventState(data)`: every version ranked and grouped (Sources / Verified / Others), each field's value,
51
+ * source and conflict count, the byline. `null` with `data`. */
52
+ state: EventState | null;
53
+ }
54
+ /** A {@link QueryReader} over the platform client. */
55
+ export declare const readerOf: (techne: Clients) => QueryReader;
56
+ /** A {@link ComposePoster} over the platform client: a procedure's JSON body. */
57
+ export declare const posterOf: (techne: Clients) => ComposePoster;
58
+ export declare function query<Q extends Query, O extends QueryOpts = {}>(techne: Clients, q: Q, opts?: O): Promise<Page<RecordOfQuery<Q>, IncludeOf<O>>>;
59
+ export declare function get<U extends string, O extends GetOpts = {}>(techne: Clients, uri: U, opts?: O): Promise<ItemFor<RecordOfUri<U>, IncludeOf<O>> | null>;
60
+ export declare function versions<U extends string>(techne: Clients, uri: U): Promise<Versions<RecordOfUri<U>> | null>;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The reads on the client (SDK1): `techne.query`, `techne.get` and `techne.versions`, each answering
3
+ * {@link Item}s, and their options forms (`{ queryKey, queryFn }`, for TanStack Query). Internal: an app
4
+ * calls them on what `connect` returns, which binds them to its session and the claims it holds.
5
+ *
6
+ * - `query(q, opts)`: one page of a query document (`pub.techne.draft.query.listRecords`). A list across
7
+ * authors answers curated records (the query's `curated`, on the platform). `count` is a read option
8
+ * (the document has no count field); the page's `count` is what the platform counted, before `include`.
9
+ * - `get(uri, opts)`: one record. By default the curated view: `commons.getVersions` resolves any copy to
10
+ * its curated record, and a type nobody curates answers the record itself. `prefer: 'mine'` answers the
11
+ * signed-in user's own version when they have one. `exact: true` answers exactly the record at the URI
12
+ * (`query.getRecords`, as written). `getVersions` is public only and answers not-found for a private
13
+ * record, so a not-found there reads `getRecords` instead. `null` when nothing is there to read.
14
+ * - `versions(uri)`: the composed item, every version as the versions sheet lists it (ranked and grouped
15
+ * by the Rust `eventState`, `techne-sdk/versions`), each field's conflict count, and the answer and
16
+ * state they come from (`{ item, versions, conflicts, data, state }`).
17
+ *
18
+ * `include: 'all'` adds the pending and invalid records the platform answered, never what it left out
19
+ * (blocked, hidden, unadmitted): see `../item`.
20
+ */
21
+ import { XRPCError } from '@atproto/xrpc';
22
+ import { authorOf, bylineOf, check, collectionOf, included, keeps } from '../item.js';
23
+ import { compose, getRecords, MAX_STEP_LIMIT, PROVENANCE_OF_QUERY } from '../query/index.js';
24
+ import { conflictsOf, eventState } from '../versions/index.js';
25
+ /** A {@link QueryReader} over the platform client. */
26
+ export const readerOf = (techne) => async (nsid, params) => (await techne.platform.call(nsid, params)).data;
27
+ /** A {@link ComposePoster} over the platform client: a procedure's JSON body. */
28
+ export const posterOf = (techne) => async (nsid, body) => (await techne.platform.call(nsid, {}, body, { encoding: 'application/json' })).data;
29
+ /** `r` as an item, with `byline` from its curated record's composition. */
30
+ function itemOf(techne, r, curated, composition) {
31
+ const { verdict, problems } = check({ uri: r.uri, collection: r.collection ?? collectionOf(r.uri), author: r.author ?? authorOf(r.uri), value: r.value, space: r.space, time: r.time, held: r.held }, techne.claims);
32
+ // The check is what makes the record a `T`: valid and pending records passed its lexicon check.
33
+ return { uri: r.uri, cid: r.cid, record: r.value, verdict, problems, curated, byline: curated ? bylineOf(composition) : null };
34
+ }
35
+ const fromQueryRecord = (techne, r, composition) => itemOf(techne, r, r.curated === true, composition);
36
+ export async function query(techne, q, opts = {}) {
37
+ // One composed call: the page, and the provenances of what it answered (a curated record's byline).
38
+ const c = compose();
39
+ const list = c.list('page', q, { params: opts.params, limit: opts.limit, cursor: opts.cursor, count: opts.count });
40
+ // Every provenance of the page's records, read past one page: a byline is never dropped for want of a
41
+ // cursor, and past MAX_STEP_LIMIT `whole` throws rather than answer a curated record with no byline.
42
+ const prov = c.list('prov', PROVENANCE_OF_QUERY, { params: { uris: list.uri }, limit: MAX_STEP_LIMIT, fields: ['subject', 'composition'] });
43
+ const answer = await c.run(posterOf(techne));
44
+ const page = answer.list(list);
45
+ // A platform before pub.10 ignores `count=true`: never read that as 0.
46
+ if (opts.count && typeof page.count !== 'number')
47
+ throw new Error('listRecords answered no count: the platform does not count (before pub.10)');
48
+ // Only a curated record's own provenance counts: public, same author, subject that record.
49
+ const provs = answer.whole(prov, 'query').filter((p) => p.source === 'public');
50
+ const composition = (r) => r.source === 'public' && r.curated
51
+ ? provs.find((p) => p.author === r.author && p.value.subject?.uri === r.uri)?.value?.composition
52
+ : undefined;
53
+ const items = page.records.map((r) => fromQueryRecord(techne, r, composition(r)));
54
+ return {
55
+ items: included(items, opts.include),
56
+ cursor: page.cursor,
57
+ count: opts.count ? page.count : undefined,
58
+ capped: opts.count ? page.capped === true : undefined,
59
+ };
60
+ }
61
+ /** `getVersions` of `uri`, or `null` when the platform answers not-found (a private record, or none). */
62
+ async function versionsOf(techne, uri) {
63
+ try {
64
+ return (await techne.platform.pub.techne.draft.commons.getVersions({ uri })).data;
65
+ }
66
+ catch (e) {
67
+ if (e instanceof XRPCError && (e.error === 'NotFound' || e.status === 404))
68
+ return null;
69
+ throw e;
70
+ }
71
+ }
72
+ /** The record at `uri` exactly, as written (`getRecords`), or `null`. */
73
+ async function exactly(techne, uri) {
74
+ const r = (await getRecords(readerOf(techne), [uri])).get(uri);
75
+ return r ? fromQueryRecord(techne, r) : null;
76
+ }
77
+ /** The record a `getVersions` answer answers, as an item. */
78
+ function answered(techne, data) {
79
+ return itemOf(techne, { uri: data.uri, cid: data.cid, value: data.record }, data.composition !== undefined, data.composition);
80
+ }
81
+ /** The item `get` answers before `include`. */
82
+ async function read(techne, uri, opts) {
83
+ if (opts.exact)
84
+ return exactly(techne, uri);
85
+ const data = await versionsOf(techne, uri);
86
+ if (!data)
87
+ return exactly(techne, uri);
88
+ if (opts.prefer === 'mine') {
89
+ const mine = data.versions.find((v) => v.did === techne.did);
90
+ if (mine)
91
+ return itemOf(techne, { uri: mine.uri, cid: mine.cid, value: mine.record, author: mine.did, time: mine.indexedAt }, false);
92
+ }
93
+ return answered(techne, data);
94
+ }
95
+ export async function get(techne, uri, opts = {}) {
96
+ const item = await read(techne, uri, opts);
97
+ return item && keeps(item, opts.include) ? item : null;
98
+ }
99
+ export async function versions(techne, uri) {
100
+ const data = await versionsOf(techne, uri);
101
+ if (!data) {
102
+ const item = await exactly(techne, uri);
103
+ return item ? { item, versions: [], conflicts: {}, data: null, state: null } : null;
104
+ }
105
+ const state = eventState(data);
106
+ return { item: answered(techne, data), versions: state.versions, conflicts: conflictsOf(state), data, state };
107
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * techne-sdk/connect's resend: a `FetchHandler` that sends a POST once more when it got no response.
3
+ *
4
+ * Each POST gets one `Idempotency-Key` (a v4 UUID), sent on the first try and on the resend, so the
5
+ * platform answers a resend of a write it already ran with that write's stored answer instead of running
6
+ * it twice. It resends only when the handler threw a `TypeError` before any `Response` (iOS reuses a
7
+ * pooled connection dropped while idle and resends no POST itself), at most once, and never after an
8
+ * abort. A status is an answer and is never resent; nor is a GET, a POST whose body is a stream
9
+ * (it cannot be sent twice), or any keyed POST where there is no `crypto.getRandomValues` to make a key.
10
+ *
11
+ * A read sent as a POST (a method in the platform's read namespace, {@link isReadMethod}: it takes its
12
+ * question as a body) gets no key: running a read twice is harmless, so it is resent the same way
13
+ * without one, and the platform stores no answer for it.
14
+ *
15
+ * Only for a handler that reaches the platform itself (`connectHosted`, `connectAnonymous`): through a
16
+ * user's PDS (`connect`) the header may be dropped, so a resend there could run the write twice.
17
+ */
18
+ import type { FetchHandler } from '@atproto/xrpc';
19
+ /** The header the platform keys a stored answer by. */
20
+ export declare const IDEMPOTENCY_KEY = "Idempotency-Key";
21
+ /** Whether `url` (`/xrpc/<nsid>…`, relative or absolute) calls a method in the read namespace. */
22
+ export declare function isReadMethod(url: string): boolean;
23
+ /** `handler`, with each POST sent once more when it got no response: a write under one key, a read
24
+ * ({@link isReadMethod}) as it is. */
25
+ export declare function resendingOnce(handler: FetchHandler): FetchHandler;
package/dist/resend.js ADDED
@@ -0,0 +1,52 @@
1
+ import { NSID } from './generated/nsid.js';
2
+ /** The header the platform keys a stored answer by. */
3
+ export const IDEMPOTENCY_KEY = 'Idempotency-Key';
4
+ /** The platform's read namespace, `pub.techne.draft.query.`: `composeRecords` and the methods beside
5
+ * it only read. The server holds the same rule (`xrpc::idempotency::is_read_method`). */
6
+ const READ_NAMESPACE = NSID.QUERY_COMPOSE_RECORDS.slice(0, NSID.QUERY_COMPOSE_RECORDS.lastIndexOf('.') + 1);
7
+ /** Whether `url` (`/xrpc/<nsid>…`, relative or absolute) calls a method in the read namespace. */
8
+ export function isReadMethod(url) {
9
+ const path = new URL(url, 'http://x').pathname;
10
+ return path.startsWith('/xrpc/') && path.slice('/xrpc/'.length).startsWith(READ_NAMESPACE);
11
+ }
12
+ /** `handler`, with each POST sent once more when it got no response: a write under one key, a read
13
+ * ({@link isReadMethod}) as it is. */
14
+ export function resendingOnce(handler) {
15
+ return async (url, init) => {
16
+ if (init.method?.toUpperCase() !== 'POST' || isStream(init.body))
17
+ return handler(url, init);
18
+ let sent = init;
19
+ if (!isReadMethod(url)) {
20
+ const key = uuidV4();
21
+ if (!key)
22
+ return handler(url, init);
23
+ const headers = new Headers(init.headers);
24
+ headers.set(IDEMPOTENCY_KEY, key);
25
+ sent = { ...init, headers };
26
+ }
27
+ try {
28
+ return await handler(url, sent);
29
+ }
30
+ catch (e) {
31
+ if (!(e instanceof TypeError) || init.signal?.aborted)
32
+ throw e;
33
+ return handler(url, sent);
34
+ }
35
+ };
36
+ }
37
+ /** A body that can be read only once (React Native may have no `ReadableStream` at all). */
38
+ function isStream(body) {
39
+ return typeof ReadableStream !== 'undefined' && body instanceof ReadableStream;
40
+ }
41
+ /** A random v4 UUID from `crypto.getRandomValues` (React Native's Hermes has no `randomUUID`; Beacon
42
+ * installs `getRandomValues` first thing), or `undefined` with no `getRandomValues`: then the POST goes
43
+ * once, unkeyed, since a resend without a key could run the write twice. */
44
+ function uuidV4() {
45
+ if (typeof globalThis.crypto?.getRandomValues !== 'function')
46
+ return undefined;
47
+ const b = globalThis.crypto.getRandomValues(new Uint8Array(16));
48
+ b[6] = (b[6] & 0x0f) | 0x40;
49
+ b[8] = (b[8] & 0x3f) | 0x80;
50
+ const hex = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
51
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
52
+ }
@@ -0,0 +1,8 @@
1
+ /** HTML5 named character references, by name without its `;` (`amp` -> `&`). */
2
+ export declare const NAMED: ReadonlyMap<string, string>;
3
+ /** The names also recognised as a prefix without their `;` (`&notit;` is `&not` + `it;`). */
4
+ export declare const LEGACY: readonly string[];
5
+ /** Numeric references the HTML5 parser replaces (`&#150;` is Windows-1252's en dash; `&#0;` U+FFFD). */
6
+ export declare const INVALID_CHARREFS: ReadonlyMap<number, string>;
7
+ /** Code points a numeric reference decodes to nothing (controls, noncharacters), as inclusive ranges. */
8
+ export declare const INVALID_CODEPOINTS: readonly (readonly [number, number])[];