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.
@@ -1,4 +1,4 @@
1
- import type { Techne } from '../connect.js';
1
+ import type { Clients } from '../connect.js';
2
2
  import type * as Defs from '../generated/types/pub/techne/draft/identity/defs.js';
3
3
  import type * as Create from '../generated/types/pub/techne/draft/identity/createLinkToken.js';
4
4
  import type * as Redeem from '../generated/types/pub/techne/draft/identity/redeemLinkToken.js';
@@ -23,6 +23,13 @@ export declare class OwnLinkError extends Error {
23
23
  cause?: unknown;
24
24
  });
25
25
  }
26
+ /** The user's PDS refused the call: the session's scopes do not name it (a Sign in with Techne session;
27
+ * see the module doc). `cause` is the PDS's answer. */
28
+ export declare class LinkScopeError extends Error {
29
+ constructor(options?: {
30
+ cause?: unknown;
31
+ });
32
+ }
26
33
  /** What a link is for: the app (a label of the caller's) and its target (a URI with a scheme). */
27
34
  export interface LinkFor {
28
35
  app: string;
@@ -31,7 +38,7 @@ export interface LinkFor {
31
38
  /** A new link: the token to put in the URL, and its view (`link.id` is its id). */
32
39
  export type NewLink = Create.OutputSchema;
33
40
  /** A new link for `app` and `target`: one-time unless `reusable`, live until `expiresAt` if given. */
34
- export declare function createLink(techne: Techne, input: LinkFor & {
41
+ export declare function createLink(techne: Clients, input: LinkFor & {
35
42
  reusable?: boolean;
36
43
  expiresAt?: Date | string;
37
44
  grant?: LinkGrant;
@@ -41,25 +48,25 @@ export declare function createLink(techne: Techne, input: LinkFor & {
41
48
  * `grant` it carries over the newest unrevoked grant of a reusable link for the same app and target (a
42
49
  * one-time link's grant is never carried); with neither, the new link has no grant.
43
50
  */
44
- export declare function resetLink(techne: Techne, input: LinkFor & {
51
+ export declare function resetLink(techne: Clients, input: LinkFor & {
45
52
  grant?: LinkGrant;
46
53
  }): Promise<Reset.OutputSchema>;
47
54
  /** Revoke one of the caller's links; `false` when they have no link with this id or it was already revoked. */
48
- export declare function revokeLink(techne: Techne, id: string): Promise<boolean>;
55
+ export declare function revokeLink(techne: Clients, id: string): Promise<boolean>;
49
56
  /** The caller's live links for `app` and `target`, in no promised order. */
50
- export declare function listLinks(techne: Techne, input: LinkFor): Promise<LinkTokenListed[]>;
57
+ export declare function listLinks(techne: Clients, input: LinkFor): Promise<LinkTokenListed[]>;
51
58
  /** Who redeemed one of the caller's links, and when (empty for a link that is not theirs). */
52
- export declare function linkRedemptions(techne: Techne, id: string): Promise<LinkRedemption[]>;
59
+ export declare function linkRedemptions(techne: Clients, id: string): Promise<LinkRedemption[]>;
53
60
  /**
54
61
  * Redeem `token` as the signed-in user. Throws {@link LinkNotUsableError} for a link that no longer
55
62
  * works and {@link OwnLinkError} for the caller's own; a repeat by the same account answers `repeat`.
56
63
  */
57
- export declare function redeemLink(techne: Techne, token: string): Promise<Redemption>;
64
+ export declare function redeemLink(techne: Clients, token: string): Promise<Redemption>;
58
65
  /** What a live token is for: the lexicon's answer with every field a live one carries. */
59
66
  export type LiveLink = Required<Pick<Check.OutputSchema, 'id' | 'app' | 'target' | 'owner' | 'reusable'>> & Pick<Check.OutputSchema, 'expiresAt'> & {
60
67
  live: true;
61
68
  };
62
69
  /** Whether `token` is live, and if so what it is for; a dead or unknown one says nothing more. */
63
- export declare function checkLink(techne: Techne, token: string): Promise<LiveLink | {
70
+ export declare function checkLink(techne: Clients, token: string): Promise<LiveLink | {
64
71
  live: false;
65
72
  }>;
@@ -21,6 +21,13 @@
21
21
  * Every call goes to the platform through the user's PDS (`techne.platform`, `atproto-proxy`), like
22
22
  * `put`; the platform relays it to the identity PDS. An account not on the identity PDS gets
23
23
  * `NotSupported`.
24
+ *
25
+ * Which session. The calls are `pub.techne.draft.identity.*` methods, and no published permission set
26
+ * names them (`authRead` and `authWrite` are the commons reads and writes), so a Sign in with Techne
27
+ * session (`connect` over the app's own OAuth session, asking for the default `scopes()`) is refused by
28
+ * its PDS for every one: they throw {@link LinkScopeError}. Links need a platform session
29
+ * (`connectHosted`), or an app that asks for those methods' `rpc:` scopes itself (with the platform's
30
+ * appview as their `aud`) beside the default ones.
24
31
  */
25
32
  import { XRPCError } from '@atproto/xrpc';
26
33
  /** The message every unusable link answers with (unknown, used, revoked or expired alike). */
@@ -39,12 +46,23 @@ export class OwnLinkError extends Error {
39
46
  this.name = 'OwnLinkError';
40
47
  }
41
48
  }
49
+ /** The user's PDS refused the call: the session's scopes do not name it (a Sign in with Techne session;
50
+ * see the module doc). `cause` is the PDS's answer. */
51
+ export class LinkScopeError extends Error {
52
+ constructor(options) {
53
+ super("techne-sdk/links: the session's scopes do not cover link tokens (no permission set names the identity methods): use a platform session (connectHosted), or ask for their rpc: scopes yourself", options);
54
+ this.name = 'LinkScopeError';
55
+ }
56
+ }
42
57
  function mapped(e) {
43
58
  if (e instanceof XRPCError) {
44
59
  if (e.error === 'LinkNotUsable')
45
60
  return new LinkNotUsableError({ cause: e });
46
61
  if (e.error === 'OwnLink')
47
62
  return new OwnLinkError({ cause: e });
63
+ // What a PDS answers for a call its OAuth session has no scope for (`@atproto/oauth-scopes` ScopeMissingError).
64
+ if (e.status === 403 && /^Missing required scope "rpc:/.test(e.message))
65
+ return new LinkScopeError({ cause: e });
48
66
  }
49
67
  return e;
50
68
  }
@@ -1,4 +1,4 @@
1
- import type { Techne } from '../connect.js';
1
+ import type { Clients } from '../connect.js';
2
2
  type Raw = {
3
3
  [k: string]: unknown;
4
4
  };
@@ -25,5 +25,5 @@ export declare function contactConflicts(stored: StoredContact[], writes: {
25
25
  record: object;
26
26
  }[]): ContactConflict[];
27
27
  /** Every contact the owner has, through the platform's private read (one page after another). */
28
- export declare function storedContacts(techne: Techne): Promise<StoredContact[]>;
28
+ export declare function storedContacts(techne: Clients): Promise<StoredContact[]>;
29
29
  export {};
@@ -3,9 +3,9 @@ import type * as CalendarEvent from '../generated/types/community/lexicon/calend
3
3
  import type * as EventConfig from '../generated/types/pub/techne/draft/event/config.js';
4
4
  import type * as EventDetail from '../generated/types/pub/techne/draft/event/detail.js';
5
5
  import type { OmitKey } from '../generated/util.js';
6
- import type { Techne } from '../connect.js';
7
6
  import { type Decision } from '../wasm/index.js';
8
- import { type Curation } from '../query/index.js';
7
+ import type { Curation } from '../query/index.js';
8
+ export { put, type PutOptions } from './put.js';
9
9
  export { contactConflicts, ContactConflictError, type ContactConflict, type StoredContact } from './contacts.js';
10
10
  export type { Records, AnyRecord, Decision, Curation };
11
11
  /** One record to put: the body (its `$type` is its collection), and its key or space if it has them. */
@@ -122,17 +122,14 @@ export declare class PutError extends Error {
122
122
  message: string;
123
123
  }[]);
124
124
  }
125
- /** The plan for `records` into `repo` (Rust, `techne_sdk::put::plan`). */
126
- export declare function plan(repo: string, records: PutRecord[], now?: Date): Write[];
125
+ /** The plan for `records` into `repo` (Rust, `techne_sdk::put::plan`) as of `now`: a `Date`, or unix
126
+ * seconds (the platform SDK's form); this machine's clock by default. */
127
+ export declare function plan(repo: string, records: PutRecord[], now?: Date | number): Write[];
127
128
  /** The plan for `records` and `deletes` into `repo` (Rust, `techne_sdk::put::plan_with_deletes`). */
128
- export declare function planWithDeletes(repo: string, records: PutRecord[], deletes: DeleteRecord[], now?: Date): {
129
+ export declare function planWithDeletes(repo: string, records: PutRecord[], deletes: DeleteRecord[], now?: Date | number): {
129
130
  writes: Write[];
130
131
  deletes: Delete[];
131
132
  };
132
- export declare function put(techne: Techne, records: PutRecord[], options?: {
133
- wait?: number;
134
- deletes?: DeleteRecord[];
135
- }): Promise<PutResult>;
136
133
  type EventFields = OmitKey<CalendarEvent.Record, '$type'>;
137
134
  type ConfigFields = OmitKey<EventConfig.Record, '$type' | 'event' | 'createdAt'>;
138
135
  type DetailFields = OmitKey<EventDetail.Record, '$type' | 'event' | 'createdAt'>;
package/dist/put/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
- * techne-sdk/put — the SDK's one write (techne P13.2): `put(techne, records)`.
2
+ * techne-sdk/put — the SDK's one write (techne P13.2): `put(techne, records)`, also the client's
3
+ * `techne.put(records)` on what `connect` returns.
3
4
  *
4
5
  * An app writes records, typed from the lexicons, and nothing refuses a write. `put`:
5
6
  *
@@ -40,7 +41,8 @@
40
41
  * private deletes. Send the same records again: the keys are deterministic,
41
42
  * a private record written again is a no-op, a public record already at its CID is not rewritten, and a
42
43
  * record already gone is not deleted again.
43
- * Until every record has landed, show the thing as pending.
44
+ * Until every record has landed, show the thing as pending. `put` does that once itself when a call got
45
+ * no answer at all (the connection was lost before any response): it runs again from the start.
44
46
  *
45
47
  * Before writing a `contact`, `put` asks whether the write would change who the contact is (its
46
48
  * number, its account; `./contacts`): the platform no longer refuses that, so the SDK does, and throws
@@ -60,17 +62,10 @@
60
62
  * Builders exist only for writes that compose several records ({@link eventRecords}); any other record
61
63
  * is put as it is.
62
64
  */
63
- import { XRPCError } from '@atproto/xrpc';
64
65
  import { NSID } from '../generated/nsid.js';
65
66
  import { call } from '../wasm/index.js';
66
- import { contactConflicts, ContactConflictError, storedContacts } from './contacts.js';
67
- import { getRecordsAnswer } from '../query/index.js';
67
+ export { put } from './put.js';
68
68
  export { contactConflicts, ContactConflictError } from './contacts.js';
69
- /** Why a private record with no space is not written (lucian 2026-11-09): the platform's private write
70
- * needs a space, as `permissioned.putRecords` refuses a write that names none. */
71
- function noSpace(did, collection) {
72
- return `names no space. ${collection} is written privately, so name the space it is for: a record only you read goes in your own space.personal (at://${did}/${NSID.SPACE_PERSONAL}/self). Public records are written with com.atproto.repo.putRecord.`;
73
- }
74
69
  /** A put whose private batch write refused some records: nothing public was written. */
75
70
  export class PutError extends Error {
76
71
  refused;
@@ -79,173 +74,20 @@ export class PutError extends Error {
79
74
  this.refused = refused;
80
75
  }
81
76
  }
82
- /** The plan for `records` into `repo` (Rust, `techne_sdk::put::plan`). */
77
+ /** The plan for `records` into `repo` (Rust, `techne_sdk::put::plan`) as of `now`: a `Date`, or unix
78
+ * seconds (the platform SDK's form); this machine's clock by default. */
83
79
  export function plan(repo, records, now = new Date()) {
84
80
  return call('put', { repo, records, now: unixSeconds(now) });
85
81
  }
86
82
  /** The clock the plan reads (an old name has a lexicon only while its rename is honoured); the
87
83
  * WebAssembly has none of its own. */
88
84
  function unixSeconds(now) {
89
- return Math.floor(now.getTime() / 1000);
85
+ return typeof now === 'number' ? Math.floor(now) : Math.floor(now.getTime() / 1000);
90
86
  }
91
87
  /** The plan for `records` and `deletes` into `repo` (Rust, `techne_sdk::put::plan_with_deletes`). */
92
88
  export function planWithDeletes(repo, records, deletes, now = new Date()) {
93
89
  return call('putPlan', { repo, records, deletes, now: unixSeconds(now) });
94
90
  }
95
- /** How often `wait` asks for the curated record. */
96
- const WAIT_POLL_MS = 250;
97
- export async function put(techne, records, options = {}) {
98
- const { did } = techne;
99
- const { writes, deletes } = options.deletes?.length ? planWithDeletes(did, records, options.deletes) : { writes: plan(did, records), deletes: [] };
100
- const privates = writes.filter((w) => w.private);
101
- const publics = writes.filter((w) => !w.private);
102
- const publicDeletes = deletes.filter((d) => !d.private);
103
- const unplaced = privates.filter((w) => !w.space);
104
- if (unplaced.length)
105
- throw new PutError(unplaced.map((w) => ({ uri: w.uri, error: 'InvalidRequest', message: noSpace(did, w.collection) })));
106
- const contacts = writes.filter((w) => w.collection === NSID.CONTACT);
107
- if (contacts.length) {
108
- const gone = new Set(deletes.map((d) => d.uri));
109
- const conflicts = contactConflicts((await storedContacts(techne)).filter((c) => !gone.has(c.uri)), contacts);
110
- if (conflicts.length)
111
- throw new ContactConflictError(conflicts);
112
- }
113
- if (privates.length) {
114
- const { data } = await techne.platform.pub.techne.draft.permissioned.putRecords({
115
- repo: did,
116
- // Every private write names its space (checked above).
117
- writes: privates.map(({ collection, rkey, record, space }) => ({ collection, rkey, record, space: space })),
118
- });
119
- const refused = data.results.flatMap((r, i) => r.$type === NSID.PERMISSIONED_PUT_RECORDS_WRITE_ERROR ? [{ uri: privates[i].uri, error: String(r.error), message: String(r.message) }] : []);
120
- if (refused.length)
121
- throw new PutError(refused);
122
- }
123
- const done = new Map();
124
- // The public deletes the PDS carried out in the applyWrites, hinted after (step 5).
125
- const pdsDeleted = [];
126
- if (publics.length || publicDeletes.length) {
127
- const current = await Promise.all(publics.map((w) => currentCid(techne, w)));
128
- const ops = publics.flatMap((w, i) => current[i] === w.cid
129
- ? []
130
- : [{ $type: current[i] ? 'com.atproto.repo.applyWrites#update' : 'com.atproto.repo.applyWrites#create', collection: w.collection, rkey: w.rkey, value: w.record }]);
131
- // A record already gone is not deleted again (a PDS refuses deleting what it does not hold).
132
- const held = await Promise.all(publicDeletes.map((d) => currentCid(techne, d)));
133
- for (const [i, d] of publicDeletes.entries()) {
134
- if (held[i])
135
- ops.push({ $type: 'com.atproto.repo.applyWrites#delete', collection: d.collection, rkey: d.rkey });
136
- }
137
- if (ops.length)
138
- await techne.pds.com.atproto.repo.applyWrites({ repo: did, writes: ops });
139
- for (const [i, d] of publicDeletes.entries()) {
140
- if (!held[i])
141
- continue;
142
- done.set(d.uri, true);
143
- pdsDeleted.push(d.uri);
144
- }
145
- }
146
- // Private deletes after the public leg: nothing public is left pointing at what they remove. A public
147
- // delete the PDS did not hold goes here too: a record of that collection kept in a space, named
148
- // without it. Deleting what is already gone answers without a `rev`, so a retry is a no-op.
149
- for (const d of deletes) {
150
- if (done.has(d.uri))
151
- continue;
152
- const { data } = await techne.platform.pub.techne.draft.permissioned.deleteRecord({ repo: did, collection: d.collection, rkey: d.rkey });
153
- done.set(d.uri, Boolean(data.rev));
154
- }
155
- const answers = new Map();
156
- // The public deletes are hinted beside the writes; their answer is not kept (a failed hint is ignored).
157
- await Promise.all([...publics.map(async (w) => answers.set(w, await hint(techne, w.uri))), ...pdsDeleted.map((uri) => hint(techne, uri))]);
158
- const curatable = publics.filter((w) => w.lexicon);
159
- const counted = (curatable.length ? curatable : publics).map((w) => answers.get(w));
160
- const status = counted.find((a) => a.decision === 'invalid') ?? { decision: 'pending' };
161
- const result = {
162
- writes: writes.map((w) => (answers.has(w) ? { ...w, status: answers.get(w) } : w)),
163
- deletes: deletes.map((d) => ({ ...d, deleted: done.get(d.uri) ?? false })),
164
- status,
165
- curation: [],
166
- };
167
- // Only a record with a lexicon the platform did not refuse can come back curated.
168
- const waitable = curatable.filter((w) => answers.get(w).decision !== 'invalid');
169
- if (options.wait && waitable.length) {
170
- const curated = await curatedOf(techne, waitable, Date.now() + options.wait);
171
- if (curated)
172
- result.curated = curated;
173
- }
174
- const { read, error } = await curationRead(techne, publics);
175
- result.curation = curationOfWrites(publics, answers, read);
176
- if (error !== undefined)
177
- result.curationError = error;
178
- return result;
179
- }
180
- /** The platform's curation answer for `publics`, by URI, through {@link getRecordsAnswer} (which keeps each
181
- * GET under the length a proxy takes), and why it failed when it did (then nothing is read). */
182
- async function curationRead(techne, publics) {
183
- if (!publics.length)
184
- return { read: new Map() };
185
- const reader = async (nsid, params) => (await techne.platform.call(nsid, params)).data;
186
- try {
187
- return { read: (await getRecordsAnswer(reader, publics.map((w) => w.uri), { curation: true })).curation };
188
- }
189
- catch (error) {
190
- return { read: new Map(), error };
191
- }
192
- }
193
- /** The curation status of each of `publics` (see {@link PutResult.curation}). */
194
- function curationOfWrites(publics, answers, read) {
195
- return publics.map((w) => {
196
- const known = read.get(w.uri);
197
- const hinted = answers.get(w);
198
- // A refusal the hint answered stands over a read that has not caught up with it.
199
- if (hinted?.decision === 'invalid' && (!known || known.status === 'pending'))
200
- return { uri: w.uri, status: 'notCurated', reason: hinted.reason };
201
- return known ?? { uri: w.uri, status: 'pending' };
202
- });
203
- }
204
- /** The CID the user's repo holds at `w`'s key, or `null` when it holds nothing there. */
205
- async function currentCid(techne, w) {
206
- try {
207
- const { data } = await techne.pds.com.atproto.repo.getRecord({ repo: techne.did, collection: w.collection, rkey: w.rkey });
208
- return data.cid ?? null;
209
- }
210
- catch (e) {
211
- if (e instanceof XRPCError && e.error === 'RecordNotFound')
212
- return null;
213
- throw e;
214
- }
215
- }
216
- /**
217
- * The hint for one public record. `indexRecord` answers `decide` for the version it indexed (P1.4:
218
- * `valid`, `pending` or `invalid` with a reason); a version the platform refused answers `invalid`.
219
- * Anything it did not refuse answers `pending` here: `put` is pending until its curated version lands
220
- * (`wait`). Any other failure (rate limit, an unreachable PDS) answers `pending`: the relay brings the
221
- * record anyway.
222
- */
223
- async function hint(techne, uri) {
224
- try {
225
- const { data } = await techne.platform.pub.techne.draft.sync.indexRecord({ uri });
226
- if (data.decision === 'invalid')
227
- return { decision: 'invalid', reason: data.reason ?? 'invalid' };
228
- return { decision: 'pending' };
229
- }
230
- catch {
231
- return { decision: 'pending' };
232
- }
233
- }
234
- /** The first curated record that names one of `sources`, at the CID just written, as its source. */
235
- async function curatedOf(techne, sources, deadline) {
236
- for (;;) {
237
- for (const source of sources) {
238
- const answer = await techne.platform.pub.techne.draft.commons.getVersions({ uri: source.uri }).then((r) => r.data, () => null);
239
- if (answer && answer.uri !== source.uri && answer.versions.some((v) => v.uri === source.uri && v.cid === source.cid)) {
240
- return { uri: answer.uri, cid: answer.cid, record: answer.record };
241
- }
242
- }
243
- const left = deadline - Date.now();
244
- if (left <= 0)
245
- return undefined;
246
- await new Promise((r) => setTimeout(r, Math.min(WAIT_POLL_MS, left)));
247
- }
248
- }
249
91
  /**
250
92
  * An event with its config, and its detail when it has gated fields, as the records to `put`
251
93
  * (repo = the host's DID). The config and the detail point at the event by URI and CID. The config is
@@ -0,0 +1,14 @@
1
+ import type { Clients } from '../connect.js';
2
+ import { type DeleteRecord, type PutRecord, type PutResult } from './index.js';
3
+ /** What `put` takes beside the records (see `./index`). */
4
+ export interface PutOptions {
5
+ wait?: number;
6
+ deletes?: DeleteRecord[];
7
+ }
8
+ /**
9
+ * `put(techne, records, options)`: the write (`./index` says what it does), on what `connect` returns
10
+ * (`techne.put` is this) or on any {@link Clients}. Runs once more from the start when a call got no
11
+ * response; it re-reads first, so nothing lands twice and nothing is deleted twice. Only the writes and
12
+ * deletes throw: the hints and the curation read already answer `pending`.
13
+ */
14
+ export declare function put(techne: Clients, records: PutRecord[], options?: PutOptions): Promise<PutResult>;
@@ -0,0 +1,206 @@
1
+ /**
2
+ * `put`: the write behind `techne-sdk/put`'s `put` and the client's `techne.put` (see `./index` for what
3
+ * it does). Internal: `./index` re-exports it.
4
+ */
5
+ import { ResponseType, XRPCError } from '@atproto/xrpc';
6
+ import { NSID } from '../generated/nsid.js';
7
+ import { getRecordsAnswer } from '../query/index.js';
8
+ import { contactConflicts, ContactConflictError, storedContacts } from './contacts.js';
9
+ import { plan, planWithDeletes, PutError } from './index.js';
10
+ /** How often `wait` asks for the curated record. */
11
+ const WAIT_POLL_MS = 250;
12
+ /**
13
+ * `put(techne, records, options)`: the write (`./index` says what it does), on what `connect` returns
14
+ * (`techne.put` is this) or on any {@link Clients}. Runs once more from the start when a call got no
15
+ * response; it re-reads first, so nothing lands twice and nothing is deleted twice. Only the writes and
16
+ * deletes throw: the hints and the curation read already answer `pending`.
17
+ */
18
+ export async function put(techne, records, options = {}) {
19
+ // The deletes the first run sent: one whose answer was lost may already have happened, so the second run
20
+ // answers it deleted when it finds the record gone.
21
+ const sent = { pds: new Set(), platform: new Set() };
22
+ try {
23
+ return await putOnce(techne, records, options, sent);
24
+ }
25
+ catch (e) {
26
+ if (!gotNoResponse(e))
27
+ throw e;
28
+ return putOnce(techne, records, options, { pds: new Set(), platform: new Set() }, sent);
29
+ }
30
+ }
31
+ /** Why a private record with no space is not written (lucian 2026-11-09): the platform's private write
32
+ * needs a space, as `permissioned.putRecords` refuses a write that names none. */
33
+ function noSpace(did, collection) {
34
+ return `names no space. ${collection} is written privately, so name the space it is for: a record only you read goes in your own space.personal (at://${did}/${NSID.SPACE_PERSONAL}/self). Public records are written with com.atproto.repo.putRecord.`;
35
+ }
36
+ /** `@atproto/xrpc` wraps what `fetch` threw as an `XRPCError` with no status and it as the cause: a
37
+ * `TypeError` from the fetch layer (no response, or a body cut off), never an abort. */
38
+ function gotNoResponse(e) {
39
+ return e instanceof XRPCError && e.status === ResponseType.Unknown && e.cause instanceof TypeError;
40
+ }
41
+ /** One run of `put`. It notes in `sent` each delete it may have carried out; `sentBefore` is the earlier
42
+ * run's, so a delete found already gone that the earlier run may have carried out answers deleted. A lost
43
+ * call may also never have arrived: the PDS is read again first, and a platform delete is always sent
44
+ * again, so only one that now finds nothing there answers from `sentBefore` (deleted, even in the rare
45
+ * case that the lost call never arrived and nothing was there to begin with). */
46
+ async function putOnce(techne, records, options, sent, sentBefore) {
47
+ const { did } = techne;
48
+ const { writes, deletes } = options.deletes?.length ? planWithDeletes(did, records, options.deletes) : { writes: plan(did, records), deletes: [] };
49
+ const privates = writes.filter((w) => w.private);
50
+ const publics = writes.filter((w) => !w.private);
51
+ const publicDeletes = deletes.filter((d) => !d.private);
52
+ const unplaced = privates.filter((w) => !w.space);
53
+ if (unplaced.length)
54
+ throw new PutError(unplaced.map((w) => ({ uri: w.uri, error: 'InvalidRequest', message: noSpace(did, w.collection) })));
55
+ const contacts = writes.filter((w) => w.collection === NSID.CONTACT);
56
+ if (contacts.length) {
57
+ const gone = new Set(deletes.map((d) => d.uri));
58
+ const conflicts = contactConflicts((await storedContacts(techne)).filter((c) => !gone.has(c.uri)), contacts);
59
+ if (conflicts.length)
60
+ throw new ContactConflictError(conflicts);
61
+ }
62
+ if (privates.length) {
63
+ const { data } = await techne.platform.pub.techne.draft.permissioned.putRecords({
64
+ repo: did,
65
+ // Every private write names its space (checked above).
66
+ writes: privates.map(({ collection, rkey, record, space }) => ({ collection, rkey, record, space: space })),
67
+ });
68
+ const refused = data.results.flatMap((r, i) => r.$type === NSID.PERMISSIONED_PUT_RECORDS_WRITE_ERROR ? [{ uri: privates[i].uri, error: String(r.error), message: String(r.message) }] : []);
69
+ if (refused.length)
70
+ throw new PutError(refused);
71
+ }
72
+ const done = new Map();
73
+ // The public deletes the PDS carried out in the applyWrites, hinted after (step 5).
74
+ const pdsDeleted = [];
75
+ if (publics.length || publicDeletes.length) {
76
+ const current = await Promise.all(publics.map((w) => currentCid(techne, w)));
77
+ const ops = publics.flatMap((w, i) => current[i] === w.cid
78
+ ? []
79
+ : [{ $type: current[i] ? 'com.atproto.repo.applyWrites#update' : 'com.atproto.repo.applyWrites#create', collection: w.collection, rkey: w.rkey, value: w.record }]);
80
+ // A record already gone is not deleted again (a PDS refuses deleting what it does not hold).
81
+ const held = await Promise.all(publicDeletes.map((d) => currentCid(techne, d)));
82
+ for (const [i, d] of publicDeletes.entries()) {
83
+ if (!held[i])
84
+ continue;
85
+ ops.push({ $type: 'com.atproto.repo.applyWrites#delete', collection: d.collection, rkey: d.rkey });
86
+ sent.pds.add(d.uri);
87
+ }
88
+ if (ops.length)
89
+ await techne.pds.com.atproto.repo.applyWrites({ repo: did, writes: ops });
90
+ for (const [i, d] of publicDeletes.entries()) {
91
+ // Gone now, and deleted by the earlier run whose applyWrites answer was lost: deleted, and hinted.
92
+ if (!held[i] && !sentBefore?.pds.has(d.uri))
93
+ continue;
94
+ done.set(d.uri, true);
95
+ pdsDeleted.push(d.uri);
96
+ }
97
+ }
98
+ // Private deletes after the public leg: nothing public is left pointing at what they remove. A public
99
+ // delete the PDS did not hold goes here too: a record of that collection kept in a space, named
100
+ // without it. Deleting what is already gone answers without a `rev`, so a retry is a no-op.
101
+ for (const d of deletes) {
102
+ if (done.has(d.uri))
103
+ continue;
104
+ const { data } = await techne.platform.pub.techne.draft.permissioned.deleteRecord({ repo: did, collection: d.collection, rkey: d.rkey }).catch((e) => {
105
+ sent.platform.add(d.uri);
106
+ throw e;
107
+ });
108
+ if (data.rev)
109
+ sent.platform.add(d.uri);
110
+ // No `rev`: nothing was there, unless the earlier run's delete took it.
111
+ done.set(d.uri, Boolean(data.rev) || Boolean(sentBefore?.platform.has(d.uri)));
112
+ }
113
+ const answers = new Map();
114
+ // The public deletes are hinted beside the writes; their answer is not kept (a failed hint is ignored).
115
+ await Promise.all([...publics.map(async (w) => answers.set(w, await hint(techne, w.uri))), ...pdsDeleted.map((uri) => hint(techne, uri))]);
116
+ const curatable = publics.filter((w) => w.lexicon);
117
+ const counted = (curatable.length ? curatable : publics).map((w) => answers.get(w));
118
+ const status = counted.find((a) => a.decision === 'invalid') ?? { decision: 'pending' };
119
+ const result = {
120
+ writes: writes.map((w) => (answers.has(w) ? { ...w, status: answers.get(w) } : w)),
121
+ deletes: deletes.map((d) => ({ ...d, deleted: done.get(d.uri) ?? false })),
122
+ status,
123
+ curation: [],
124
+ };
125
+ // Only a record with a lexicon the platform did not refuse can come back curated.
126
+ const waitable = curatable.filter((w) => answers.get(w).decision !== 'invalid');
127
+ if (options.wait && waitable.length) {
128
+ const curated = await curatedOf(techne, waitable, Date.now() + options.wait);
129
+ if (curated)
130
+ result.curated = curated;
131
+ }
132
+ const { read, error } = await curationRead(techne, publics);
133
+ result.curation = curationOfWrites(publics, answers, read);
134
+ if (error !== undefined)
135
+ result.curationError = error;
136
+ return result;
137
+ }
138
+ /** The platform's curation answer for `publics`, by URI, through {@link getRecordsAnswer} (which keeps each
139
+ * GET under the length a proxy takes), and why it failed when it did (then nothing is read). */
140
+ async function curationRead(techne, publics) {
141
+ if (!publics.length)
142
+ return { read: new Map() };
143
+ const reader = async (nsid, params) => (await techne.platform.call(nsid, params)).data;
144
+ try {
145
+ return { read: (await getRecordsAnswer(reader, publics.map((w) => w.uri), { curation: true })).curation };
146
+ }
147
+ catch (error) {
148
+ return { read: new Map(), error };
149
+ }
150
+ }
151
+ /** The curation status of each of `publics` (see {@link PutResult.curation}). */
152
+ function curationOfWrites(publics, answers, read) {
153
+ return publics.map((w) => {
154
+ const known = read.get(w.uri);
155
+ const hinted = answers.get(w);
156
+ // A refusal the hint answered stands over a read that has not caught up with it.
157
+ if (hinted?.decision === 'invalid' && (!known || known.status === 'pending'))
158
+ return { uri: w.uri, status: 'notCurated', reason: hinted.reason };
159
+ return known ?? { uri: w.uri, status: 'pending' };
160
+ });
161
+ }
162
+ /** The CID the user's repo holds at `w`'s key, or `null` when it holds nothing there. */
163
+ async function currentCid(techne, w) {
164
+ try {
165
+ const { data } = await techne.pds.com.atproto.repo.getRecord({ repo: techne.did, collection: w.collection, rkey: w.rkey });
166
+ return data.cid ?? null;
167
+ }
168
+ catch (e) {
169
+ if (e instanceof XRPCError && e.error === 'RecordNotFound')
170
+ return null;
171
+ throw e;
172
+ }
173
+ }
174
+ /**
175
+ * The hint for one public record. `indexRecord` answers `decide` for the version it indexed (P1.4:
176
+ * `valid`, `pending` or `invalid` with a reason); a version the platform refused answers `invalid`.
177
+ * Anything it did not refuse answers `pending` here: `put` is pending until its curated version lands
178
+ * (`wait`). Any other failure (rate limit, an unreachable PDS) answers `pending`: the relay brings the
179
+ * record anyway.
180
+ */
181
+ async function hint(techne, uri) {
182
+ try {
183
+ const { data } = await techne.platform.pub.techne.draft.sync.indexRecord({ uri });
184
+ if (data.decision === 'invalid')
185
+ return { decision: 'invalid', reason: data.reason ?? 'invalid' };
186
+ return { decision: 'pending' };
187
+ }
188
+ catch {
189
+ return { decision: 'pending' };
190
+ }
191
+ }
192
+ /** The first curated record that names one of `sources`, at the CID just written, as its source. */
193
+ async function curatedOf(techne, sources, deadline) {
194
+ for (;;) {
195
+ for (const source of sources) {
196
+ const answer = await techne.platform.pub.techne.draft.commons.getVersions({ uri: source.uri }).then((r) => r.data, () => null);
197
+ if (answer && answer.uri !== source.uri && answer.versions.some((v) => v.uri === source.uri && v.cid === source.cid)) {
198
+ return { uri: answer.uri, cid: answer.cid, record: answer.record };
199
+ }
200
+ }
201
+ const left = deadline - Date.now();
202
+ if (left <= 0)
203
+ return undefined;
204
+ await new Promise((r) => setTimeout(r, Math.min(WAIT_POLL_MS, left)));
205
+ }
206
+ }