@enbox/api 0.0.1

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.
Files changed (92) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +585 -0
  3. package/dist/browser.js +2226 -0
  4. package/dist/browser.js.map +7 -0
  5. package/dist/browser.mjs +2226 -0
  6. package/dist/browser.mjs.map +7 -0
  7. package/dist/cjs/did-api.js +126 -0
  8. package/dist/cjs/did-api.js.map +1 -0
  9. package/dist/cjs/dwn-api.js +804 -0
  10. package/dist/cjs/dwn-api.js.map +1 -0
  11. package/dist/cjs/grant-revocation.js +183 -0
  12. package/dist/cjs/grant-revocation.js.map +1 -0
  13. package/dist/cjs/index.js +63 -0
  14. package/dist/cjs/index.js.map +1 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/permission-grant.js +365 -0
  17. package/dist/cjs/permission-grant.js.map +1 -0
  18. package/dist/cjs/permission-request.js +272 -0
  19. package/dist/cjs/permission-request.js.map +1 -0
  20. package/dist/cjs/protocol.js +110 -0
  21. package/dist/cjs/protocol.js.map +1 -0
  22. package/dist/cjs/record.js +1127 -0
  23. package/dist/cjs/record.js.map +1 -0
  24. package/dist/cjs/subscription-util.js +86 -0
  25. package/dist/cjs/subscription-util.js.map +1 -0
  26. package/dist/cjs/utils.js +127 -0
  27. package/dist/cjs/utils.js.map +1 -0
  28. package/dist/cjs/vc-api.js +64 -0
  29. package/dist/cjs/vc-api.js.map +1 -0
  30. package/dist/cjs/web5.js +471 -0
  31. package/dist/cjs/web5.js.map +1 -0
  32. package/dist/esm/did-api.js +69 -0
  33. package/dist/esm/did-api.js.map +1 -0
  34. package/dist/esm/dwn-api.js +573 -0
  35. package/dist/esm/dwn-api.js.map +1 -0
  36. package/dist/esm/grant-revocation.js +109 -0
  37. package/dist/esm/grant-revocation.js.map +1 -0
  38. package/dist/esm/index.js +34 -0
  39. package/dist/esm/index.js.map +1 -0
  40. package/dist/esm/permission-grant.js +233 -0
  41. package/dist/esm/permission-grant.js.map +1 -0
  42. package/dist/esm/permission-request.js +166 -0
  43. package/dist/esm/permission-request.js.map +1 -0
  44. package/dist/esm/protocol.js +67 -0
  45. package/dist/esm/protocol.js.map +1 -0
  46. package/dist/esm/record.js +814 -0
  47. package/dist/esm/record.js.map +1 -0
  48. package/dist/esm/subscription-util.js +35 -0
  49. package/dist/esm/subscription-util.js.map +1 -0
  50. package/dist/esm/utils.js +120 -0
  51. package/dist/esm/utils.js.map +1 -0
  52. package/dist/esm/vc-api.js +30 -0
  53. package/dist/esm/vc-api.js.map +1 -0
  54. package/dist/esm/web5.js +281 -0
  55. package/dist/esm/web5.js.map +1 -0
  56. package/dist/types/did-api.d.ts +66 -0
  57. package/dist/types/did-api.d.ts.map +1 -0
  58. package/dist/types/dwn-api.d.ts +336 -0
  59. package/dist/types/dwn-api.d.ts.map +1 -0
  60. package/dist/types/grant-revocation.d.ts +66 -0
  61. package/dist/types/grant-revocation.d.ts.map +1 -0
  62. package/dist/types/index.d.ts +34 -0
  63. package/dist/types/index.d.ts.map +1 -0
  64. package/dist/types/permission-grant.d.ts +157 -0
  65. package/dist/types/permission-grant.d.ts.map +1 -0
  66. package/dist/types/permission-request.d.ts +108 -0
  67. package/dist/types/permission-request.d.ts.map +1 -0
  68. package/dist/types/protocol.d.ts +59 -0
  69. package/dist/types/protocol.d.ts.map +1 -0
  70. package/dist/types/record.d.ts +441 -0
  71. package/dist/types/record.d.ts.map +1 -0
  72. package/dist/types/subscription-util.d.ts +19 -0
  73. package/dist/types/subscription-util.d.ts.map +1 -0
  74. package/dist/types/utils.d.ts +85 -0
  75. package/dist/types/utils.d.ts.map +1 -0
  76. package/dist/types/vc-api.d.ts +24 -0
  77. package/dist/types/vc-api.d.ts.map +1 -0
  78. package/dist/types/web5.d.ts +219 -0
  79. package/dist/types/web5.d.ts.map +1 -0
  80. package/package.json +111 -0
  81. package/src/did-api.ts +90 -0
  82. package/src/dwn-api.ts +952 -0
  83. package/src/grant-revocation.ts +124 -0
  84. package/src/index.ts +35 -0
  85. package/src/permission-grant.ts +327 -0
  86. package/src/permission-request.ts +214 -0
  87. package/src/protocol.ts +87 -0
  88. package/src/record.ts +1125 -0
  89. package/src/subscription-util.ts +42 -0
  90. package/src/utils.ts +128 -0
  91. package/src/vc-api.ts +30 -0
  92. package/src/web5.ts +516 -0
