@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,1127 @@
1
+ "use strict";
2
+ /**
3
+ * NOTE: Added reference types here to avoid a `pnpm` bug during build.
4
+ * https://github.com/TBD54566975/web5-js/pull/507
5
+ */
6
+ /// <reference types="@enbox/dwn-sdk-js" />
7
+ var __assign = (this && this.__assign) || function () {
8
+ __assign = Object.assign || function(t) {
9
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
10
+ s = arguments[i];
11
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
12
+ t[p] = s[p];
13
+ }
14
+ return t;
15
+ };
16
+ return __assign.apply(this, arguments);
17
+ };
18
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
+ return new (P || (P = Promise))(function (resolve, reject) {
21
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
24
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
25
+ });
26
+ };
27
+ var __generator = (this && this.__generator) || function (thisArg, body) {
28
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
29
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
30
+ function verb(n) { return function (v) { return step([n, v]); }; }
31
+ function step(op) {
32
+ if (f) throw new TypeError("Generator is already executing.");
33
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
34
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
35
+ if (y = 0, t) op = [op[0] & 2, t.value];
36
+ switch (op[0]) {
37
+ case 0: case 1: t = op; break;
38
+ case 4: _.label++; return { value: op[1], done: false };
39
+ case 5: _.label++; y = op[1]; op = [0]; continue;
40
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
41
+ default:
42
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
43
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
44
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
45
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
46
+ if (t[2]) _.ops.pop();
47
+ _.trys.pop(); continue;
48
+ }
49
+ op = body.call(thisArg, _);
50
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
51
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
52
+ }
53
+ };
54
+ var __rest = (this && this.__rest) || function (s, e) {
55
+ var t = {};
56
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
57
+ t[p] = s[p];
58
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
59
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
60
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
61
+ t[p[i]] = s[p[i]];
62
+ }
63
+ return t;
64
+ };
65
+ var __values = (this && this.__values) || function(o) {
66
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
67
+ if (m) return m.call(o);
68
+ if (o && typeof o.length === "number") return {
69
+ next: function () {
70
+ if (o && i >= o.length) o = void 0;
71
+ return { value: o && o[i++], done: !o };
72
+ }
73
+ };
74
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
75
+ };
76
+ Object.defineProperty(exports, "__esModule", { value: true });
77
+ exports.Record = void 0;
78
+ var agent_1 = require("@enbox/agent");
79
+ var common_1 = require("@enbox/common");
80
+ var utils_js_1 = require("./utils.js");
81
+ /**
82
+ * The `Record` class encapsulates a single record's data and metadata, providing a more
83
+ * developer-friendly interface for working with Decentralized Web Node (DWN) records.
84
+ *
85
+ * Methods are provided to read, update, and manage the record's lifecycle, including writing to
86
+ * remote DWNs.
87
+ *
88
+ * Note: The `messageTimestamp` of the most recent RecordsWrite message is
89
+ * logically equivalent to the date/time at which a Record was most
90
+ * recently modified. Since this Record class implementation is
91
+ * intended to simplify the developer experience of working with
92
+ * logical records (and not individual DWN messages) the
93
+ * `messageTimestamp` is mapped to `dateModified`.
94
+ *
95
+ * @beta
96
+ */
97
+ var Record = exports.Record = /** @class */ (function () {
98
+ function Record(agent, options, permissionsApi) {
99
+ this._agent = agent;
100
+ // Store the author DID that originally signed the message as a convenience for developers, so
101
+ // that they don't have to decode the signer's DID from the JWS.
102
+ this._author = options.author;
103
+ // The creator is the author of the initial write, or the author of the record if there is no initial write.
104
+ this._creator = options.initialWrite ? (0, agent_1.getRecordAuthor)(options.initialWrite) : options.author;
105
+ // Store the `connectedDid`, and optionally the `delegateDid` and `permissionsApi` in order to be able
106
+ // to perform operations on the record (update, delete, data) as a delegate of the connected DID.
107
+ this._connectedDid = options.connectedDid;
108
+ this._delegateDid = options.delegateDid;
109
+ this._permissionsApi = permissionsApi !== null && permissionsApi !== void 0 ? permissionsApi : new agent_1.AgentPermissionsApi({ agent: agent });
110
+ // If the record was queried or read from a remote DWN, the `remoteOrigin` DID will be
111
+ // defined. This value is used to send subsequent read requests to the same remote DWN in the
112
+ // event the record's data payload was too large to be returned in query results. or must be
113
+ // read again (e.g., if the data stream is consumed).
114
+ this._remoteOrigin = options.remoteOrigin;
115
+ // RecordsWriteMessage properties.
116
+ this._attestation = options.attestation;
117
+ this._authorization = options.authorization;
118
+ this._contextId = options.contextId;
119
+ this._descriptor = options.descriptor;
120
+ this._encryption = options.encryption;
121
+ this._initialWrite = options.initialWrite;
122
+ this._recordId = this.isRecordsDeleteDescriptor(options.descriptor) ? options.descriptor.recordId : options.recordId;
123
+ this._protocolRole = options.protocolRole;
124
+ if (options.encodedData) {
125
+ // If `encodedData` is set, then it is expected that:
126
+ // type is Blob if the Record object was instantiated by dwn.records.create()/write().
127
+ // type is Base64 URL encoded string if the Record object was instantiated by dwn.records.query().
128
+ // If it is a string, we need to Base64 URL decode to bytes and instantiate a Blob.
129
+ this._encodedData = (typeof options.encodedData === 'string') ?
130
+ new Blob([common_1.Convert.base64Url(options.encodedData).toUint8Array()], { type: this.dataFormat }) :
131
+ options.encodedData;
132
+ }
133
+ if (options.data) {
134
+ // If the record was created from a RecordsRead reply then it will have a `data` property.
135
+ // If the `data` property is a web ReadableStream, convert it to a Node.js Readable.
136
+ this._readableStream = common_1.Stream.isReadableStream(options.data) ?
137
+ common_1.NodeStream.fromWebReadable({ readableStream: options.data }) :
138
+ options.data;
139
+ }
140
+ }
141
+ Object.defineProperty(Record.prototype, "_recordsWriteDescriptor", {
142
+ /** The `RecordsWriteMessage` descriptor unless the record is in a deleted state */
143
+ get: function () {
144
+ if ((0, agent_1.isDwnMessage)(agent_1.DwnInterface.RecordsWrite, this.rawMessage)) {
145
+ return this._descriptor;
146
+ }
147
+ return undefined; // returns undefined if the descriptor does not represent a RecordsWrite message.
148
+ },
149
+ enumerable: false,
150
+ configurable: true
151
+ });
152
+ Object.defineProperty(Record.prototype, "_immutableProperties", {
153
+ /** The `RecordsWrite` descriptor from the current record or the initial write if the record is in a delete state. */
154
+ get: function () {
155
+ return this._recordsWriteDescriptor || this._initialWrite.descriptor;
156
+ },
157
+ enumerable: false,
158
+ configurable: true
159
+ });
160
+ Object.defineProperty(Record.prototype, "id", {
161
+ // Getters for immutable Record properties.
162
+ /** Record's ID */
163
+ get: function () { return this._recordId; },
164
+ enumerable: false,
165
+ configurable: true
166
+ });
167
+ Object.defineProperty(Record.prototype, "contextId", {
168
+ /** Record's context ID. If the record is deleted, the context Id comes from the initial write */
169
+ get: function () { return this.deleted ? this._initialWrite.contextId : this._contextId; },
170
+ enumerable: false,
171
+ configurable: true
172
+ });
173
+ Object.defineProperty(Record.prototype, "dateCreated", {
174
+ /** Record's creation date */
175
+ get: function () { return this._immutableProperties.dateCreated; },
176
+ enumerable: false,
177
+ configurable: true
178
+ });
179
+ Object.defineProperty(Record.prototype, "parentId", {
180
+ /** Record's parent ID */
181
+ get: function () { return this._immutableProperties.parentId; },
182
+ enumerable: false,
183
+ configurable: true
184
+ });
185
+ Object.defineProperty(Record.prototype, "protocol", {
186
+ /** Record's protocol */
187
+ get: function () { return this._immutableProperties.protocol; },
188
+ enumerable: false,
189
+ configurable: true
190
+ });
191
+ Object.defineProperty(Record.prototype, "protocolPath", {
192
+ /** Record's protocol path */
193
+ get: function () { return this._immutableProperties.protocolPath; },
194
+ enumerable: false,
195
+ configurable: true
196
+ });
197
+ Object.defineProperty(Record.prototype, "recipient", {
198
+ /** Record's recipient */
199
+ get: function () { return this._immutableProperties.recipient; },
200
+ enumerable: false,
201
+ configurable: true
202
+ });
203
+ Object.defineProperty(Record.prototype, "schema", {
204
+ /** Record's schema */
205
+ get: function () { return this._immutableProperties.schema; },
206
+ enumerable: false,
207
+ configurable: true
208
+ });
209
+ Object.defineProperty(Record.prototype, "dataFormat", {
210
+ // Getters for mutable DWN RecordsWrite properties that may be undefined in a deleted state.
211
+ /** Record's data format */
212
+ get: function () { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.dataFormat; },
213
+ enumerable: false,
214
+ configurable: true
215
+ });
216
+ Object.defineProperty(Record.prototype, "dataCid", {
217
+ /** Record's CID */
218
+ get: function () { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.dataCid; },
219
+ enumerable: false,
220
+ configurable: true
221
+ });
222
+ Object.defineProperty(Record.prototype, "dataSize", {
223
+ /** Record's data size */
224
+ get: function () { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.dataSize; },
225
+ enumerable: false,
226
+ configurable: true
227
+ });
228
+ Object.defineProperty(Record.prototype, "datePublished", {
229
+ /** Record's published date */
230
+ get: function () { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.datePublished; },
231
+ enumerable: false,
232
+ configurable: true
233
+ });
234
+ Object.defineProperty(Record.prototype, "published", {
235
+ /** Record's published status (true/false) */
236
+ get: function () { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.published; },
237
+ enumerable: false,
238
+ configurable: true
239
+ });
240
+ Object.defineProperty(Record.prototype, "tags", {
241
+ /** Tags of the record */
242
+ get: function () { var _a; return (_a = this._recordsWriteDescriptor) === null || _a === void 0 ? void 0 : _a.tags; },
243
+ enumerable: false,
244
+ configurable: true
245
+ });
246
+ Object.defineProperty(Record.prototype, "author", {
247
+ // Getters for for properties that depend on the current state of the Record.
248
+ /** DID that is the logical author of the Record. */
249
+ get: function () { return this._author; },
250
+ enumerable: false,
251
+ configurable: true
252
+ });
253
+ Object.defineProperty(Record.prototype, "creator", {
254
+ /** DID that is the original creator of the Record. */
255
+ get: function () { return this._creator; },
256
+ enumerable: false,
257
+ configurable: true
258
+ });
259
+ Object.defineProperty(Record.prototype, "dateModified", {
260
+ /** Record's modified date */
261
+ get: function () { return this._descriptor.messageTimestamp; },
262
+ enumerable: false,
263
+ configurable: true
264
+ });
265
+ Object.defineProperty(Record.prototype, "encryption", {
266
+ /** Record's encryption */
267
+ get: function () { return this._encryption; },
268
+ enumerable: false,
269
+ configurable: true
270
+ });
271
+ Object.defineProperty(Record.prototype, "authorization", {
272
+ /** Record's signatures attestation */
273
+ get: function () { return this._authorization; },
274
+ enumerable: false,
275
+ configurable: true
276
+ });
277
+ Object.defineProperty(Record.prototype, "attestation", {
278
+ /** Record's signatures attestation */
279
+ get: function () { return this._attestation; },
280
+ enumerable: false,
281
+ configurable: true
282
+ });
283
+ Object.defineProperty(Record.prototype, "protocolRole", {
284
+ /** Role under which the author is writing the record */
285
+ get: function () { return this._protocolRole; },
286
+ enumerable: false,
287
+ configurable: true
288
+ });
289
+ Object.defineProperty(Record.prototype, "deleted", {
290
+ /** Record's deleted state (true/false) */
291
+ get: function () { return (0, agent_1.isDwnMessage)(agent_1.DwnInterface.RecordsDelete, this.rawMessage); },
292
+ enumerable: false,
293
+ configurable: true
294
+ });
295
+ Object.defineProperty(Record.prototype, "initialWrite", {
296
+ /** Record's initial write if the record has been updated */
297
+ get: function () { return this._initialWrite; },
298
+ enumerable: false,
299
+ configurable: true
300
+ });
301
+ Object.defineProperty(Record.prototype, "rawMessage", {
302
+ /**
303
+ * Returns a copy of the raw `RecordsWriteMessage` that was used to create the current `Record` instance.
304
+ */
305
+ get: function () {
306
+ var messageType = this._descriptor.interface + this._descriptor.method;
307
+ var message;
308
+ if (messageType === agent_1.DwnInterface.RecordsWrite) {
309
+ message = JSON.parse(JSON.stringify({
310
+ contextId: this._contextId,
311
+ recordId: this._recordId,
312
+ descriptor: this._descriptor,
313
+ attestation: this._attestation,
314
+ authorization: this._authorization,
315
+ encryption: this._encryption,
316
+ }));
317
+ }
318
+ else {
319
+ message = JSON.parse(JSON.stringify({
320
+ descriptor: this._descriptor,
321
+ authorization: this._authorization,
322
+ }));
323
+ }
324
+ (0, common_1.removeUndefinedProperties)(message);
325
+ return message;
326
+ },
327
+ enumerable: false,
328
+ configurable: true
329
+ });
330
+ Object.defineProperty(Record.prototype, "data", {
331
+ /**
332
+ * Returns the data of the current record.
333
+ * If the record data is not available, it attempts to fetch the data from the DWN.
334
+ * @returns a data stream with convenience methods such as `blob()`, `json()`, `text()`, and `stream()`, similar to the fetch API response
335
+ * @throws `Error` if the record has already been deleted.
336
+ *
337
+ * @beta
338
+ */
339
+ get: function () {
340
+ var self = this; // Capture the context of the `Record` instance.
341
+ var dataObj = {
342
+ /**
343
+ * Returns the data of the current record as a `Blob`.
344
+ *
345
+ * @returns A promise that resolves to a Blob containing the record's data.
346
+ * @throws If the record data is not available or cannot be converted to a `Blob`.
347
+ *
348
+ * @beta
349
+ */
350
+ blob: function () {
351
+ return __awaiter(this, void 0, void 0, function () {
352
+ var _a, _b, _c;
353
+ var _d;
354
+ return __generator(this, function (_e) {
355
+ switch (_e.label) {
356
+ case 0:
357
+ _a = Blob.bind;
358
+ _c = (_b = common_1.NodeStream).consumeToBytes;
359
+ _d = {};
360
+ return [4 /*yield*/, this.stream()];
361
+ case 1: return [4 /*yield*/, _c.apply(_b, [(_d.readable = _e.sent(), _d)])];
362
+ case 2: return [2 /*return*/, new (_a.apply(Blob, [void 0, [_e.sent()], { type: self.dataFormat }]))()];
363
+ }
364
+ });
365
+ });
366
+ },
367
+ /**
368
+ * Returns the data of the current record as a `Uint8Array`.
369
+ *
370
+ * @returns A Promise that resolves to a `Uint8Array` containing the record's data bytes.
371
+ * @throws If the record data is not available or cannot be converted to a byte array.
372
+ *
373
+ * @beta
374
+ */
375
+ bytes: function () {
376
+ return __awaiter(this, void 0, void 0, function () {
377
+ var _a, _b;
378
+ var _c;
379
+ return __generator(this, function (_d) {
380
+ switch (_d.label) {
381
+ case 0:
382
+ _b = (_a = common_1.NodeStream).consumeToBytes;
383
+ _c = {};
384
+ return [4 /*yield*/, this.stream()];
385
+ case 1: return [4 /*yield*/, _b.apply(_a, [(_c.readable = _d.sent(), _c)])];
386
+ case 2: return [2 /*return*/, _d.sent()];
387
+ }
388
+ });
389
+ });
390
+ },
391
+ /**
392
+ * Parses the data of the current record as JSON and returns it as a JavaScript object.
393
+ *
394
+ * @returns A Promise that resolves to a JavaScript object parsed from the record's JSON data.
395
+ * @throws If the record data is not available, not in JSON format, or cannot be parsed.
396
+ *
397
+ * @beta
398
+ */
399
+ json: function () {
400
+ return __awaiter(this, void 0, void 0, function () {
401
+ var _a, _b;
402
+ var _c;
403
+ return __generator(this, function (_d) {
404
+ switch (_d.label) {
405
+ case 0:
406
+ _b = (_a = common_1.NodeStream).consumeToJson;
407
+ _c = {};
408
+ return [4 /*yield*/, this.stream()];
409
+ case 1: return [4 /*yield*/, _b.apply(_a, [(_c.readable = _d.sent(), _c)])];
410
+ case 2: return [2 /*return*/, _d.sent()];
411
+ }
412
+ });
413
+ });
414
+ },
415
+ /**
416
+ * Returns the data of the current record as a `string`.
417
+ *
418
+ * @returns A promise that resolves to a `string` containing the record's text data.
419
+ * @throws If the record data is not available or cannot be converted to text.
420
+ *
421
+ * @beta
422
+ */
423
+ text: function () {
424
+ return __awaiter(this, void 0, void 0, function () {
425
+ var _a, _b;
426
+ var _c;
427
+ return __generator(this, function (_d) {
428
+ switch (_d.label) {
429
+ case 0:
430
+ _b = (_a = common_1.NodeStream).consumeToText;
431
+ _c = {};
432
+ return [4 /*yield*/, this.stream()];
433
+ case 1: return [4 /*yield*/, _b.apply(_a, [(_c.readable = _d.sent(), _c)])];
434
+ case 2: return [2 /*return*/, _d.sent()];
435
+ }
436
+ });
437
+ });
438
+ },
439
+ /**
440
+ * Provides a `Readable` stream containing the record's data.
441
+ *
442
+ * @returns A promise that resolves to a Node.js `Readable` stream of the record's data.
443
+ * @throws If the record data is not available in-memory and cannot be fetched.
444
+ *
445
+ * @beta
446
+ */
447
+ stream: function () {
448
+ return __awaiter(this, void 0, void 0, function () {
449
+ var _a, _b;
450
+ return __generator(this, function (_c) {
451
+ switch (_c.label) {
452
+ case 0:
453
+ if (!self._encodedData) return [3 /*break*/, 1];
454
+ /** If `encodedData` is set, it indicates that the Record was instantiated by
455
+ * `dwn.records.create()`/`dwn.records.write()` or the record's data payload was small
456
+ * enough to be returned in `dwn.records.query()` results. In either case, the data is
457
+ * already available in-memory and can be returned as a Node.js `Readable` stream. */
458
+ self._readableStream = common_1.NodeStream.fromWebReadable({ readableStream: self._encodedData.stream() });
459
+ return [3 /*break*/, 6];
460
+ case 1:
461
+ if (!!common_1.NodeStream.isReadable({ readable: self._readableStream })) return [3 /*break*/, 6];
462
+ /** If the data stream for this `Record` instance has already been partially or fully
463
+ * consumed, then the data must be fetched again from either: */
464
+ _a = self;
465
+ if (!self._remoteOrigin) return [3 /*break*/, 3];
466
+ // A. ...a remote DWN if the record was originally queried from a remote DWN.
467
+ return [4 /*yield*/, self.readRecordData({ target: self._remoteOrigin, isRemote: true })];
468
+ case 2:
469
+ // A. ...a remote DWN if the record was originally queried from a remote DWN.
470
+ _b = _c.sent();
471
+ return [3 /*break*/, 5];
472
+ case 3:
473
+ // B. ...a local DWN if the record was originally queried from the local DWN.
474
+ return [4 /*yield*/, self.readRecordData({ target: self._connectedDid, isRemote: false })];
475
+ case 4:
476
+ // B. ...a local DWN if the record was originally queried from the local DWN.
477
+ _b = _c.sent();
478
+ _c.label = 5;
479
+ case 5:
480
+ /** If the data stream for this `Record` instance has already been partially or fully
481
+ * consumed, then the data must be fetched again from either: */
482
+ _a._readableStream = _b;
483
+ _c.label = 6;
484
+ case 6:
485
+ if (!self._readableStream) {
486
+ throw new Error('Record data is not available.');
487
+ }
488
+ return [2 /*return*/, self._readableStream];
489
+ }
490
+ });
491
+ });
492
+ },
493
+ /**
494
+ * Attaches callbacks for the resolution and/or rejection of the `Promise` returned by
495
+ * `stream()`.
496
+ *
497
+ * This method is a proxy to the `then` method of the `Promise` returned by `stream()`,
498
+ * allowing for a seamless integration with promise-based workflows.
499
+ * @param onFulfilled - A function to asynchronously execute when the `stream()` promise
500
+ * becomes fulfilled.
501
+ * @param onRejected - A function to asynchronously execute when the `stream()` promise
502
+ * becomes rejected.
503
+ * @returns A `Promise` for the completion of which ever callback is executed.
504
+ */
505
+ then: function (onFulfilled, onRejected) {
506
+ return this.stream().then(onFulfilled, onRejected);
507
+ },
508
+ /**
509
+ * Attaches a rejection handler callback to the `Promise` returned by the `stream()` method.
510
+ * This method is a shorthand for `.then(undefined, onRejected)`, specifically designed for handling
511
+ * rejection cases in the promise chain initiated by accessing the record's data. It ensures that
512
+ * errors during data retrieval or processing can be caught and handled appropriately.
513
+ *
514
+ * @param onRejected - A function to asynchronously execute when the `stream()` promise
515
+ * becomes rejected.
516
+ * @returns A `Promise` that resolves to the value of the callback if it is called, or to its
517
+ * original fulfillment value if the promise is instead fulfilled.
518
+ */
519
+ catch: function (onRejected) {
520
+ return this.stream().catch(onRejected);
521
+ }
522
+ };
523
+ return dataObj;
524
+ },
525
+ enumerable: false,
526
+ configurable: true
527
+ });
528
+ /**
529
+ * Stores the current record state as well as any initial write to the owner's DWN.
530
+ *
531
+ * @param importRecord - if true, the record will signed by the owner before storing it to the owner's DWN. Defaults to false.
532
+ * @returns the status of the store request
533
+ *
534
+ * @beta
535
+ */
536
+ Record.prototype.store = function (importRecord) {
537
+ if (importRecord === void 0) { importRecord = false; }
538
+ return __awaiter(this, void 0, void 0, function () {
539
+ return __generator(this, function (_a) {
540
+ // if we are importing the record we sign it as the owner
541
+ return [2 /*return*/, this.processRecord({ signAsOwner: importRecord, store: true })];
542
+ });
543
+ });
544
+ };
545
+ /**
546
+ * Signs the current record state as well as any initial write and optionally stores it to the owner's DWN.
547
+ * This is useful when importing a record that was signed by someone else into your own DWN.
548
+ *
549
+ * @param store - if true, the record will be stored to the owner's DWN after signing. Defaults to true.
550
+ * @returns the status of the import request
551
+ *
552
+ * @beta
553
+ */
554
+ Record.prototype.import = function (store) {
555
+ if (store === void 0) { store = true; }
556
+ return __awaiter(this, void 0, void 0, function () {
557
+ return __generator(this, function (_a) {
558
+ return [2 /*return*/, this.processRecord({ store: store, signAsOwner: true })];
559
+ });
560
+ });
561
+ };
562
+ /**
563
+ * Send the current record to a remote DWN by specifying their DID
564
+ * If no DID is specified, the target is assumed to be the owner (connectedDID).
565
+ *
566
+ * If an initial write is present and the Record class send cache has no awareness of it, the initial write is sent first
567
+ * (vs waiting for the regular DWN sync)
568
+ *
569
+ * @param target - the optional DID to send the record to, if none is set it is sent to the connectedDid
570
+ * @returns the status of the send record request
571
+ * @throws `Error` if the record has already been deleted.
572
+ *
573
+ * @beta
574
+ */
575
+ Record.prototype.send = function (target) {
576
+ return __awaiter(this, void 0, void 0, function () {
577
+ var initialWrite, rawMessage, sendRequestOptions, reply;
578
+ var _a;
579
+ return __generator(this, function (_b) {
580
+ switch (_b.label) {
581
+ case 0:
582
+ initialWrite = this._initialWrite;
583
+ target !== null && target !== void 0 ? target : (target = this._connectedDid);
584
+ if (!(initialWrite && !Record._sendCache.check(this._recordId, target))) return [3 /*break*/, 2];
585
+ rawMessage = __assign({}, initialWrite);
586
+ (0, common_1.removeUndefinedProperties)(rawMessage);
587
+ // Send the initial write to the target.
588
+ return [4 /*yield*/, this._agent.sendDwnRequest({
589
+ messageType: agent_1.DwnInterface.RecordsWrite,
590
+ author: this._connectedDid,
591
+ target: target,
592
+ rawMessage: rawMessage
593
+ })];
594
+ case 1:
595
+ // Send the initial write to the target.
596
+ _b.sent();
597
+ // Set the cache to maintain awareness that we don't need to send the initial write next time.
598
+ Record._sendCache.set(this._recordId, target);
599
+ _b.label = 2;
600
+ case 2:
601
+ if (!this.deleted) return [3 /*break*/, 3];
602
+ sendRequestOptions = {
603
+ messageType: agent_1.DwnInterface.RecordsDelete,
604
+ author: this._connectedDid,
605
+ target: target,
606
+ rawMessage: __assign({}, this.rawMessage)
607
+ };
608
+ return [3 /*break*/, 5];
609
+ case 3:
610
+ _a = {
611
+ messageType: agent_1.DwnInterface.RecordsWrite,
612
+ author: this._connectedDid,
613
+ target: target
614
+ };
615
+ return [4 /*yield*/, this.data.blob()];
616
+ case 4:
617
+ sendRequestOptions = (_a.dataStream = _b.sent(),
618
+ _a.rawMessage = __assign({}, this.rawMessage),
619
+ _a);
620
+ _b.label = 5;
621
+ case 5: return [4 /*yield*/, this._agent.sendDwnRequest(sendRequestOptions)];
622
+ case 6:
623
+ reply = (_b.sent()).reply;
624
+ return [2 /*return*/, reply];
625
+ }
626
+ });
627
+ });
628
+ };
629
+ /**
630
+ * Returns a JSON representation of the Record instance.
631
+ * It's called by `JSON.stringify(...)` automatically.
632
+ */
633
+ Record.prototype.toJSON = function () {
634
+ return {
635
+ attestation: this.attestation,
636
+ author: this.author,
637
+ authorization: this.authorization,
638
+ contextId: this.contextId,
639
+ dataCid: this.dataCid,
640
+ dataFormat: this.dataFormat,
641
+ dataSize: this.dataSize,
642
+ dateCreated: this.dateCreated,
643
+ messageTimestamp: this.dateModified,
644
+ datePublished: this.datePublished,
645
+ encryption: this.encryption,
646
+ parentId: this.parentId,
647
+ protocol: this.protocol,
648
+ protocolPath: this.protocolPath,
649
+ protocolRole: this.protocolRole,
650
+ published: this.published,
651
+ recipient: this.recipient,
652
+ recordId: this.id,
653
+ schema: this.schema,
654
+ tags: this.tags,
655
+ };
656
+ };
657
+ /**
658
+ * Convenience method to return the string representation of the Record instance.
659
+ * Called automatically in string concatenation, String() type conversion, and template literals.
660
+ */
661
+ Record.prototype.toString = function () {
662
+ var str = "Record: {\n";
663
+ str += " ID: ".concat(this.id, "\n");
664
+ str += this.contextId ? " Context ID: ".concat(this.contextId, "\n") : '';
665
+ str += this.protocol ? " Protocol: ".concat(this.protocol, "\n") : '';
666
+ str += this.schema ? " Schema: ".concat(this.schema, "\n") : '';
667
+ // Only display data properties if the record has not been deleted.
668
+ if (!this.deleted) {
669
+ str += " Data CID: ".concat(this.dataCid, "\n");
670
+ str += " Data Format: ".concat(this.dataFormat, "\n");
671
+ str += " Data Size: ".concat(this.dataSize, "\n");
672
+ }
673
+ str += " Deleted: ".concat(this.deleted, "\n");
674
+ str += " Created: ".concat(this.dateCreated, "\n");
675
+ str += " Modified: ".concat(this.dateModified, "\n");
676
+ str += "}";
677
+ return str;
678
+ };
679
+ /**
680
+ * Returns a pagination cursor for the current record given a sort order.
681
+ *
682
+ * @param sort the sort order to use for the pagination cursor.
683
+ * @returns A promise that resolves to a pagination cursor for the current record.
684
+ */
685
+ Record.prototype.paginationCursor = function (sort) {
686
+ return __awaiter(this, void 0, void 0, function () {
687
+ return __generator(this, function (_a) {
688
+ return [2 /*return*/, (0, agent_1.isDwnMessage)(agent_1.DwnInterface.RecordsWrite, this.rawMessage) ? (0, agent_1.getPaginationCursor)(this.rawMessage, sort) : undefined];
689
+ });
690
+ });
691
+ };
692
+ /**
693
+ * Update the current record on the DWN.
694
+ * @param params - Parameters to update the record.
695
+ * @returns the status of the update request
696
+ * @throws `Error` if the record has already been deleted.
697
+ *
698
+ * @beta
699
+ */
700
+ Record.prototype.update = function (_a) {
701
+ var _b;
702
+ var dateModified = _a.dateModified, data = _a.data, protocolRole = _a.protocolRole, store = (_b = _a.store, _b === void 0 ? true : _b), params = __rest(_a, ["dateModified", "data", "protocolRole", "store"]);
703
+ return __awaiter(this, void 0, void 0, function () {
704
+ var _c, parentId, descriptor, parentContextId, updateMessage, dataBlob, mutableDescriptorProperties, requestOptions, delegatedGrant, agentResponse, message, status, responseMessage;
705
+ var _this = this;
706
+ return __generator(this, function (_d) {
707
+ switch (_d.label) {
708
+ case 0:
709
+ if (this.deleted) {
710
+ throw new Error('Record: Cannot revive a deleted record.');
711
+ }
712
+ _c = this._recordsWriteDescriptor, parentId = _c.parentId, descriptor = __rest(_c, ["parentId"]);
713
+ parentContextId = parentId ? this._contextId.split('/').slice(0, -1).join('/') : undefined;
714
+ updateMessage = __assign(__assign(__assign({}, descriptor), params), { parentContextId: parentContextId, protocolRole: protocolRole !== null && protocolRole !== void 0 ? protocolRole : this._protocolRole, messageTimestamp: dateModified, recordId: this._recordId });
715
+ // NOTE: The original Record's tags are copied to the update message, so that the tags are not lost.
716
+ // However if a user passes new tags in the `RecordUpdateParams` object, they will overwrite the original tags.
717
+ // 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.
718
+ if ((0, common_1.isEmptyObject)(updateMessage.tags) || updateMessage.tags === null) {
719
+ delete updateMessage.tags;
720
+ }
721
+ if (data !== undefined) {
722
+ // If `data` is being updated then `dataCid` and `dataSize` must be undefined and the `data`
723
+ // value must be converted to a Blob and later passed as a top-level property to
724
+ // `agent.processDwnRequest()`.
725
+ delete updateMessage.dataCid;
726
+ delete updateMessage.dataSize;
727
+ (dataBlob = (0, utils_js_1.dataToBlob)(data, updateMessage.dataFormat).dataBlob);
728
+ }
729
+ mutableDescriptorProperties = new Set(['data', 'dataCid', 'dataFormat', 'dataSize', 'datePublished', 'messageTimestamp', 'published', 'tags']);
730
+ Record.verifyPermittedMutation(Object.keys(params), mutableDescriptorProperties);
731
+ // If `published` is set to false, ensure that `datePublished` is undefined. Otherwise, DWN SDK's schema validation
732
+ // will throw an error if `published` is false but `datePublished` is set.
733
+ if (params.published === false && updateMessage.datePublished !== undefined) {
734
+ delete updateMessage.datePublished;
735
+ }
736
+ requestOptions = {
737
+ author: this._connectedDid,
738
+ dataStream: dataBlob,
739
+ messageParams: __assign({}, updateMessage),
740
+ messageType: agent_1.DwnInterface.RecordsWrite,
741
+ target: this._connectedDid,
742
+ store: store
743
+ };
744
+ if (!this._delegateDid) return [3 /*break*/, 2];
745
+ return [4 /*yield*/, this._permissionsApi.getPermissionForRequest({
746
+ connectedDid: this._connectedDid,
747
+ delegateDid: this._delegateDid,
748
+ protocol: this.protocol,
749
+ delegate: true,
750
+ cached: true,
751
+ messageType: requestOptions.messageType
752
+ })];
753
+ case 1:
754
+ delegatedGrant = (_d.sent()).message;
755
+ requestOptions.messageParams.delegatedGrant = delegatedGrant;
756
+ requestOptions.granteeDid = this._delegateDid;
757
+ _d.label = 2;
758
+ case 2: return [4 /*yield*/, this._agent.processDwnRequest(requestOptions)];
759
+ case 3:
760
+ agentResponse = _d.sent();
761
+ message = agentResponse.message, status = agentResponse.reply.status;
762
+ responseMessage = message;
763
+ if (200 <= status.code && status.code <= 299) {
764
+ // copy the original raw message to the initial write before we update the values.
765
+ if (!this._initialWrite) {
766
+ // If there is no initial write, we need to create one from the current record state.
767
+ // We checked in the beginning of the function that the rawMessage is a RecordsWrite message.
768
+ this._initialWrite = __assign({}, this.rawMessage);
769
+ }
770
+ // Only update the local Record instance mutable properties if the record was successfully (over)written.
771
+ this._authorization = responseMessage.authorization;
772
+ this._protocolRole = updateMessage.protocolRole;
773
+ mutableDescriptorProperties.forEach(function (property) {
774
+ _this._descriptor[property] = responseMessage.descriptor[property];
775
+ });
776
+ // Cache data.
777
+ if (data !== undefined) {
778
+ this._encodedData = dataBlob;
779
+ }
780
+ }
781
+ return [2 /*return*/, { status: status }];
782
+ }
783
+ });
784
+ });
785
+ };
786
+ /**
787
+ * Delete the current record on the DWN.
788
+ * @param params - Parameters to delete the record.
789
+ * @returns the status of the delete request
790
+ */
791
+ Record.prototype.delete = function (deleteParams) {
792
+ var _a;
793
+ return __awaiter(this, void 0, void 0, function () {
794
+ var store, signAsOwner, dateModified, prune, signAsOwnerValue, signAsOwnerDelegate, deleteOptions, differentRole, delegatedGrant, agentResponse, message, status;
795
+ var _b, _c, _d;
796
+ return __generator(this, function (_e) {
797
+ switch (_e.label) {
798
+ case 0:
799
+ store = (_b = deleteParams || {}, _c = _b.store, _c === void 0 ? true : _c), signAsOwner = _b.signAsOwner, dateModified = _b.dateModified, prune = (_d = _b.prune, _d === void 0 ? false : _d);
800
+ signAsOwnerValue = signAsOwner && this._delegateDid === undefined;
801
+ signAsOwnerDelegate = signAsOwner && this._delegateDid !== undefined;
802
+ if (this.deleted && !this._initialWrite) {
803
+ throw new Error('Record: Record is in an invalid state, initial write is missing.');
804
+ }
805
+ if (!this._initialWrite) {
806
+ // If there is no initial write, we need to create one from the current record state.
807
+ // We checked in the beginning of the function that the initialWrite is not set if the rawMessage is a RecordsDelete message.
808
+ // So we can safely assume that the rawMessage is a RecordsWrite message.
809
+ this._initialWrite = __assign({}, this.rawMessage);
810
+ }
811
+ return [4 /*yield*/, this.processInitialWriteIfNeeded({ store: store, signAsOwner: signAsOwner })];
812
+ case 1:
813
+ _e.sent();
814
+ deleteOptions = {
815
+ messageType: agent_1.DwnInterface.RecordsDelete,
816
+ author: this._connectedDid,
817
+ target: this._connectedDid,
818
+ signAsOwner: signAsOwnerValue,
819
+ signAsOwnerDelegate: signAsOwnerDelegate,
820
+ store: store
821
+ };
822
+ differentRole = (deleteParams === null || deleteParams === void 0 ? void 0 : deleteParams.protocolRole) ? (0, agent_1.getRecordProtocolRole)(this.rawMessage) !== deleteParams.protocolRole : false;
823
+ // 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
824
+ // otherwise we can just use the existing delete message.
825
+ if (this.deleted && !differentRole) {
826
+ deleteOptions.rawMessage = this.rawMessage;
827
+ }
828
+ else {
829
+ // otherwise we construct a delete message given the `RecordDeleteParams`
830
+ deleteOptions.messageParams = {
831
+ prune: prune,
832
+ recordId: this._recordId,
833
+ messageTimestamp: dateModified,
834
+ 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
835
+ };
836
+ }
837
+ if (!this._delegateDid) return [3 /*break*/, 3];
838
+ return [4 /*yield*/, this._permissionsApi.getPermissionForRequest({
839
+ connectedDid: this._connectedDid,
840
+ delegateDid: this._delegateDid,
841
+ protocol: this.protocol,
842
+ delegate: true,
843
+ cached: true,
844
+ messageType: deleteOptions.messageType
845
+ })];
846
+ case 2:
847
+ delegatedGrant = (_e.sent()).message;
848
+ deleteOptions.messageParams = __assign(__assign({}, deleteOptions.messageParams), { delegatedGrant: delegatedGrant });
849
+ deleteOptions.granteeDid = this._delegateDid;
850
+ _e.label = 3;
851
+ case 3: return [4 /*yield*/, this._agent.processDwnRequest(deleteOptions)];
852
+ case 4:
853
+ agentResponse = _e.sent();
854
+ message = agentResponse.message, status = agentResponse.reply.status;
855
+ if (status.code !== 202) {
856
+ // If the delete was not successful, return the status.
857
+ return [2 /*return*/, { status: status }];
858
+ }
859
+ // If the delete was successful, update the Record author to the author of the delete message.
860
+ this._author = (0, agent_1.getRecordAuthor)(message);
861
+ this._descriptor = message.descriptor;
862
+ this._authorization = message.authorization;
863
+ // clear out properties that are not relevant for a deleted record
864
+ this._encodedData = undefined;
865
+ this._encryption = undefined;
866
+ this._attestation = undefined;
867
+ this._contextId = undefined;
868
+ return [2 /*return*/, { status: status }];
869
+ }
870
+ });
871
+ });
872
+ };
873
+ /**
874
+ * Process the initial write, if it hasn't already been processed, with the options set for storing and/or signing as the owner.
875
+ */
876
+ Record.prototype.processInitialWriteIfNeeded = function (_a) {
877
+ var store = _a.store, signAsOwner = _a.signAsOwner;
878
+ return __awaiter(this, void 0, void 0, function () {
879
+ var signAsOwnerValue, signAsOwnerDelegate, initialWriteRequest, delegatedGrant, agentResponse, message, status_1, responseMessage;
880
+ return __generator(this, function (_b) {
881
+ switch (_b.label) {
882
+ case 0:
883
+ if (!(this.initialWrite && ((signAsOwner && !this._initialWriteSigned) || (store && !this._initialWriteStored)))) return [3 /*break*/, 4];
884
+ signAsOwnerValue = signAsOwner && this._delegateDid === undefined;
885
+ signAsOwnerDelegate = signAsOwner && this._delegateDid !== undefined;
886
+ initialWriteRequest = {
887
+ messageType: agent_1.DwnInterface.RecordsWrite,
888
+ rawMessage: this.initialWrite,
889
+ author: this._connectedDid,
890
+ target: this._connectedDid,
891
+ signAsOwner: signAsOwnerValue,
892
+ signAsOwnerDelegate: signAsOwnerDelegate,
893
+ store: store,
894
+ };
895
+ if (!this._delegateDid) return [3 /*break*/, 2];
896
+ return [4 /*yield*/, this._permissionsApi.getPermissionForRequest({
897
+ connectedDid: this._connectedDid,
898
+ delegateDid: this._delegateDid,
899
+ protocol: this.protocol,
900
+ delegate: true,
901
+ cached: true,
902
+ messageType: initialWriteRequest.messageType
903
+ })];
904
+ case 1:
905
+ delegatedGrant = (_b.sent()).message;
906
+ initialWriteRequest.messageParams = __assign(__assign({}, initialWriteRequest.messageParams), { delegatedGrant: delegatedGrant });
907
+ initialWriteRequest.granteeDid = this._delegateDid;
908
+ _b.label = 2;
909
+ case 2: return [4 /*yield*/, this._agent.processDwnRequest(initialWriteRequest)];
910
+ case 3:
911
+ agentResponse = _b.sent();
912
+ message = agentResponse.message, status_1 = agentResponse.reply.status;
913
+ responseMessage = message;
914
+ if (200 <= status_1.code && status_1.code <= 299) {
915
+ if (store)
916
+ this._initialWriteStored = true;
917
+ if (signAsOwner) {
918
+ this._initialWriteSigned = true;
919
+ this.initialWrite.authorization = responseMessage.authorization;
920
+ }
921
+ }
922
+ _b.label = 4;
923
+ case 4: return [2 /*return*/];
924
+ }
925
+ });
926
+ });
927
+ };
928
+ /**
929
+ * Handles the various conditions around there being an initial write, whether to store initial/current state,
930
+ * and whether to add an owner signature to the initial write to enable storage when protocol rules require it.
931
+ */
932
+ Record.prototype.processRecord = function (_a) {
933
+ var store = _a.store, signAsOwner = _a.signAsOwner;
934
+ return __awaiter(this, void 0, void 0, function () {
935
+ var signAsOwnerValue, signAsOwnerDelegate, requestOptions, delegatedGrant, agentResponse, message, status, responseMessage;
936
+ var _b;
937
+ return __generator(this, function (_c) {
938
+ switch (_c.label) {
939
+ case 0:
940
+ signAsOwnerValue = signAsOwner && this._delegateDid === undefined;
941
+ signAsOwnerDelegate = signAsOwner && this._delegateDid !== undefined;
942
+ return [4 /*yield*/, this.processInitialWriteIfNeeded({ store: store, signAsOwner: signAsOwner })];
943
+ case 1:
944
+ _c.sent();
945
+ if (!this.deleted) return [3 /*break*/, 2];
946
+ requestOptions = {
947
+ messageType: agent_1.DwnInterface.RecordsDelete,
948
+ rawMessage: this.rawMessage,
949
+ author: this._connectedDid,
950
+ target: this._connectedDid,
951
+ signAsOwner: signAsOwnerValue,
952
+ signAsOwnerDelegate: signAsOwnerDelegate,
953
+ store: store,
954
+ };
955
+ return [3 /*break*/, 4];
956
+ case 2:
957
+ _b = {
958
+ messageType: agent_1.DwnInterface.RecordsWrite,
959
+ rawMessage: this.rawMessage,
960
+ author: this._connectedDid,
961
+ target: this._connectedDid
962
+ };
963
+ return [4 /*yield*/, this.data.blob()];
964
+ case 3:
965
+ requestOptions = (_b.dataStream = _c.sent(),
966
+ _b.signAsOwner = signAsOwnerValue,
967
+ _b.signAsOwnerDelegate = signAsOwnerDelegate,
968
+ _b.store = store,
969
+ _b);
970
+ _c.label = 4;
971
+ case 4:
972
+ if (!this._delegateDid) return [3 /*break*/, 6];
973
+ return [4 /*yield*/, this._permissionsApi.getPermissionForRequest({
974
+ connectedDid: this._connectedDid,
975
+ delegateDid: this._delegateDid,
976
+ protocol: this.protocol,
977
+ delegate: true,
978
+ cached: true,
979
+ messageType: requestOptions.messageType
980
+ })];
981
+ case 5:
982
+ delegatedGrant = (_c.sent()).message;
983
+ requestOptions.messageParams = __assign(__assign({}, requestOptions.messageParams), { delegatedGrant: delegatedGrant });
984
+ requestOptions.granteeDid = this._delegateDid;
985
+ _c.label = 6;
986
+ case 6: return [4 /*yield*/, this._agent.processDwnRequest(requestOptions)];
987
+ case 7:
988
+ agentResponse = _c.sent();
989
+ message = agentResponse.message, status = agentResponse.reply.status;
990
+ responseMessage = message;
991
+ if (200 <= status.code && status.code <= 299) {
992
+ // 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.
993
+ if (signAsOwner)
994
+ this._authorization = responseMessage.authorization;
995
+ }
996
+ return [2 /*return*/, { status: status }];
997
+ }
998
+ });
999
+ });
1000
+ };
1001
+ /**
1002
+ * Fetches the record's data from the specified DWN.
1003
+ *
1004
+ * This private method is called when the record data is not available in-memory
1005
+ * and needs to be fetched from either a local or a remote DWN.
1006
+ * It makes a read request to the specified DWN and processes the response to provide
1007
+ * a Node.js `Readable` stream of the record's data.
1008
+ *
1009
+ * @param params - Parameters for fetching the record's data.
1010
+ * @param params.target - The DID of the DWN to fetch the data from.
1011
+ * @param params.isRemote - Indicates whether the target DWN is a remote node.
1012
+ * @returns A Promise that resolves to a Node.js `Readable` stream of the record's data.
1013
+ * @throws If there is an error while fetching or processing the data from the DWN.
1014
+ *
1015
+ * @beta
1016
+ */
1017
+ Record.prototype.readRecordData = function (_a) {
1018
+ var target = _a.target, isRemote = _a.isRemote;
1019
+ return __awaiter(this, void 0, void 0, function () {
1020
+ var readRequest, delegatedGrant, error_1, agentResponsePromise, status_2, entry, dataStream, nodeReadable, error_2;
1021
+ var _b;
1022
+ return __generator(this, function (_c) {
1023
+ switch (_c.label) {
1024
+ case 0:
1025
+ readRequest = {
1026
+ author: this._connectedDid,
1027
+ messageParams: { filter: { recordId: this.id }, protocolRole: this._protocolRole },
1028
+ messageType: agent_1.DwnInterface.RecordsRead,
1029
+ target: target,
1030
+ };
1031
+ if (!this._delegateDid) return [3 /*break*/, 4];
1032
+ _c.label = 1;
1033
+ case 1:
1034
+ _c.trys.push([1, 3, , 4]);
1035
+ return [4 /*yield*/, this._permissionsApi.getPermissionForRequest({
1036
+ connectedDid: this._connectedDid,
1037
+ delegateDid: this._delegateDid,
1038
+ protocol: this.protocol,
1039
+ delegate: true,
1040
+ cached: true,
1041
+ messageType: readRequest.messageType
1042
+ })];
1043
+ case 2:
1044
+ delegatedGrant = (_c.sent()).message;
1045
+ readRequest.messageParams = __assign(__assign({}, readRequest.messageParams), { delegatedGrant: delegatedGrant });
1046
+ readRequest.granteeDid = this._delegateDid;
1047
+ return [3 /*break*/, 4];
1048
+ case 3:
1049
+ error_1 = _c.sent();
1050
+ // If there is an error fetching the grant, we will attempt to read the data as the delegate.
1051
+ readRequest.author = this._delegateDid;
1052
+ return [3 /*break*/, 4];
1053
+ case 4:
1054
+ agentResponsePromise = isRemote ?
1055
+ this._agent.sendDwnRequest(readRequest) :
1056
+ this._agent.processDwnRequest(readRequest);
1057
+ _c.label = 5;
1058
+ case 5:
1059
+ _c.trys.push([5, 7, , 8]);
1060
+ return [4 /*yield*/, agentResponsePromise];
1061
+ case 6:
1062
+ status_2 = (_b = (_c.sent()).reply, _b.status), entry = _b.entry;
1063
+ if (status_2.code !== 200) {
1064
+ throw new Error("".concat(status_2.code, ": ").concat(status_2.detail));
1065
+ }
1066
+ dataStream = entry.data;
1067
+ nodeReadable = common_1.Stream.isReadableStream(dataStream) ?
1068
+ common_1.NodeStream.fromWebReadable({ readableStream: dataStream }) :
1069
+ dataStream;
1070
+ return [2 /*return*/, nodeReadable];
1071
+ case 7:
1072
+ error_2 = _c.sent();
1073
+ throw new Error("Error encountered while attempting to read data: ".concat(error_2.message));
1074
+ case 8: return [2 /*return*/];
1075
+ }
1076
+ });
1077
+ });
1078
+ };
1079
+ /**
1080
+ * Verifies if the properties to be mutated are mutable.
1081
+ *
1082
+ * This private method is used to ensure that only mutable properties of the `Record` instance
1083
+ * are being changed. It checks whether the properties specified for mutation are among the
1084
+ * set of properties that are allowed to be modified. If any of the properties to be mutated
1085
+ * are not in the set of mutable properties, the method throws an error.
1086
+ *
1087
+ * @param propertiesToMutate - An iterable of property names that are intended to be mutated.
1088
+ * @param mutableDescriptorProperties - A set of property names that are allowed to be mutated.
1089
+ *
1090
+ * @throws If any of the properties in `propertiesToMutate` are not in `mutableDescriptorProperties`.
1091
+ *
1092
+ * @beta
1093
+ */
1094
+ Record.verifyPermittedMutation = function (propertiesToMutate, mutableDescriptorProperties) {
1095
+ var e_1, _a;
1096
+ try {
1097
+ for (var propertiesToMutate_1 = __values(propertiesToMutate), propertiesToMutate_1_1 = propertiesToMutate_1.next(); !propertiesToMutate_1_1.done; propertiesToMutate_1_1 = propertiesToMutate_1.next()) {
1098
+ var property = propertiesToMutate_1_1.value;
1099
+ if (!mutableDescriptorProperties.has(property)) {
1100
+ throw new Error("".concat(property, " is an immutable property. Its value cannot be changed."));
1101
+ }
1102
+ }
1103
+ }
1104
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1105
+ finally {
1106
+ try {
1107
+ if (propertiesToMutate_1_1 && !propertiesToMutate_1_1.done && (_a = propertiesToMutate_1.return)) _a.call(propertiesToMutate_1);
1108
+ }
1109
+ finally { if (e_1) throw e_1.error; }
1110
+ }
1111
+ };
1112
+ /**
1113
+ * Checks if the descriptor is a RecordsDelete descriptor.
1114
+ *
1115
+ * @param descriptor a RecordsWrite or RecordsDelete descriptor
1116
+ */
1117
+ Record.prototype.isRecordsDeleteDescriptor = function (descriptor) {
1118
+ return descriptor.interface + descriptor.method === agent_1.DwnInterface.RecordsDelete;
1119
+ };
1120
+ /**
1121
+ * Cache to minimize the amount of redundant two-phase commits we do in store() and send()
1122
+ * Retains awareness of the last 100 records stored/sent for up to 100 target DIDs each.
1123
+ */
1124
+ Record._sendCache = utils_js_1.SendCache;
1125
+ return Record;
1126
+ }());
1127
+ //# sourceMappingURL=record.js.map