@@ -0,0 +1,814 @@
1
+ /**
2
+ * NOTE: Added reference types here to avoid a `pnpm` bug during build.
3
+ * https://github.com/TBD54566975/web5-js/pull/507
4
+ */
5
+ /// <reference types="@enbox/dwn-sdk-js" />
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ var __rest = (this && this.__rest) || function (s, e) {
16
+ var t = {};
17
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
18
+ t[p] = s[p];
19
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
20
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
21
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
22
+ t[p[i]] = s[p[i]];
23
+ }
24
+ return t;
25
+ };
26
+ import { DwnInterface, getPaginationCursor, getRecordAuthor, isDwnMessage, AgentPermissionsApi, getRecordProtocolRole } from '@enbox/agent';
27
+ import { Convert, isEmptyObject, NodeStream, removeUndefinedProperties, Stream } from '@enbox/common';
28
+ import { dataToBlob, SendCache } from './utils.js';
29
+ /**
30
+ * The `Record` class encapsulates a single record's data and metadata, providing a more
31
+ * developer-friendly interface for working with Decentralized Web Node (DWN) records.
32
+ *
33
+ * Methods are provided to read, update, and manage the record's lifecycle, including writing to
34
+ * remote DWNs.
35
+ *
36
+ * Note: The `messageTimestamp` of the most recent RecordsWrite message is
37
+ * logically equivalent to the date/time at which a Record was most
38
+ * recently modified. Since this Record class implementation is
39
+ * intended to simplify the developer experience of working with
40
+ * logical records (and not individual DWN messages) the
41
+ * `messageTimestamp` is mapped to `dateModified`.
42
+ *
43
+ * @beta
44
+ */
45
+ export class Record {
46
+ /** The `RecordsWriteMessage` descriptor unless the record is in a deleted state */
47
+ get _recordsWriteDescriptor() {
48
+ if (isDwnMessage(DwnInterface.RecordsWrite, this.rawMessage)) {
49
+ return this._descriptor;
50
+ }
51
+ return undefined; // returns undefined if the descriptor does not represent a RecordsWrite message.
52
+ }
53
+ /** The `RecordsWrite` descriptor from the current record or the initial write if the record is in a delete state. */
54
+ get _immutableProperties() {
55
+ return this._recordsWriteDescriptor || this._initialWrite.descriptor;
56
+ }
57
+ // Getters for immutable Record properties.
58
+ /** Record's ID */
59
+ get id() { return this._recordId; }
60
+ /** Record's context ID. If the record is deleted, the context Id comes from the initial write */
61
+ get contextId() { return this.deleted ? this._initialWrite.contextId : this._contextId; }
62
+ /** Record's creation date */
63
+ get dateCreated() { return this._immutableProperties.dateCreated; }
64
+ /** Record's parent ID */
65
+ get parentId() { return this._immutableProperties.parentId; }
66
+ /** Record's protocol */
67
+ get protocol() { return this._immutableProperties.protocol; }
68
+ /** Record's protocol path */
69
+ get protocolPath() { return this._immutableProperties.protocolPath; }
70
+ /** Record's recipient */
71
+ get recipient() { return this._immutableProperties.recipient; }
72
+ /** Record's schema */
73
+ get schema() { return this._immutableProperties.schema; }
74
+ // Getters for mutable DWN RecordsWrite properties that may be undefined in a deleted state.
75
+ /** Record's data format */
76
+ get dataFormat() { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.dataFormat; }
77
+ /** Record's CID */
78
+ get dataCid() { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.dataCid; }
79
+ /** Record's data size */
80
+ get dataSize() { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.dataSize; }
81
+ /** Record's published date */
82
+ get datePublished() { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.datePublished; }
83
+ /** Record's published status (true/false) */
84
+ get published() { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.published; }
85
+ /** Tags of the record */
86
+ get tags() { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.tags; }
87
+ // Getters for for properties that depend on the current state of the Record.
88
+ /** DID that is the logical author of the Record. */
89
+ get author() { return this._author; }
90
+ /** DID that is the original creator of the Record. */
91
+ get creator() { return this._creator; }
92
+ /** Record's modified date */
93
+ get dateModified() { return this._descriptor.messageTimestamp; }
94
+ /** Record's encryption */
95
+ get encryption() { return this._encryption; }
96
+ /** Record's signatures attestation */
97
+ get authorization() { return this._authorization; }
98
+ /** Record's signatures attestation */
99
+ get attestation() { return this._attestation; }
100
+ /** Role under which the author is writing the record */
101
+ get protocolRole() { return this._protocolRole; }
102
+ /** Record's deleted state (true/false) */
103
+ get deleted() { return isDwnMessage(DwnInterface.RecordsDelete, this.rawMessage); }
104
+ /** Record's initial write if the record has been updated */
105
+ get initialWrite() { return this._initialWrite; }
106
+ /**
107
+ * Returns a copy of the raw `RecordsWriteMessage` that was used to create the current `Record` instance.
108
+ */
109
+ get rawMessage() {
110
+ const messageType = this._descriptor.interface + this._descriptor.method;
111
+ let message;
112
+ if (messageType === DwnInterface.RecordsWrite) {
113
+ message = JSON.parse(JSON.stringify({
114
+ contextId: this._contextId,
115
+ recordId: this._recordId,
116
+ descriptor: this._descriptor,
117
+ attestation: this._attestation,
118
+ authorization: this._authorization,
119
+ encryption: this._encryption,
120
+ }));
121
+ }
122
+ else {
123
+ message = JSON.parse(JSON.stringify({
124
+ descriptor: this._descriptor,
125
+ authorization: this._authorization,
126
+ }));
127
+ }
128
+ removeUndefinedProperties(message);
129
+ return message;
130
+ }
131
+ constructor(agent, options, permissionsApi) {
132
+ this._agent = agent;
133
+ // Store the author DID that originally signed the message as a convenience for developers, so
134
+ // that they don't have to decode the signer's DID from the JWS.
135
+ this._author = options.author;
136
+ // The creator is the author of the initial write, or the author of the record if there is no initial write.
137
+ this._creator = options.initialWrite ? getRecordAuthor(options.initialWrite) : options.author;
138
+ // Store the `connectedDid`, and optionally the `delegateDid` and `permissionsApi` in order to be able
139
+ // to perform operations on the record (update, delete, data) as a delegate of the connected DID.
140
+ this._connectedDid = options.connectedDid;
141
+ this._delegateDid = options.delegateDid;
142
+ this._permissionsApi = permissionsApi !== null && permissionsApi !== void 0 ? permissionsApi : new AgentPermissionsApi({ agent });
143
+ // If the record was queried or read from a remote DWN, the `remoteOrigin` DID will be
144
+ // defined. This value is used to send subsequent read requests to the same remote DWN in the
145
+ // event the record's data payload was too large to be returned in query results. or must be
146
+ // read again (e.g., if the data stream is consumed).
147
+ this._remoteOrigin = options.remoteOrigin;
148
+ // RecordsWriteMessage properties.
149
+ this._attestation = options.attestation;
150
+ this._authorization = options.authorization;
151
+ this._contextId = options.contextId;
152
+ this._descriptor = options.descriptor;
153
+ this._encryption = options.encryption;
154
+ this._initialWrite = options.initialWrite;
155
+ this._recordId = this.isRecordsDeleteDescriptor(options.descriptor) ? options.descriptor.recordId : options.recordId;
156
+ this._protocolRole = options.protocolRole;
157
+ if (options.encodedData) {
158
+ // If `encodedData` is set, then it is expected that:
159
+ // type is Blob if the Record object was instantiated by dwn.records.create()/write().
160
+ // type is Base64 URL encoded string if the Record object was instantiated by dwn.records.query().
161
+ // If it is a string, we need to Base64 URL decode to bytes and instantiate a Blob.
162
+ this._encodedData = (typeof options.encodedData === 'string') ?
163
+ new Blob([Convert.base64Url(options.encodedData).toUint8Array()], { type: this.dataFormat }) :
164
+ options.encodedData;
165
+ }
166
+ if (options.data) {
167
+ // If the record was created from a RecordsRead reply then it will have a `data` property.
168
+ // If the `data` property is a web ReadableStream, convert it to a Node.js Readable.
169
+ this._readableStream = Stream.isReadableStream(options.data) ?
170
+ NodeStream.fromWebReadable({ readableStream: options.data }) :
171
+ options.data;
172
+ }
173
+ }
174
+ /**
175
+ * Returns the data of the current record.
176
+ * If the record data is not available, it attempts to fetch the data from the DWN.
177
+ * @returns a data stream with convenience methods such as `blob()`, `json()`, `text()`, and `stream()`, similar to the fetch API response
178
+ * @throws `Error` if the record has already been deleted.
179
+ *
180
+ * @beta
181
+ */
182
+ get data() {
183
+ const self = this; // Capture the context of the `Record` instance.
184
+ const dataObj = {
185
+ /**
186
+ * Returns the data of the current record as a `Blob`.
187
+ *
188
+ * @returns A promise that resolves to a Blob containing the record's data.
189
+ * @throws If the record data is not available or cannot be converted to a `Blob`.
190
+ *
191
+ * @beta
192
+ */
193
+ blob() {
194
+ return __awaiter(this, void 0, void 0, function* () {
195
+ return new Blob([yield NodeStream.consumeToBytes({ readable: yield this.stream() })], { type: self.dataFormat });
196
+ });
197
+ },
198
+ /**
199
+ * Returns the data of the current record as a `Uint8Array`.
200
+ *
201
+ * @returns A Promise that resolves to a `Uint8Array` containing the record's data bytes.
202
+ * @throws If the record data is not available or cannot be converted to a byte array.
203
+ *
204
+ * @beta
205
+ */
206
+ bytes() {
207
+ return __awaiter(this, void 0, void 0, function* () {
208
+ return yield NodeStream.consumeToBytes({ readable: yield this.stream() });
209
+ });
210
+ },
211
+ /**
212
+ * Parses the data of the current record as JSON and returns it as a JavaScript object.
213
+ *
214
+ * @returns A Promise that resolves to a JavaScript object parsed from the record's JSON data.
215
+ * @throws If the record data is not available, not in JSON format, or cannot be parsed.
216
+ *
217
+ * @beta
218
+ */
219
+ json() {
220
+ return __awaiter(this, void 0, void 0, function* () {
221
+ return yield NodeStream.consumeToJson({ readable: yield this.stream() });
222
+ });
223
+ },
224
+ /**
225
+ * Returns the data of the current record as a `string`.
226
+ *
227
+ * @returns A promise that resolves to a `string` containing the record's text data.
228
+ * @throws If the record data is not available or cannot be converted to text.
229
+ *
230
+ * @beta
231
+ */
232
+ text() {
233
+ return __awaiter(this, void 0, void 0, function* () {
234
+ return yield NodeStream.consumeToText({ readable: yield this.stream() });
235
+ });
236
+ },
237
+ /**
238
+ * Provides a `Readable` stream containing the record's data.
239
+ *
240
+ * @returns A promise that resolves to a Node.js `Readable` stream of the record's data.
241
+ * @throws If the record data is not available in-memory and cannot be fetched.
242
+ *
243
+ * @beta
244
+ */
245
+ stream() {
246
+ return __awaiter(this, void 0, void 0, function* () {
247
+ if (self._encodedData) {
248
+ /** If `encodedData` is set, it indicates that the Record was instantiated by
249
+ * `dwn.records.create()`/`dwn.records.write()` or the record's data payload was small
250
+ * enough to be returned in `dwn.records.query()` results. In either case, the data is
251
+ * already available in-memory and can be returned as a Node.js `Readable` stream. */
252
+ self._readableStream = NodeStream.fromWebReadable({ readableStream: self._encodedData.stream() });
253
+ }
254
+ else if (!NodeStream.isReadable({ readable: self._readableStream })) {
255
+ /** If the data stream for this `Record` instance has already been partially or fully
256
+ * consumed, then the data must be fetched again from either: */
257
+ self._readableStream = self._remoteOrigin ?
258
+ // A. ...a remote DWN if the record was originally queried from a remote DWN.
259
+ yield self.readRecordData({ target: self._remoteOrigin, isRemote: true }) :
260
+ // B. ...a local DWN if the record was originally queried from the local DWN.
261
+ yield self.readRecordData({ target: self._connectedDid, isRemote: false });
262
+ }
263
+ if (!self._readableStream) {
264
+ throw new Error('Record data is not available.');
265
+ }
266
+ return self._readableStream;
267
+ });
268
+ },
269
+ /**
270
+ * Attaches callbacks for the resolution and/or rejection of the `Promise` returned by
271
+ * `stream()`.
272
+ *
273
+ * This method is a proxy to the `then` method of the `Promise` returned by `stream()`,
274
+ * allowing for a seamless integration with promise-based workflows.
275
+ * @param onFulfilled - A function to asynchronously execute when the `stream()` promise
276
+ * becomes fulfilled.
277
+ * @param onRejected - A function to asynchronously execute when the `stream()` promise
278
+ * becomes rejected.
279
+ * @returns A `Promise` for the completion of which ever callback is executed.
280
+ */
281
+ then(onFulfilled, onRejected) {
282
+ return this.stream().then(onFulfilled, onRejected);
283
+ },
284
+ /**
285
+ * Attaches a rejection handler callback to the `Promise` returned by the `stream()` method.
286
+ * This method is a shorthand for `.then(undefined, onRejected)`, specifically designed for handling
287
+ * rejection cases in the promise chain initiated by accessing the record's data. It ensures that
288
+ * errors during data retrieval or processing can be caught and handled appropriately.
289
+ *
290
+ * @param onRejected - A function to asynchronously execute when the `stream()` promise
291
+ * becomes rejected.
292
+ * @returns A `Promise` that resolves to the value of the callback if it is called, or to its
293
+ * original fulfillment value if the promise is instead fulfilled.
294
+ */
295
+ catch(onRejected) {
296
+ return this.stream().catch(onRejected);
297
+ }
298
+ };
299
+ return dataObj;
300
+ }
301
+ /**
302
+ * Stores the current record state as well as any initial write to the owner's DWN.
303
+ *
304
+ * @param importRecord - if true, the record will signed by the owner before storing it to the owner's DWN. Defaults to false.
305
+ * @returns the status of the store request
306
+ *
307
+ * @beta
308
+ */
309
+ store(importRecord = false) {
310
+ return __awaiter(this, void 0, void 0, function* () {
311
+ // if we are importing the record we sign it as the owner
312
+ return this.processRecord({ signAsOwner: importRecord, store: true });
313
+ });
314
+ }
315
+ /**
316
+ * Signs the current record state as well as any initial write and optionally stores it to the owner's DWN.
317
+ * This is useful when importing a record that was signed by someone else into your own DWN.
318
+ *
319
+ * @param store - if true, the record will be stored to the owner's DWN after signing. Defaults to true.
320
+ * @returns the status of the import request
321
+ *
322
+ * @beta
323
+ */
324
+ import(store = true) {
325
+ return __awaiter(this, void 0, void 0, function* () {
326
+ return this.processRecord({ store, signAsOwner: true });
327
+ });
328
+ }
329
+ /**
330
+ * Send the current record to a remote DWN by specifying their DID
331
+ * If no DID is specified, the target is assumed to be the owner (connectedDID).
332
+ *
333
+ * If an initial write is present and the Record class send cache has no awareness of it, the initial write is sent first
334
+ * (vs waiting for the regular DWN sync)
335
+ *
336
+ * @param target - the optional DID to send the record to, if none is set it is sent to the connectedDid
337
+ * @returns the status of the send record request
338
+ * @throws `Error` if the record has already been deleted.
339
+ *
340
+ * @beta
341
+ */
342
+ send(target) {
343
+ return __awaiter(this, void 0, void 0, function* () {
344
+ const initialWrite = this._initialWrite;
345
+ target !== null && target !== void 0 ? target : (target = this._connectedDid);
346
+ // Is there an initial write? Do we know if we've already sent it to this target?
347
+ if (initialWrite && !Record._sendCache.check(this._recordId, target)) {
348
+ // We do have an initial write, so prepare it for sending to the target.
349
+ const rawMessage = Object.assign({}, initialWrite);
350
+ removeUndefinedProperties(rawMessage);
351
+ // Send the initial write to the target.
352
+ yield this._agent.sendDwnRequest({
353
+ messageType: DwnInterface.RecordsWrite,
354
+ author: this._connectedDid,
355
+ target: target,
356
+ rawMessage
357
+ });
358
+ // Set the cache to maintain awareness that we don't need to send the initial write next time.
359
+ Record._sendCache.set(this._recordId, target);
360
+ }
361
+ let sendRequestOptions;
362
+ if (this.deleted) {
363
+ sendRequestOptions = {
364
+ messageType: DwnInterface.RecordsDelete,
365
+ author: this._connectedDid,
366
+ target: target,
367
+ rawMessage: Object.assign({}, this.rawMessage)
368
+ };
369
+ }
370
+ else {
371
+ sendRequestOptions = {
372
+ messageType: DwnInterface.RecordsWrite,
373
+ author: this._connectedDid,
374
+ target: target,
375
+ dataStream: yield this.data.blob(),
376
+ rawMessage: Object.assign({}, this.rawMessage)
377
+ };
378
+ }
379
+ // Send the current/latest state to the target.
380
+ const { reply } = yield this._agent.sendDwnRequest(sendRequestOptions);
381
+ return reply;
382
+ });
383
+ }
384
+ /**
385
+ * Returns a JSON representation of the Record instance.
386
+ * It's called by `JSON.stringify(...)` automatically.
387
+ */
388
+ toJSON() {
389
+ return {
390
+ attestation: this.attestation,
391
+ author: this.author,
392
+ authorization: this.authorization,
393
+ contextId: this.contextId,
394
+ dataCid: this.dataCid,
395
+ dataFormat: this.dataFormat,
396
+ dataSize: this.dataSize,
397
+ dateCreated: this.dateCreated,
398
+ messageTimestamp: this.dateModified,
399
+ datePublished: this.datePublished,
400
+ encryption: this.encryption,
401
+ parentId: this.parentId,
402
+ protocol: this.protocol,
403
+ protocolPath: this.protocolPath,
404
+ protocolRole: this.protocolRole,
405
+ published: this.published,
406
+ recipient: this.recipient,
407
+ recordId: this.id,
408
+ schema: this.schema,
409
+ tags: this.tags,
410
+ };
411
+ }
412
+ /**
413
+ * Convenience method to return the string representation of the Record instance.
414
+ * Called automatically in string concatenation, String() type conversion, and template literals.
415
+ */
416
+ toString() {
417
+ let str = `Record: {\n`;
418
+ str += ` ID: ${this.id}\n`;
419
+ str += this.contextId ? ` Context ID: ${this.contextId}\n` : '';
420
+ str += this.protocol ? ` Protocol: ${this.protocol}\n` : '';
421
+ str += this.schema ? ` Schema: ${this.schema}\n` : '';
422
+ // Only display data properties if the record has not been deleted.
423
+ if (!this.deleted) {
424
+ str += ` Data CID: ${this.dataCid}\n`;
425
+ str += ` Data Format: ${this.dataFormat}\n`;
426
+ str += ` Data Size: ${this.dataSize}\n`;
427
+ }
428
+ str += ` Deleted: ${this.deleted}\n`;
429
+ str += ` Created: ${this.dateCreated}\n`;
430
+ str += ` Modified: ${this.dateModified}\n`;
431
+ str += `}`;
432
+ return str;
433
+ }
434
+ /**
435
+ * Returns a pagination cursor for the current record given a sort order.
436
+ *
437
+ * @param sort the sort order to use for the pagination cursor.
438
+ * @returns A promise that resolves to a pagination cursor for the current record.
439
+ */
440
+ paginationCursor(sort) {
441
+ return __awaiter(this, void 0, void 0, function* () {
442
+ return isDwnMessage(DwnInterface.RecordsWrite, this.rawMessage) ? getPaginationCursor(this.rawMessage, sort) : undefined;
443
+ });
444
+ }
445
+ /**
446
+ * Update the current record on the DWN.
447
+ * @param params - Parameters to update the record.
448
+ * @returns the status of the update request
449
+ * @throws `Error` if the record has already been deleted.
450
+ *
451
+ * @beta
452
+ */
453
+ update(_a) {
454
+ var { dateModified, data, protocolRole, store = true } = _a, params = __rest(_a, ["dateModified", "data", "protocolRole", "store"]);
455
+ return __awaiter(this, void 0, void 0, function* () {
456
+ if (this.deleted) {
457
+ throw new Error('Record: Cannot revive a deleted record.');
458
+ }
459
+ // if there is a parentId, we remove it from the descriptor and set a parentContextId
460
+ const _b = this._recordsWriteDescriptor, { parentId } = _b, descriptor = __rest(_b, ["parentId"]);
461
+ const parentContextId = parentId ? this._contextId.split('/').slice(0, -1).join('/') : undefined;
462
+ // Begin assembling the update message.
463
+ let updateMessage = Object.assign(Object.assign(Object.assign({}, descriptor), params), { parentContextId, protocolRole: protocolRole !== null && protocolRole !== void 0 ? protocolRole : this._protocolRole, messageTimestamp: dateModified, recordId: this._recordId });
464
+ // NOTE: The original Record's tags are copied to the update message, so that the tags are not lost.
465
+ // However if a user passes new tags in the `RecordUpdateParams` object, they will overwrite the original tags.
466
+ // If the updated tag object is empty or set to null, we remove the tags property to avoid schema validation errors in the DWN SDK.
467
+ if (isEmptyObject(updateMessage.tags) || updateMessage.tags === null) {
468
+ delete updateMessage.tags;
469
+ }
470
+ let dataBlob;
471
+ if (data !== undefined) {
472
+ // If `data` is being updated then `dataCid` and `dataSize` must be undefined and the `data`
473
+ // value must be converted to a Blob and later passed as a top-level property to
474
+ // `agent.processDwnRequest()`.
475
+ delete updateMessage.dataCid;
476
+ delete updateMessage.dataSize;
477
+ ({ dataBlob } = dataToBlob(data, updateMessage.dataFormat));
478
+ }
479
+ // Throw an error if an attempt is made to modify immutable properties.
480
+ // Note: `data` and `dateModified` have already been handled.
481
+ const mutableDescriptorProperties = new Set(['data', 'dataCid', 'dataFormat', 'dataSize', 'datePublished', 'messageTimestamp', 'published', 'tags']);
482
+ Record.verifyPermittedMutation(Object.keys(params), mutableDescriptorProperties);
483
+ // If `published` is set to false, ensure that `datePublished` is undefined. Otherwise, DWN SDK's schema validation
484
+ // will throw an error if `published` is false but `datePublished` is set.
485
+ if (params.published === false && updateMessage.datePublished !== undefined) {
486
+ delete updateMessage.datePublished;
487
+ }
488
+ const requestOptions = {
489
+ author: this._connectedDid,
490
+ dataStream: dataBlob,
491
+ messageParams: Object.assign({}, updateMessage),
492
+ messageType: DwnInterface.RecordsWrite,
493
+ target: this._connectedDid,
494
+ store
495
+ };
496
+ if (this._delegateDid) {
497
+ const { message: delegatedGrant } = yield this._permissionsApi.getPermissionForRequest({
498
+ connectedDid: this._connectedDid,
499
+ delegateDid: this._delegateDid,
500
+ protocol: this.protocol,
501
+ delegate: true,
502
+ cached: true,
503
+ messageType: requestOptions.messageType
504
+ });
505
+ requestOptions.messageParams.delegatedGrant = delegatedGrant;
506
+ requestOptions.granteeDid = this._delegateDid;
507
+ }
508
+ const agentResponse = yield this._agent.processDwnRequest(requestOptions);
509
+ const { message, reply: { status } } = agentResponse;
510
+ const responseMessage = message;
511
+ if (200 <= status.code && status.code <= 299) {
512
+ // copy the original raw message to the initial write before we update the values.
513
+ if (!this._initialWrite) {
514
+ // If there is no initial write, we need to create one from the current record state.
515
+ // We checked in the beginning of the function that the rawMessage is a RecordsWrite message.
516
+ this._initialWrite = Object.assign({}, this.rawMessage);
517
+ }
518
+ // Only update the local Record instance mutable properties if the record was successfully (over)written.
519
+ this._authorization = responseMessage.authorization;
520
+ this._protocolRole = updateMessage.protocolRole;
521
+ mutableDescriptorProperties.forEach(property => {
522
+ this._descriptor[property] = responseMessage.descriptor[property];
523
+ });
524
+ // Cache data.
525
+ if (data !== undefined) {
526
+ this._encodedData = dataBlob;
527
+ }
528
+ }
529
+ return { status };
530
+ });
531
+ }
532
+ /**
533
+ * Delete the current record on the DWN.
534
+ * @param params - Parameters to delete the record.
535
+ * @returns the status of the delete request
536
+ */
537
+ delete(deleteParams) {
538
+ var _a;
539
+ return __awaiter(this, void 0, void 0, function* () {
540
+ const { store = true, signAsOwner, dateModified, prune = false } = deleteParams || {};
541
+ const signAsOwnerValue = signAsOwner && this._delegateDid === undefined;
542
+ const signAsOwnerDelegate = signAsOwner && this._delegateDid !== undefined;
543
+ if (this.deleted && !this._initialWrite) {
544
+ throw new Error('Record: Record is in an invalid state, initial write is missing.');
545
+ }
546
+ if (!this._initialWrite) {
547
+ // If there is no initial write, we need to create one from the current record state.
548
+ // We checked in the beginning of the function that the initialWrite is not set if the rawMessage is a RecordsDelete message.
549
+ // So we can safely assume that the rawMessage is a RecordsWrite message.
550
+ this._initialWrite = Object.assign({}, this.rawMessage);
551
+ }
552
+ yield this.processInitialWriteIfNeeded({ store, signAsOwner });
553
+ // prepare delete options
554
+ let deleteOptions = {
555
+ messageType: DwnInterface.RecordsDelete,
556
+ author: this._connectedDid,
557
+ target: this._connectedDid,
558
+ signAsOwner: signAsOwnerValue,
559
+ signAsOwnerDelegate,
560
+ store
561
+ };
562
+ // Check to see if the provided protocolRole within the deleteParams is different from the current protocolRole.
563
+ const differentRole = (deleteParams === null || deleteParams === void 0 ? void 0 : deleteParams.protocolRole) ? getRecordProtocolRole(this.rawMessage) !== deleteParams.protocolRole : false;
564
+ // If the record is already in a deleted state but the protocolRole is different, we need to construct a delete message with the new protocolRole
565
+ // otherwise we can just use the existing delete message.
566
+ if (this.deleted && !differentRole) {
567
+ deleteOptions.rawMessage = this.rawMessage;
568
+ }
569
+ else {
570
+ // otherwise we construct a delete message given the `RecordDeleteParams`
571
+ deleteOptions.messageParams = {
572
+ prune: prune,
573
+ recordId: this._recordId,
574
+ messageTimestamp: dateModified,
575
+ protocolRole: (_a = deleteParams === null || deleteParams === void 0 ? void 0 : deleteParams.protocolRole) !== null && _a !== void 0 ? _a : this._protocolRole // if no protocolRole is provided, use the current protocolRole
576
+ };
577
+ }
578
+ if (this._delegateDid) {
579
+ const { message: delegatedGrant } = yield this._permissionsApi.getPermissionForRequest({
580
+ connectedDid: this._connectedDid,
581
+ delegateDid: this._delegateDid,
582
+ protocol: this.protocol,
583
+ delegate: true,
584
+ cached: true,
585
+ messageType: deleteOptions.messageType
586
+ });
587
+ deleteOptions.messageParams = Object.assign(Object.assign({}, deleteOptions.messageParams), { delegatedGrant });
588
+ deleteOptions.granteeDid = this._delegateDid;
589
+ }
590
+ const agentResponse = yield this._agent.processDwnRequest(deleteOptions);
591
+ const { message, reply: { status } } = agentResponse;
592
+ if (status.code !== 202) {
593
+ // If the delete was not successful, return the status.
594
+ return { status };
595
+ }
596
+ // If the delete was successful, update the Record author to the author of the delete message.
597
+ this._author = getRecordAuthor(message);
598
+ this._descriptor = message.descriptor;
599
+ this._authorization = message.authorization;
600
+ // clear out properties that are not relevant for a deleted record
601
+ this._encodedData = undefined;
602
+ this._encryption = undefined;
603
+ this._attestation = undefined;
604
+ this._contextId = undefined;
605
+ return { status };
606
+ });
607
+ }
608
+ /**
609
+ * Process the initial write, if it hasn't already been processed, with the options set for storing and/or signing as the owner.
610
+ */
611
+ processInitialWriteIfNeeded({ store, signAsOwner }) {
612
+ return __awaiter(this, void 0, void 0, function* () {
613
+ if (this.initialWrite && ((signAsOwner && !this._initialWriteSigned) || (store && !this._initialWriteStored))) {
614
+ const signAsOwnerValue = signAsOwner && this._delegateDid === undefined;
615
+ const signAsOwnerDelegate = signAsOwner && this._delegateDid !== undefined;
616
+ const initialWriteRequest = {
617
+ messageType: DwnInterface.RecordsWrite,
618
+ rawMessage: this.initialWrite,
619
+ author: this._connectedDid,
620
+ target: this._connectedDid,
621
+ signAsOwner: signAsOwnerValue,
622
+ signAsOwnerDelegate,
623
+ store,
624
+ };
625
+ if (this._delegateDid) {
626
+ const { message: delegatedGrant } = yield this._permissionsApi.getPermissionForRequest({
627
+ connectedDid: this._connectedDid,
628
+ delegateDid: this._delegateDid,
629
+ protocol: this.protocol,
630
+ delegate: true,
631
+ cached: true,
632
+ messageType: initialWriteRequest.messageType
633
+ });
634
+ initialWriteRequest.messageParams = Object.assign(Object.assign({}, initialWriteRequest.messageParams), { delegatedGrant });
635
+ initialWriteRequest.granteeDid = this._delegateDid;
636
+ }
637
+ // Process the prepared initial write, with the options set for storing and/or signing as the owner.
638
+ const agentResponse = yield this._agent.processDwnRequest(initialWriteRequest);
639
+ const { message, reply: { status } } = agentResponse;
640
+ const responseMessage = message;
641
+ if (200 <= status.code && status.code <= 299) {
642
+ if (store)
643
+ this._initialWriteStored = true;
644
+ if (signAsOwner) {
645
+ this._initialWriteSigned = true;
646
+ this.initialWrite.authorization = responseMessage.authorization;
647
+ }
648
+ }
649
+ }
650
+ });
651
+ }
652
+ /**
653
+ * Handles the various conditions around there being an initial write, whether to store initial/current state,
654
+ * and whether to add an owner signature to the initial write to enable storage when protocol rules require it.
655
+ */
656
+ processRecord({ store, signAsOwner }) {
657
+ return __awaiter(this, void 0, void 0, function* () {
658
+ const signAsOwnerValue = signAsOwner && this._delegateDid === undefined;
659
+ const signAsOwnerDelegate = signAsOwner && this._delegateDid !== undefined;
660
+ yield this.processInitialWriteIfNeeded({ store, signAsOwner });
661
+ let requestOptions;
662
+ // Now that we've processed a potential initial write, we can process the current record state.
663
+ // If the record has been deleted, we need to send a delete request. Otherwise, we send a write request.
664
+ if (this.deleted) {
665
+ requestOptions = {
666
+ messageType: DwnInterface.RecordsDelete,
667
+ rawMessage: this.rawMessage,
668
+ author: this._connectedDid,
669
+ target: this._connectedDid,
670
+ signAsOwner: signAsOwnerValue,
671
+ signAsOwnerDelegate,
672
+ store,
673
+ };
674
+ }
675
+ else {
676
+ requestOptions = {
677
+ messageType: DwnInterface.RecordsWrite,
678
+ rawMessage: this.rawMessage,
679
+ author: this._connectedDid,
680
+ target: this._connectedDid,
681
+ dataStream: yield this.data.blob(),
682
+ signAsOwner: signAsOwnerValue,
683
+ signAsOwnerDelegate,
684
+ store,
685
+ };
686
+ }
687
+ if (this._delegateDid) {
688
+ const { message: delegatedGrant } = yield this._permissionsApi.getPermissionForRequest({
689
+ connectedDid: this._connectedDid,
690
+ delegateDid: this._delegateDid,
691
+ protocol: this.protocol,
692
+ delegate: true,
693
+ cached: true,
694
+ messageType: requestOptions.messageType
695
+ });
696
+ requestOptions.messageParams = Object.assign(Object.assign({}, requestOptions.messageParams), { delegatedGrant });
697
+ requestOptions.granteeDid = this._delegateDid;
698
+ }
699
+ const agentResponse = yield this._agent.processDwnRequest(requestOptions);
700
+ const { message, reply: { status } } = agentResponse;
701
+ const responseMessage = message;
702
+ if (200 <= status.code && status.code <= 299) {
703
+ // If we are signing as the owner, make sure to update the current record state's authorization, because now it will have the owner's signature on it.
704
+ if (signAsOwner)
705
+ this._authorization = responseMessage.authorization;
706
+ }
707
+ return { status };
708
+ });
709
+ }
710
+ /**
711
+ * Fetches the record's data from the specified DWN.
712
+ *
713
+ * This private method is called when the record data is not available in-memory
714
+ * and needs to be fetched from either a local or a remote DWN.
715
+ * It makes a read request to the specified DWN and processes the response to provide
716
+ * a Node.js `Readable` stream of the record's data.
717
+ *
718
+ * @param params - Parameters for fetching the record's data.
719
+ * @param params.target - The DID of the DWN to fetch the data from.
720
+ * @param params.isRemote - Indicates whether the target DWN is a remote node.
721
+ * @returns A Promise that resolves to a Node.js `Readable` stream of the record's data.
722
+ * @throws If there is an error while fetching or processing the data from the DWN.
723
+ *
724
+ * @beta
725
+ */
726
+ readRecordData({ target, isRemote }) {
727
+ return __awaiter(this, void 0, void 0, function* () {
728
+ const readRequest = {
729
+ author: this._connectedDid,
730
+ messageParams: { filter: { recordId: this.id }, protocolRole: this._protocolRole },
731
+ messageType: DwnInterface.RecordsRead,
732
+ target,
733
+ };
734
+ if (this._delegateDid) {
735
+ // When reading the data as a delegate, if we don't find a grant we will attempt to read it with the delegate DID as the author.
736
+ // This allows users to read publicly available data without needing explicit grants.
737
+ //
738
+ // NOTE: When a read-only Record class is implemented, callers would have that returned instead when they don't have an explicit permission.
739
+ // This should fail if a permission is not found, although it should not happen in practice.
740
+ // TODO: https://github.com/TBD54566975/web5-js/issues/898
741
+ try {
742
+ const { message: delegatedGrant } = yield this._permissionsApi.getPermissionForRequest({
743
+ connectedDid: this._connectedDid,
744
+ delegateDid: this._delegateDid,
745
+ protocol: this.protocol,
746
+ delegate: true,
747
+ cached: true,
748
+ messageType: readRequest.messageType
749
+ });
750
+ readRequest.messageParams = Object.assign(Object.assign({}, readRequest.messageParams), { delegatedGrant });
751
+ readRequest.granteeDid = this._delegateDid;
752
+ }
753
+ catch (error) {
754
+ // If there is an error fetching the grant, we will attempt to read the data as the delegate.
755
+ readRequest.author = this._delegateDid;
756
+ }
757
+ }
758
+ const agentResponsePromise = isRemote ?
759
+ this._agent.sendDwnRequest(readRequest) :
760
+ this._agent.processDwnRequest(readRequest);
761
+ try {
762
+ const { reply: { status, entry } } = yield agentResponsePromise;
763
+ if (status.code !== 200) {
764
+ throw new Error(`${status.code}: ${status.detail}`);
765
+ }
766
+ const dataStream = entry.data;
767
+ // If the data stream is a web ReadableStream, convert it to a Node.js Readable.
768
+ const nodeReadable = Stream.isReadableStream(dataStream) ?
769
+ NodeStream.fromWebReadable({ readableStream: dataStream }) :
770
+ dataStream;
771
+ return nodeReadable;
772
+ }
773
+ catch (error) {
774
+ throw new Error(`Error encountered while attempting to read data: ${error.message}`);
775
+ }
776
+ });
777
+ }
778
+ /**
779
+ * Verifies if the properties to be mutated are mutable.
780
+ *
781
+ * This private method is used to ensure that only mutable properties of the `Record` instance
782
+ * are being changed. It checks whether the properties specified for mutation are among the
783
+ * set of properties that are allowed to be modified. If any of the properties to be mutated
784
+ * are not in the set of mutable properties, the method throws an error.
785
+ *
786
+ * @param propertiesToMutate - An iterable of property names that are intended to be mutated.
787
+ * @param mutableDescriptorProperties - A set of property names that are allowed to be mutated.
788
+ *
789
+ * @throws If any of the properties in `propertiesToMutate` are not in `mutableDescriptorProperties`.
790
+ *
791
+ * @beta
792
+ */
793
+ static verifyPermittedMutation(propertiesToMutate, mutableDescriptorProperties) {
794
+ for (const property of propertiesToMutate) {
795
+ if (!mutableDescriptorProperties.has(property)) {
796
+ throw new Error(`${property} is an immutable property. Its value cannot be changed.`);
797
+ }
798
+ }
799
+ }
800
+ /**
801
+ * Checks if the descriptor is a RecordsDelete descriptor.
802
+ *
803
+ * @param descriptor a RecordsWrite or RecordsDelete descriptor
804
+ */
805
+ isRecordsDeleteDescriptor(descriptor) {
806
+ return descriptor.interface + descriptor.method === DwnInterface.RecordsDelete;
807
+ }
808
+ }
809
+ /**
810
+ * Cache to minimize the amount of redundant two-phase commits we do in store() and send()
811
+ * Retains awareness of the last 100 records stored/sent for up to 100 target DIDs each.
812
+ */
813
+ Record._sendCache = SendCache;
814
+ //# sourceMappingURL=record.js.map