Add comprehensive installation and setup documentation

- Add GETTING_STARTED.md with quick start guide and development modes
- Add INSTALL.sh automated installation script
- Add INSTALLATION_CHECKLIST.md, INSTALLATION_SUCCESS.md, and INSTALLATION_SUMMARY.md
- Add QUICK_REFERENCE.md for common commands
- Add SETUP_GUIDE.md with detailed setup instructions
- Update README.md with improved project overview
- Add did-wallet app dependencies and node_modules
This commit is contained in:
Dorian
2026-01-27 17:18:21 +00:00
parent a81f655133
commit 0d073fa89e
22658 changed files with 4494151 additions and 6 deletions
+69
View File
@@ -0,0 +1,69 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { DidInterface } from '@web5/agent';
/**
* The DID API is used to resolve DIDs.
*
* @beta
*/
export class DidApi {
constructor(options) {
this.agent = options.agent;
this.connectedDid = options.connectedDid;
}
/**
* Initiates the creation of a Decentralized Identifier (DID) using the specified method, options,
* and storage preference.
*
* This method sends a request to the Web5 Agent to create a new DID based on the provided method,
* with method-specific options. It also specifies whether the newly created DID should be stored.
*
* @param request - The request parameters for creating a DID, including the method, options, and
* storage flag.
* @returns A promise that resolves to a `DidCreateResponse`, which includes the operation's
* status and, if successful, the newly created DID.
*/
create(request) {
return __awaiter(this, void 0, void 0, function* () {
const _a = yield this.agent.processDidRequest({
messageType: DidInterface.Create,
messageParams: Object.assign({}, request)
}), { result } = _a, status = __rest(_a, ["result"]);
return Object.assign({ did: result }, status);
});
}
/**
* Resolves a DID to a DID Resolution Result.
*
* @param didUri - The DID or DID URL to resolve.
* @returns A promise that resolves to the DID Resolution Result.
*/
resolve(didUri, options) {
return __awaiter(this, void 0, void 0, function* () {
const { result: didResolutionResult } = yield this.agent.processDidRequest({
messageParams: { didUri, options },
messageType: DidInterface.Resolve
});
return didResolutionResult;
});
}
}
//# sourceMappingURL=did-api.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"did-api.js","sourceRoot":"","sources":["../../src/did-api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA8B3C;;;;GAIG;AACH,MAAM,OAAO,MAAM;IAUjB,YAAY,OAAmD;QAC7D,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAC3B,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3C,CAAC;IAED;;;;;;;;;;;OAWG;IACU,MAAM,CAAC,OAAyB;;YAC3C,MAAM,KAAwB,MAAM,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC;gBAC/D,WAAW,EAAK,YAAY,CAAC,MAAM;gBACnC,aAAa,oBAAQ,OAAO,CAAE;aAC/B,CAAC,EAHI,EAAE,MAAM,OAGZ,EAHiB,MAAM,cAAnB,UAAqB,CAGzB,CAAC;YAEH,uBAAS,GAAG,EAAE,MAAM,IAAK,MAAM,EAAG;QACpC,CAAC;KAAA;IAED;;;;;OAKG;IACU,OAAO,CAClB,MAAkC,EAAE,OAAqC;;YAEzE,MAAM,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC;gBACzE,aAAa,EAAG,EAAE,MAAM,EAAE,OAAO,EAAE;gBACnC,WAAW,EAAK,YAAY,CAAC,OAAO;aACrC,CAAC,CAAC;YAEH,OAAO,mBAAmB,CAAC;QAC7B,CAAC;KAAA;CACF"}
+298
View File
@@ -0,0 +1,298 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { isEmptyObject } from '@web5/common';
import { DwnInterface, getRecordAuthor } from '@web5/agent';
import { Record } from './record.js';
import { dataToBlob } from './utils.js';
import { Protocol } from './protocol.js';
/**
* Interface to interact with DWN Records and Protocols
*/
export class DwnApi {
constructor(options) {
this.agent = options.agent;
this.connectedDid = options.connectedDid;
}
/**
* API to interact with DWN protocols (e.g., `dwn.protocols.configure()`).
*/
get protocols() {
return {
/**
* Configure method, used to setup a new protocol (or update) with the passed definitions
*/
configure: (request) => __awaiter(this, void 0, void 0, function* () {
const agentResponse = yield this.agent.processDwnRequest({
author: this.connectedDid,
messageParams: request.message,
messageType: DwnInterface.ProtocolsConfigure,
target: this.connectedDid
});
const { message, messageCid, reply: { status } } = agentResponse;
const response = { status };
if (status.code < 300) {
const metadata = { author: this.connectedDid, messageCid };
response.protocol = new Protocol(this.agent, message, metadata);
}
return response;
}),
/**
* Query the available protocols
*/
query: (request) => __awaiter(this, void 0, void 0, function* () {
const agentRequest = {
author: this.connectedDid,
messageParams: request.message,
messageType: DwnInterface.ProtocolsQuery,
target: request.from || this.connectedDid
};
let agentResponse;
if (request.from) {
agentResponse = yield this.agent.sendDwnRequest(agentRequest);
}
else {
agentResponse = yield this.agent.processDwnRequest(agentRequest);
}
const reply = agentResponse.reply;
const { entries = [], status } = reply;
const protocols = entries.map((entry) => {
const metadata = { author: this.connectedDid };
return new Protocol(this.agent, entry, metadata);
});
return { protocols, status };
})
};
}
/**
* API to interact with DWN records (e.g., `dwn.records.create()`).
*/
get records() {
return {
/**
* Alias for the `write` method
*/
create: (request) => __awaiter(this, void 0, void 0, function* () {
return this.records.write(request);
}),
/**
* Write a record based on an existing one (useful for updating an existing record)
*/
createFrom: (request) => __awaiter(this, void 0, void 0, function* () {
var _a;
const _b = request.record.toJSON(), { author: inheritedAuthor } = _b, inheritedProperties = __rest(_b, ["author"]);
// If `data` is being updated then `dataCid` and `dataSize` must not be present.
if (request.data !== undefined) {
delete inheritedProperties.dataCid;
delete inheritedProperties.dataSize;
}
// If `published` is set to false, ensure that `datePublished` is undefined. Otherwise, DWN SDK's schema validation
// will throw an error if `published` is false but `datePublished` is set.
if (((_a = request.message) === null || _a === void 0 ? void 0 : _a.published) === false && inheritedProperties.datePublished !== undefined) {
delete inheritedProperties.datePublished;
delete inheritedProperties.published;
}
// If the request changes the `author` or message `descriptor` then the deterministic `recordId` will change.
// As a result, we will discard the `recordId` if either of these changes occur.
if (!isEmptyObject(request.message) || (request.author && request.author !== inheritedAuthor)) {
delete inheritedProperties.recordId;
}
return this.records.write({
data: request.data,
message: Object.assign(Object.assign({}, inheritedProperties), request.message),
});
}),
/**
* Delete a record
*/
delete: (request) => __awaiter(this, void 0, void 0, function* () {
const agentRequest = {
/**
* The `author` is the DID that will sign the message and must be the DID the Web5 app is
* connected with and is authorized to access the signing private key of.
*/
author: this.connectedDid,
messageParams: request.message,
messageType: DwnInterface.RecordsDelete,
/**
* The `target` is the DID of the DWN tenant under which the delete will be executed.
* If `from` is provided, the delete operation will be executed on a remote DWN.
* Otherwise, the record will be deleted on the local DWN.
*/
target: request.from || this.connectedDid
};
let agentResponse;
if (request.from) {
agentResponse = yield this.agent.sendDwnRequest(agentRequest);
}
else {
agentResponse = yield this.agent.processDwnRequest(agentRequest);
}
const { reply: { status } } = agentResponse;
return { status };
}),
/**
* Query a single or multiple records based on the given filter
*/
query: (request) => __awaiter(this, void 0, void 0, function* () {
const agentRequest = {
/**
* The `author` is the DID that will sign the message and must be the DID the Web5 app is
* connected with and is authorized to access the signing private key of.
*/
author: this.connectedDid,
messageParams: request.message,
messageType: DwnInterface.RecordsQuery,
/**
* The `target` is the DID of the DWN tenant under which the query will be executed.
* If `from` is provided, the query operation will be executed on a remote DWN.
* Otherwise, the local DWN will be queried.
*/
target: request.from || this.connectedDid
};
let agentResponse;
if (request.from) {
agentResponse = yield this.agent.sendDwnRequest(agentRequest);
}
else {
agentResponse = yield this.agent.processDwnRequest(agentRequest);
}
const reply = agentResponse.reply;
const { entries, status, cursor } = reply;
const records = entries.map((entry) => {
const recordOptions = Object.assign({
/**
* Extract the `author` DID from the record entry since records may be signed by the
* tenant owner or any other entity.
*/
author: getRecordAuthor(entry),
/**
* Set the `connectedDid` to currently connected DID so that subsequent calls to
* {@link Record} instance methods, such as `record.update()` are executed on the
* local DWN even if the record was returned by a query of a remote DWN.
*/
connectedDid: this.connectedDid,
/**
* If the record was returned by a query of a remote DWN, set the `remoteOrigin` to
* the DID of the DWN that returned the record. The `remoteOrigin` property will be used
* to determine which DWN to send subsequent read requests to in the event the data
* payload exceeds the threshold for being returned with queries.
*/
remoteOrigin: request.from }, entry);
const record = new Record(this.agent, recordOptions);
return record;
});
return { records, status, cursor };
}),
/**
* Read a single record based on the given filter
*/
read: (request) => __awaiter(this, void 0, void 0, function* () {
const agentRequest = {
/**
* The `author` is the DID that will sign the message and must be the DID the Web5 app is
* connected with and is authorized to access the signing private key of.
*/
author: this.connectedDid,
messageParams: request.message,
messageType: DwnInterface.RecordsRead,
/**
* The `target` is the DID of the DWN tenant under which the read will be executed.
* If `from` is provided, the read operation will be executed on a remote DWN.
* Otherwise, the read will occur on the local DWN.
*/
target: request.from || this.connectedDid
};
let agentResponse;
if (request.from) {
agentResponse = yield this.agent.sendDwnRequest(agentRequest);
}
else {
agentResponse = yield this.agent.processDwnRequest(agentRequest);
}
const { reply: { record: responseRecord, status } } = agentResponse;
let record;
if (200 <= status.code && status.code <= 299) {
const recordOptions = Object.assign({
/**
* Extract the `author` DID from the record since records may be signed by the
* tenant owner or any other entity.
*/
author: getRecordAuthor(responseRecord),
/**
* Set the `connectedDid` to currently connected DID so that subsequent calls to
* {@link Record} instance methods, such as `record.update()` are executed on the
* local DWN even if the record was read from a remote DWN.
*/
connectedDid: this.connectedDid,
/**
* If the record was returned by reading from a remote DWN, set the `remoteOrigin` to
* the DID of the DWN that returned the record. The `remoteOrigin` property will be used
* to determine which DWN to send subsequent read requests to in the event the data
* payload must be read again (e.g., if the data stream is consumed).
*/
remoteOrigin: request.from }, responseRecord);
record = new Record(this.agent, recordOptions);
}
return { record, status };
}),
/**
* Writes a record to the DWN
*
* As a convenience, the Record instance returned will cache a copy of the data. This is done
* to maintain consistency with other DWN methods, like RecordsQuery, that include relatively
* small data payloads when returning RecordsWrite message properties. Regardless of data
* size, methods such as `record.data.stream()` will return the data when called even if it
* requires fetching from the DWN datastore.
*/
write: (request) => __awaiter(this, void 0, void 0, function* () {
var _c;
const { dataBlob, dataFormat } = dataToBlob(request.data, (_c = request.message) === null || _c === void 0 ? void 0 : _c.dataFormat);
const agentResponse = yield this.agent.processDwnRequest({
author: this.connectedDid,
dataStream: dataBlob,
messageParams: Object.assign(Object.assign({}, request.message), { dataFormat }),
messageType: DwnInterface.RecordsWrite,
store: request.store,
target: this.connectedDid
});
const { message: responseMessage, reply: { status } } = agentResponse;
let record;
if (200 <= status.code && status.code <= 299) {
const recordOptions = Object.assign({
/**
* Assume the author is the connected DID since the record was just written to the
* local DWN.
*/
author: this.connectedDid,
/**
* Set the `connectedDid` to currently connected DID so that subsequent calls to
* {@link Record} instance methods, such as `record.update()` are executed on the
* local DWN.
*/
connectedDid: this.connectedDid, encodedData: dataBlob }, responseMessage);
record = new Record(this.agent, recordOptions);
}
return { record, status };
}),
};
}
}
//# sourceMappingURL=dwn-api.js.map
File diff suppressed because one or more lines are too long
+33
View File
@@ -0,0 +1,33 @@
/**
* Making developing with Web5 components at least 5 times easier to work with.
*
* Web5 consists of the following components:
* - Decentralized Identifiers
* - Verifiable Credentials
* - DWeb Node personal datastores
*
* The SDK sets out to gather the most oft used functionality from all three of
* these pillar technologies to provide a simple library that is as close to
* effortless as possible.
*
* The SDK is currently still under active development, but having entered the
* Tech Preview phase there is now a drive to avoid unnecessary changes unless
* backwards compatibility is provided. Additional functionality will be added
* in the lead up to 1.0 final, and modifications will be made to address
* issues and community feedback.
*
* [Link to GitHub Repo](https://github.com/TBD54566975/web5-js)
*
* @packageDocumentation
*/
export * from './did-api.js';
export * from './dwn-api.js';
export * from './protocol.js';
export * from './record.js';
export * from './vc-api.js';
export * from './web5.js';
export * from './tech-preview.js';
export * from './web-features.js';
import * as utils from './utils.js';
export { utils };
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAElC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,KAAK,EAAE,CAAC"}
+67
View File
@@ -0,0 +1,67 @@
/**
* NOTE: Added reference types here to avoid a `pnpm` bug during build.
* https://github.com/TBD54566975/web5-js/pull/507
*/
/// <reference types="@tbd54566975/dwn-sdk-js" />
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { DwnInterface } from '@web5/agent';
/**
* Encapsulates a DWN Protocol with its associated metadata and configuration.
*
* This class primarly exists to provide developers with a convenient way to configure/install
* protocols on remote DWNs.
*/
export class Protocol {
/**
* Constructs a new instance of the Protocol class.
*
* @param agent - The Web5Agent instance used for network interactions.
* @param protocolsConfigureMessage - The configuration message containing the protocol details.
* @param metadata - Metadata associated with the protocol, including the author and optional message CID.
*/
constructor(agent, protocolsConfigureMessage, metadata) {
this._agent = agent;
this._metadata = metadata;
this._protocolsConfigureMessage = protocolsConfigureMessage;
}
/**
* Retrieves the protocol definition from the protocol's configuration message.
* @returns The protocol definition.
*/
get definition() {
return this._protocolsConfigureMessage.descriptor.definition;
}
/**
* Serializes the protocol's configuration message to JSON.
* @returns The serialized JSON object of the protocol's configuration message.
*/
toJSON() {
return this._protocolsConfigureMessage;
}
/**
* Sends the protocol configuration to a remote DWN identified by the target DID.
*
* @param target - The DID of the target DWN to which the protocol configuration will be installed.
* @returns A promise that resolves to an object containing the status of the send operation.
*/
send(target) {
return __awaiter(this, void 0, void 0, function* () {
const { reply } = yield this._agent.sendDwnRequest({
author: this._metadata.author,
messageCid: this._metadata.messageCid,
messageType: DwnInterface.ProtocolsConfigure,
target: target,
});
return { status: reply.status };
});
}
}
//# sourceMappingURL=protocol.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/protocol.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,iDAAiD;;;;;;;;;;AAIjD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAiB3C;;;;;GAKG;AACH,MAAM,OAAO,QAAQ;IAUnB;;;;;;OAMG;IACH,YAAY,KAAgB,EAAE,yBAAsE,EAAE,QAA0B;QAC9H,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,0BAA0B,GAAG,yBAAyB,CAAC;IAC9D,CAAC;IAED;;;OAGG;IACH,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,UAAU,CAAC;IAC/D,CAAC;IAED;;;OAGG;IACH,MAAM;QACJ,OAAO,IAAI,CAAC,0BAA0B,CAAC;IACzC,CAAC;IAED;;;;;OAKG;IACG,IAAI,CAAC,MAAc;;YACvB,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC;gBACjD,MAAM,EAAQ,IAAI,CAAC,SAAS,CAAC,MAAM;gBACnC,UAAU,EAAI,IAAI,CAAC,SAAS,CAAC,UAAU;gBACvC,WAAW,EAAG,YAAY,CAAC,kBAAkB;gBAC7C,MAAM,EAAQ,MAAM;aACrB,CAAC,CAAC;YAEH,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC;QAClC,CAAC;KAAA;CACF"}
+602
View File
@@ -0,0 +1,602 @@
/**
* NOTE: Added reference types here to avoid a `pnpm` bug during build.
* https://github.com/TBD54566975/web5-js/pull/507
*/
/// <reference types="@tbd54566975/dwn-sdk-js" />
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { getPaginationCursor } from '@web5/agent';
import { DwnInterface } from '@web5/agent';
import { Convert, isEmptyObject, NodeStream, removeUndefinedProperties, Stream } from '@web5/common';
import { dataToBlob, SendCache } from './utils.js';
/**
* Record wrapper class with convenience methods to send and update,
* aside from manipulating and reading the record data.
*
* Note: The `messageTimestamp` of the most recent RecordsWrite message is
* logically equivalent to the date/time at which a Record was most
* recently modified. Since this Record class implementation is
* intended to simplify the developer experience of working with
* logical records (and not individual DWN messages) the
* `messageTimestamp` is mapped to `dateModified`.
*
* @beta
*/
/**
* The `Record` class encapsulates a single record's data and metadata, providing a more
* developer-friendly interface for working with Decentralized Web Node (DWN) records.
*
* Methods are provided to read, update, and manage the record's lifecycle, including writing to
* remote DWNs.
*
* @beta
*/
export class Record {
// Getters for immutable DWN Record properties.
/** Record's signatures attestation */
get attestation() { return this._attestation; }
/** Record's signatures attestation */
get authorization() { return this._authorization; }
/** DID that signed the record. */
get author() { return this._author; }
/** Record's context ID */
get contextId() { return this._contextId; }
/** Record's data format */
get dataFormat() { return this._descriptor.dataFormat; }
/** Record's creation date */
get dateCreated() { return this._descriptor.dateCreated; }
/** Record's encryption */
get encryption() { return this._encryption; }
/** Record's initial write if the record has been updated */
get initialWrite() { return this._initialWrite; }
/** Record's ID */
get id() { return this._recordId; }
/** Interface is always `Records` */
get interface() { return this._descriptor.interface; }
/** Method is always `Write` */
get method() { return this._descriptor.method; }
/** Record's parent ID */
get parentId() { return this._descriptor.parentId; }
/** Record's protocol */
get protocol() { return this._descriptor.protocol; }
/** Record's protocol path */
get protocolPath() { return this._descriptor.protocolPath; }
/** Role under which the author is writing the record */
get protocolRole() { return this._protocolRole; }
/** Record's recipient */
get recipient() { return this._descriptor.recipient; }
/** Record's schema */
get schema() { return this._descriptor.schema; }
// Getters for mutable DWN Record properties.
/** Record's CID */
get dataCid() { return this._descriptor.dataCid; }
/** Record's data size */
get dataSize() { return this._descriptor.dataSize; }
/** Record's modified date */
get dateModified() { return this._descriptor.messageTimestamp; }
/** Record's published date */
get datePublished() { return this._descriptor.datePublished; }
/** Record's published status */
get messageTimestamp() { return this._descriptor.messageTimestamp; }
/** Record's published status (true/false) */
get published() { return this._descriptor.published; }
/** Tags of the record */
get tags() { return this._descriptor.tags; }
/**
* Returns a copy of the raw `RecordsWriteMessage` that was used to create the current `Record` instance.
*/
get rawMessage() {
const message = JSON.parse(JSON.stringify({
contextId: this._contextId,
recordId: this._recordId,
descriptor: this._descriptor,
attestation: this._attestation,
authorization: this._authorization,
encryption: this._encryption,
}));
removeUndefinedProperties(message);
return message;
}
constructor(agent, options) {
this._agent = agent;
// Store the author DID that originally signed the message as a convenience for developers, so
// that they don't have to decode the signer's DID from the JWS.
this._author = options.author;
// Store the currently `connectedDid` so that subsequent message signing is done with the
// connected DID's keys and DWN requests target the connected DID's DWN.
this._connectedDid = options.connectedDid;
// If the record was queried or read from a remote DWN, the `remoteOrigin` DID will be
// defined. This value is used to send subsequent read requests to the same remote DWN in the
// event the record's data payload was too large to be returned in query results. or must be
// read again (e.g., if the data stream is consumed).
this._remoteOrigin = options.remoteOrigin;
// RecordsWriteMessage properties.
this._attestation = options.attestation;
this._authorization = options.authorization;
this._contextId = options.contextId;
this._descriptor = options.descriptor;
this._encryption = options.encryption;
this._initialWrite = options.initialWrite;
this._recordId = options.recordId;
this._protocolRole = options.protocolRole;
if (options.encodedData) {
// If `encodedData` is set, then it is expected that:
// type is Blob if the Record object was instantiated by dwn.records.create()/write().
// type is Base64 URL encoded string if the Record object was instantiated by dwn.records.query().
// If it is a string, we need to Base64 URL decode to bytes and instantiate a Blob.
this._encodedData = (typeof options.encodedData === 'string') ?
new Blob([Convert.base64Url(options.encodedData).toUint8Array()], { type: this.dataFormat }) :
options.encodedData;
}
if (options.data) {
// If the record was created from a RecordsRead reply then it will have a `data` property.
// If the `data` property is a web ReadableStream, convert it to a Node.js Readable.
this._readableStream = Stream.isReadableStream(options.data) ?
NodeStream.fromWebReadable({ readableStream: options.data }) :
options.data;
}
}
/**
* Returns the data of the current record.
* If the record data is not available, it attempts to fetch the data from the DWN.
* @returns a data stream with convenience methods such as `blob()`, `json()`, `text()`, and `stream()`, similar to the fetch API response
* @throws `Error` if the record has already been deleted.
*
* @beta
*/
get data() {
const self = this; // Capture the context of the `Record` instance.
const dataObj = {
/**
* Returns the data of the current record as a `Blob`.
*
* @returns A promise that resolves to a Blob containing the record's data.
* @throws If the record data is not available or cannot be converted to a `Blob`.
*
* @beta
*/
blob() {
return __awaiter(this, void 0, void 0, function* () {
return new Blob([yield NodeStream.consumeToBytes({ readable: yield this.stream() })], { type: self.dataFormat });
});
},
/**
* Returns the data of the current record as a `Uint8Array`.
*
* @returns A Promise that resolves to a `Uint8Array` containing the record's data bytes.
* @throws If the record data is not available or cannot be converted to a byte array.
*
* @beta
*/
bytes() {
return __awaiter(this, void 0, void 0, function* () {
return yield NodeStream.consumeToBytes({ readable: yield this.stream() });
});
},
/**
* Parses the data of the current record as JSON and returns it as a JavaScript object.
*
* @returns A Promise that resolves to a JavaScript object parsed from the record's JSON data.
* @throws If the record data is not available, not in JSON format, or cannot be parsed.
*
* @beta
*/
json() {
return __awaiter(this, void 0, void 0, function* () {
return yield NodeStream.consumeToJson({ readable: yield this.stream() });
});
},
/**
* Returns the data of the current record as a `string`.
*
* @returns A promise that resolves to a `string` containing the record's text data.
* @throws If the record data is not available or cannot be converted to text.
*
* @beta
*/
text() {
return __awaiter(this, void 0, void 0, function* () {
return yield NodeStream.consumeToText({ readable: yield this.stream() });
});
},
/**
* Provides a `Readable` stream containing the record's data.
*
* @returns A promise that resolves to a Node.js `Readable` stream of the record's data.
* @throws If the record data is not available in-memory and cannot be fetched.
*
* @beta
*/
stream() {
return __awaiter(this, void 0, void 0, function* () {
if (self._encodedData) {
/** If `encodedData` is set, it indicates that the Record was instantiated by
* `dwn.records.create()`/`dwn.records.write()` or the record's data payload was small
* enough to be returned in `dwn.records.query()` results. In either case, the data is
* already available in-memory and can be returned as a Node.js `Readable` stream. */
self._readableStream = NodeStream.fromWebReadable({ readableStream: self._encodedData.stream() });
}
else if (!NodeStream.isReadable({ readable: self._readableStream })) {
/** If the data stream for this `Record` instance has already been partially or fully
* consumed, then the data must be fetched again from either: */
self._readableStream = self._remoteOrigin ?
// A. ...a remote DWN if the record was originally queried from a remote DWN.
yield self.readRecordData({ target: self._remoteOrigin, isRemote: true }) :
// B. ...a local DWN if the record was originally queried from the local DWN.
yield self.readRecordData({ target: self._connectedDid, isRemote: false });
}
if (!self._readableStream) {
throw new Error('Record data is not available.');
}
return self._readableStream;
});
},
/**
* Attaches callbacks for the resolution and/or rejection of the `Promise` returned by
* `stream()`.
*
* This method is a proxy to the `then` method of the `Promise` returned by `stream()`,
* allowing for a seamless integration with promise-based workflows.
* @param onFulfilled - A function to asynchronously execute when the `stream()` promise
* becomes fulfilled.
* @param onRejected - A function to asynchronously execute when the `stream()` promise
* becomes rejected.
* @returns A `Promise` for the completion of which ever callback is executed.
*/
then(onFulfilled, onRejected) {
return this.stream().then(onFulfilled, onRejected);
},
/**
* Attaches a rejection handler callback to the `Promise` returned by the `stream()` method.
* This method is a shorthand for `.then(undefined, onRejected)`, specifically designed for handling
* rejection cases in the promise chain initiated by accessing the record's data. It ensures that
* errors during data retrieval or processing can be caught and handled appropriately.
*
* @param onRejected - A function to asynchronously execute when the `stream()` promise
* becomes rejected.
* @returns A `Promise` that resolves to the value of the callback if it is called, or to its
* original fulfillment value if the promise is instead fulfilled.
*/
catch(onRejected) {
return this.stream().catch(onRejected);
}
};
return dataObj;
}
/**
* Stores the current record state as well as any initial write to the owner's DWN.
*
* @param importRecord - if true, the record will signed by the owner before storing it to the owner's DWN. Defaults to false.
* @returns the status of the store request
*
* @beta
*/
store(importRecord = false) {
return __awaiter(this, void 0, void 0, function* () {
// if we are importing the record we sign it as the owner
return this.processRecord({ signAsOwner: importRecord, store: true });
});
}
/**
* Signs the current record state as well as any initial write and optionally stores it to the owner's DWN.
* This is useful when importing a record that was signed by someone else into your own DWN.
*
* @param store - if true, the record will be stored to the owner's DWN after signing. Defaults to true.
* @returns the status of the import request
*
* @beta
*/
import(store = true) {
return __awaiter(this, void 0, void 0, function* () {
return this.processRecord({ store, signAsOwner: true });
});
}
/**
* Send the current record to a remote DWN by specifying their DID
* If no DID is specified, the target is assumed to be the owner (connectedDID).
* If an initial write is present and the Record class send cache has no awareness of it, the initial write is sent first
* (vs waiting for the regular DWN sync)
*
* @param target - the optional DID to send the record to, if none is set it is sent to the connectedDid
* @returns the status of the send record request
* @throws `Error` if the record has already been deleted.
*
* @beta
*/
send(target) {
return __awaiter(this, void 0, void 0, function* () {
const initialWrite = this._initialWrite;
target !== null && target !== void 0 ? target : (target = this._connectedDid);
// Is there an initial write? Do we know if we've already sent it to this target?
if (initialWrite && !Record._sendCache.check(this._recordId, target)) {
// We do have an initial write, so prepare it for sending to the target.
const rawMessage = Object.assign({}, initialWrite);
removeUndefinedProperties(rawMessage);
// Send the initial write to the target.
yield this._agent.sendDwnRequest({
messageType: DwnInterface.RecordsWrite,
author: this._connectedDid,
target: target,
rawMessage
});
// Set the cache to maintain awareness that we don't need to send the initial write next time.
Record._sendCache.set(this._recordId, target);
}
// Send the current/latest state to the target.
const { reply } = yield this._agent.sendDwnRequest({
messageType: DwnInterface.RecordsWrite,
author: this._connectedDid,
dataStream: yield this.data.blob(),
target: target,
rawMessage: Object.assign({}, this.rawMessage)
});
return reply;
});
}
/**
* Returns a JSON representation of the Record instance.
* It's called by `JSON.stringify(...)` automatically.
*/
toJSON() {
return {
attestation: this.attestation,
author: this.author,
authorization: this.authorization,
contextId: this.contextId,
dataCid: this.dataCid,
dataFormat: this.dataFormat,
dataSize: this.dataSize,
dateCreated: this.dateCreated,
messageTimestamp: this.dateModified,
datePublished: this.datePublished,
encryption: this.encryption,
interface: this.interface,
method: this.method,
parentId: this.parentId,
protocol: this.protocol,
protocolPath: this.protocolPath,
protocolRole: this.protocolRole,
published: this.published,
recipient: this.recipient,
recordId: this.id,
schema: this.schema,
tags: this.tags,
};
}
/**
* Convenience method to return the string representation of the Record instance.
* Called automatically in string concatenation, String() type conversion, and template literals.
*/
toString() {
let str = `Record: {\n`;
str += ` ID: ${this.id}\n`;
str += this.contextId ? ` Context ID: ${this.contextId}\n` : '';
str += this.protocol ? ` Protocol: ${this.protocol}\n` : '';
str += this.schema ? ` Schema: ${this.schema}\n` : '';
str += ` Data CID: ${this.dataCid}\n`;
str += ` Data Format: ${this.dataFormat}\n`;
str += ` Data Size: ${this.dataSize}\n`;
str += ` Created: ${this.dateCreated}\n`;
str += ` Modified: ${this.dateModified}\n`;
str += `}`;
return str;
}
/**
* Returns a pagination cursor for the current record given a sort order.
*
* @param sort the sort order to use for the pagination cursor.
* @returns A promise that resolves to a pagination cursor for the current record.
*/
paginationCursor(sort) {
return __awaiter(this, void 0, void 0, function* () {
return getPaginationCursor(this.rawMessage, sort);
});
}
/**
* Update the current record on the DWN.
* @param params - Parameters to update the record.
* @returns the status of the update request
* @throws `Error` if the record has already been deleted.
*
* @beta
*/
update(_a) {
var { dateModified, data } = _a, params = __rest(_a, ["dateModified", "data"]);
return __awaiter(this, void 0, void 0, function* () {
// if there is a parentId, we remove it from the descriptor and set a parentContextId
const _b = this._descriptor, { parentId } = _b, descriptor = __rest(_b, ["parentId"]);
const parentContextId = parentId ? this._contextId.split('/').slice(0, -1).join('/') : undefined;
// Begin assembling the update message.
let updateMessage = Object.assign(Object.assign(Object.assign({}, descriptor), params), { parentContextId, messageTimestamp: dateModified, recordId: this._recordId });
// NOTE: The original Record's tags are copied to the update message, so that the tags are not lost.
// However if a user passes new tags in the `RecordUpdateParams` object, they will overwrite the original tags.
// 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.
if (isEmptyObject(updateMessage.tags) || updateMessage.tags === null) {
delete updateMessage.tags;
}
let dataBlob;
if (data !== undefined) {
// If `data` is being updated then `dataCid` and `dataSize` must be undefined and the `data`
// value must be converted to a Blob and later passed as a top-level property to
// `agent.processDwnRequest()`.
delete updateMessage.dataCid;
delete updateMessage.dataSize;
({ dataBlob } = dataToBlob(data, updateMessage.dataFormat));
}
// Throw an error if an attempt is made to modify immutable properties.
// Note: `data` and `dateModified` have already been handled.
const mutableDescriptorProperties = new Set(['data', 'dataCid', 'dataSize', 'datePublished', 'messageTimestamp', 'published', 'tags']);
Record.verifyPermittedMutation(Object.keys(params), mutableDescriptorProperties);
// If `published` is set to false, ensure that `datePublished` is undefined. Otherwise, DWN SDK's schema validation
// will throw an error if `published` is false but `datePublished` is set.
if (params.published === false && updateMessage.datePublished !== undefined) {
delete updateMessage.datePublished;
}
const agentResponse = yield this._agent.processDwnRequest({
author: this._connectedDid,
dataStream: dataBlob,
messageParams: Object.assign({}, updateMessage),
messageType: DwnInterface.RecordsWrite,
target: this._connectedDid,
});
const { message, reply: { status } } = agentResponse;
const responseMessage = message;
if (200 <= status.code && status.code <= 299) {
// copy the original raw message to the initial write before we update the values.
if (!this._initialWrite) {
this._initialWrite = Object.assign({}, this.rawMessage);
}
// Only update the local Record instance mutable properties if the record was successfully (over)written.
this._authorization = responseMessage.authorization;
this._protocolRole = params.protocolRole;
mutableDescriptorProperties.forEach(property => {
this._descriptor[property] = responseMessage.descriptor[property];
});
// Cache data.
if (data !== undefined) {
this._encodedData = dataBlob;
}
}
return { status };
});
}
/**
* Handles the various conditions around there being an initial write, whether to store initial/current state,
* and whether to add an owner signature to the initial write to enable storage when protocol rules require it.
*/
processRecord({ store, signAsOwner }) {
return __awaiter(this, void 0, void 0, function* () {
// if there is an initial write and we haven't already processed it, we first process it and marked it as such.
if (this._initialWrite && ((signAsOwner && !this._initialWriteSigned) || (store && !this._initialWriteStored))) {
const initialWriteRequest = {
messageType: DwnInterface.RecordsWrite,
rawMessage: this.initialWrite,
author: this._connectedDid,
target: this._connectedDid,
signAsOwner,
store,
};
// Process the prepared initial write, with the options set for storing and/or signing as the owner.
const agentResponse = yield this._agent.processDwnRequest(initialWriteRequest);
const { message, reply: { status } } = agentResponse;
const responseMessage = message;
// If we are signing as owner, make sure to update the initial write's authorization, because now it will have the owner's signature on it
// set the stored or signed status to true so we don't process it again.
if (200 <= status.code && status.code <= 299) {
if (store)
this._initialWriteStored = true;
if (signAsOwner) {
this._initialWriteSigned = true;
this.initialWrite.authorization = responseMessage.authorization;
}
}
}
// Now that we've processed a potential initial write, we can process the current record state.
const requestOptions = {
messageType: DwnInterface.RecordsWrite,
rawMessage: this.rawMessage,
author: this._connectedDid,
target: this._connectedDid,
dataStream: yield this.data.blob(),
signAsOwner,
store,
};
const agentResponse = yield this._agent.processDwnRequest(requestOptions);
const { message, reply: { status } } = agentResponse;
const responseMessage = message;
if (200 <= status.code && status.code <= 299) {
// 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.
if (signAsOwner)
this._authorization = responseMessage.authorization;
}
return { status };
});
}
/**
* Fetches the record's data from the specified DWN.
*
* This private method is called when the record data is not available in-memory
* and needs to be fetched from either a local or a remote DWN.
* It makes a read request to the specified DWN and processes the response to provide
* a Node.js `Readable` stream of the record's data.
*
* @param params - Parameters for fetching the record's data.
* @param params.target - The DID of the DWN to fetch the data from.
* @param params.isRemote - Indicates whether the target DWN is a remote node.
* @returns A Promise that resolves to a Node.js `Readable` stream of the record's data.
* @throws If there is an error while fetching or processing the data from the DWN.
*
* @beta
*/
readRecordData({ target, isRemote }) {
return __awaiter(this, void 0, void 0, function* () {
const readRequest = {
author: this._connectedDid,
messageParams: { filter: { recordId: this.id } },
messageType: DwnInterface.RecordsRead,
target,
};
const agentResponsePromise = isRemote ?
this._agent.sendDwnRequest(readRequest) :
this._agent.processDwnRequest(readRequest);
try {
const { reply: { record } } = yield agentResponsePromise;
const dataStream = record.data;
// If the data stream is a web ReadableStream, convert it to a Node.js Readable.
const nodeReadable = Stream.isReadableStream(dataStream) ?
NodeStream.fromWebReadable({ readableStream: dataStream }) :
dataStream;
return nodeReadable;
}
catch (error) {
throw new Error(`Error encountered while attempting to read data: ${error.message}`);
}
});
}
/**
* Verifies if the properties to be mutated are mutable.
*
* This private method is used to ensure that only mutable properties of the `Record` instance
* are being changed. It checks whether the properties specified for mutation are among the
* set of properties that are allowed to be modified. If any of the properties to be mutated
* are not in the set of mutable properties, the method throws an error.
*
* @param propertiesToMutate - An iterable of property names that are intended to be mutated.
* @param mutableDescriptorProperties - A set of property names that are allowed to be mutated.
*
* @throws If any of the properties in `propertiesToMutate` are not in `mutableDescriptorProperties`.
*
* @beta
*/
static verifyPermittedMutation(propertiesToMutate, mutableDescriptorProperties) {
for (const property of propertiesToMutate) {
if (!mutableDescriptorProperties.has(property)) {
throw new Error(`${property} is an immutable property. Its value cannot be changed.`);
}
}
}
}
/**
* Cache to minimize the amount of redundant two-phase commits we do in store() and send()
* Retains awareness of the last 100 records stored/sent for up to 100 target DIDs each.
*/
Record._sendCache = SendCache;
//# sourceMappingURL=record.js.map
File diff suppressed because one or more lines are too long
+65
View File
@@ -0,0 +1,65 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { UniversalResolver, DidDht, DidWeb } from '@web5/dids';
const workerSelf = self;
const DidResolver = new UniversalResolver({ didResolvers: [DidDht, DidWeb] });
const didUrlRegex = /^https?:\/\/dweb\/(([^/]+)\/.*)?$/;
const httpToHttpsRegex = /^http:/;
const trailingSlashRegex = /\/$/;
workerSelf.addEventListener('fetch', event => {
const match = event.request.url.match(didUrlRegex);
if (match) {
event.respondWith((() => __awaiter(void 0, void 0, void 0, function* () {
const normalizedUrl = event.request.url.replace(httpToHttpsRegex, 'https:').replace(trailingSlashRegex, '');
const cachedResponse = yield caches.open('drl').then(cache => cache.match(normalizedUrl));
return cachedResponse || handleEvent(event, match[2], match[1]);
}))());
}
});
function handleEvent(event, did, route) {
return __awaiter(this, void 0, void 0, function* () {
try {
const result = yield DidResolver.resolve(did);
return yield fetchResource(event, result.didDocument, route);
}
catch (error) {
if (error instanceof Response) {
return error;
}
console.log(`Error in DID URL fetch: ${error}`);
return new Response('DID URL fetch error', { status: 500 });
}
});
}
function fetchResource(event, ddo, route) {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
let endpoints = (_b = (_a = ddo === null || ddo === void 0 ? void 0 : ddo.service) === null || _a === void 0 ? void 0 : _a.find(service => service.type === 'DecentralizedWebNode')) === null || _b === void 0 ? void 0 : _b.serviceEndpoint;
endpoints = (Array.isArray(endpoints) ? endpoints : [endpoints]).filter(url => url.startsWith('http'));
if (!(endpoints === null || endpoints === void 0 ? void 0 : endpoints.length)) {
throw new Response('DWeb Node resolution failed: no valid endpoints found.', { status: 530 });
}
for (const endpoint of endpoints) {
try {
const response = yield fetch(`${endpoint.replace(trailingSlashRegex, '')}/${route}`, { headers: event.request.headers });
if (response.ok) {
return response;
}
console.log(`DWN endpoint error: ${response.status}`);
return new Response('DWeb Node request failed', { status: response.status });
}
catch (error) {
console.log(`DWN endpoint error: ${error}`);
return new Response('DWeb Node request failed: ' + error, { status: 500 });
}
}
});
}
//# sourceMappingURL=service-worker.js.map
@@ -0,0 +1 @@
{"version":3,"file":"service-worker.js","sourceRoot":"","sources":["../../src/service-worker.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAE/D,MAAM,UAAU,GAAG,IAAW,CAAC;AAC/B,MAAM,WAAW,GAAG,IAAI,iBAAiB,CAAC,EAAE,YAAY,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;AAC9E,MAAM,WAAW,GAAG,mCAAmC,CAAC;AACxD,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AAClC,MAAM,kBAAkB,GAAG,KAAK,CAAC;AAEjC,UAAU,CAAC,gBAAgB,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE;IAC3C,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACnD,IAAI,KAAK,EAAE;QACT,KAAK,CAAC,WAAW,CAAC,CAAC,GAAS,EAAE;YAC5B,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,gBAAgB,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,EAAE,CAAC,CAAC;YAC5G,MAAM,cAAc,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC;YAC1F,OAAO,cAAc,IAAI,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAClE,CAAC,CAAA,CAAC,EAAE,CAAC,CAAC;KACP;AACH,CAAC,CAA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AG,QAAQ,CAAC,OAAO,CAAC,kBAAkB,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;gBACzH,IAAI,QAAQ,CAAC,EAAE,EAAE;oBACf,OAAO,QAAQ,CAAC;iBACjB;gBACD,OAAO,CAAC,GAAG,CAAC,uBAAuB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;gBACtD,OAAO,IAAI,QAAQ,CAAC,0BAA0B,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;aAC9E;YACD,OAAO,KAAK,EAAE;gBACZ,OAAO,CAAC,GAAG,CAAC,uBAAuB,KAAK,EAAE,CAAC,CAAC;gBAC5C,OAAO,IAAI,QAAQ,CAAC,4BAA4B,GAAG,KAAK,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;aAC5E;SACF;;CACF"}
+62
View File
@@ -0,0 +1,62 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { utils as didUtils } from '@web5/dids';
/**
* Dynamically selects up to 2 DWN endpoints that are provided
* by default during the Tech Preview period.
*
* @beta
*/
export function getTechPreviewDwnEndpoints() {
return __awaiter(this, void 0, void 0, function* () {
let response;
try {
response = yield fetch('https://dwn.tbddev.org/.well-known/did.json');
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
}
}
catch (error) {
console.warn('failed to get tech preview dwn endpoints:', error.message);
return [];
}
const didDocument = yield response.json();
const [dwnService] = didUtils.getServices({ didDocument, id: '#dwn', type: 'DecentralizedWebNode' });
// allocate up to 2 nodes for a user.
const techPreviewEndpoints = new Set();
if ('serviceEndpoint' in dwnService
&& !Array.isArray(dwnService.serviceEndpoint)
&& typeof dwnService.serviceEndpoint !== 'string'
&& Array.isArray(dwnService.serviceEndpoint.nodes)) {
const dwnUrls = dwnService.serviceEndpoint.nodes;
const numNodesToAllocate = Math.min(dwnUrls.length, 2);
for (let attempts = 0; attempts < dwnUrls.length && techPreviewEndpoints.size < numNodesToAllocate; attempts += 1) {
const nodeIdx = getRandomInt(0, dwnUrls.length);
const dwnUrl = dwnUrls[nodeIdx];
try {
const healthCheck = yield fetch(`${dwnUrl}/health`);
if (healthCheck.ok) {
techPreviewEndpoints.add(dwnUrl);
}
}
catch (error) {
// Ignore healthcheck failures and try the next node.
}
}
}
return Array.from(techPreviewEndpoints);
});
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
//# sourceMappingURL=tech-preview.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"tech-preview.js","sourceRoot":"","sources":["../../src/tech-preview.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,KAAK,IAAI,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE/C;;;;;GAKG;AACH,MAAM,UAAgB,0BAA0B;;QAC9C,IAAI,QAAkB,CAAC;QACvB,IAAI;YACF,QAAQ,GAAG,MAAM,KAAK,CAAC,6CAA6C,CAAC,CAAC;YACtE,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;gBAChB,MAAM,IAAI,KAAK,CAAC,eAAe,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;aAC1E;SACF;QAAC,OAAM,KAAU,EAAE;YAClB,OAAO,CAAC,IAAI,CAAC,2CAA2C,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;YACzE,OAAO,E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AAC;IAC1C,CAAC;CAAA;AAED,SAAS,YAAY,CAAC,GAAG,EAAE,GAAG;IAC5B,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACrB,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACtB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;AACvD,CAAC"}
+120
View File
@@ -0,0 +1,120 @@
import { Convert, universalTypeOf } from '@web5/common';
/**
* Converts various data types to a `Blob` object, automatically detecting the data type or using
* the specified `dataFormat` to set the Blob's MIME type.
*
* This function supports plain text, JSON objects, binary data (Uint8Array, ArrayBuffer), and Blob
* inputs and will attempt to automatically detect the type of the data if `dataFormat` is not
* explicitly provided.
*
* @beta
*
* @example
* ```ts
* // Convert a JSON object to a Blob
* const { dataBlob, dataFormat } = dataToBlob({ key: 'value' }, 'application/json');
*
* // Convert a plain text string to a Blob without specifying dataFormat
* const { dataBlob: textBlob } = dataToBlob('Hello, world!');
*
* // Convert binary data to a Blob
* const binaryData = new Uint8Array([0, 1, 2, 3]);
* const { dataBlob: binaryBlob } = dataToBlob(binaryData);
* ```
*
* @param data - The data to be converted into a `Blob`. This can be a string, an object, binary
* data (Uint8Array or ArrayBuffer), or a Blob.
* @param dataFormat - An optional MIME type string that specifies the format of the data. Common
* types include 'text/plain' for string data, 'application/json' for JSON
* objects, and 'application/octet-stream' for binary data. If not provided, the
* function will attempt to detect the format based on the data type or default
* to 'application/octet-stream'.
* @returns An object containing the `dataBlob`, a Blob representation of the input data, and
* `dataFormat`, the MIME type of the data as determined by the function or specified by the caller.
* @throws An error if the data type is not supported or cannot be converted to a Blob.
*/
export function dataToBlob(data, dataFormat) {
let dataBlob;
// Check for Object or String, and if neither, assume bytes.
const detectedType = universalTypeOf(data);
if (dataFormat === 'text/plain' || detectedType === 'String') {
dataBlob = new Blob([data], { type: 'text/plain' });
}
else if (dataFormat === 'application/json' || detectedType === 'Object') {
const dataBytes = Convert.object(data).toUint8Array();
dataBlob = new Blob([dataBytes], { type: 'application/json' });
}
else if (detectedType === 'Uint8Array' || detectedType === 'ArrayBuffer') {
dataBlob = new Blob([data], { type: 'application/octet-stream' });
}
else if (detectedType === 'Blob') {
dataBlob = data;
}
else {
throw new Error('data type not supported.');
}
dataFormat = dataFormat || dataBlob.type || 'application/octet-stream';
return { dataBlob, dataFormat };
}
/**
* The `SendCache` class provides a static caching mechanism to optimize the process of sending
* records to remote DWN targets by minimizing redundant sends.
*
* It maintains a cache of record IDs and their associated target DIDs to which they have been sent.
* This helps in avoiding unnecessary network requests and ensures efficient data synchronization
* across Decentralized Web Nodes (DWNs).
*
* The cache employs a simple eviction policy to maintain a manageable size, ensuring that the cache
* does not grow indefinitely and consume excessive memory resources.
*
* @beta
*/
export class SendCache {
/**
* Checks if a given record ID has been sent to a specified target DID. This method is used to
* determine whether a send operation is necessary or if it can be skipped to avoid redundancy.
*
* @param id - The unique identifier of the record.
* @param target - The DID of the target to check against.
* @returns A boolean indicating whether the record has been sent to the target.
*/
static check(id, target) {
let targetCache = SendCache.cache.get(id);
return targetCache ? targetCache.has(target) : false;
}
/**
* Adds or updates an entry in the cache for a given record ID and target DID. If the cache
* exceeds its size limit, the oldest entry is removed. This method ensures that the cache
* reflects the most recent sends.
*
* @param id - The unique identifier of the record.
* @param target - The DID of the target to which the record has been sent.
*/
static set(id, target) {
let targetCache = SendCache.cache.get(id) || new Set();
SendCache.cache.delete(id);
SendCache.cache.set(id, targetCache);
if (this.cache.size > SendCache.sendCacheLimit) {
const firstRecord = SendCache.cache.keys().next().value;
SendCache.cache.delete(firstRecord);
}
targetCache.delete(target);
targetCache.add(target);
if (targetCache.size > SendCache.sendCacheLimit) {
const firstTarget = targetCache.keys().next().value;
targetCache.delete(firstTarget);
}
}
}
/**
* A private static map that serves as the core storage mechanism for the cache. It maps record
* IDs to a set of target DIDs, indicating which records have been sent to which targets.
*/
SendCache.cache = new Map();
/**
* The maximum number of entries allowed in the cache. Once this limit is exceeded, the oldest
* entries are evicted to make room for new ones. This limit applies both to the number of records
* and the number of targets per record.
*/
SendCache.sendCacheLimit = 100;
//# sourceMappingURL=utils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,UAAU,UAAU,CAAC,IAAS,EAAE,UAAmB;IAMvD,IAAI,QAAc,CAAC;IAEnB,4DAA4D;IAC5D,MAAM,YAAY,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IAC3C,IAAI,UAAU,KAAK,YAAY,IAAI,YAAY,KAAK,QAAQ,EAAE;QAC5D,QAAQ,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;KACrD;SAAM,IAAI,UAAU,KAAK,kBAAkB,IAAI,YAAY,KAAK,QAAQ,EAAE;QACzE,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,CAAC;QACtD,QAAQ,GAAG,IAAI,IAAI,CAAC,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC,CAAC;KAChE;SAAM,IAAI,YAAY,KAAK,YAAY,IAAI,YAAY,KAAK,aAAa,EAAE;QAC1E,QAAQ,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,0BAA0B,EAAE,CAAC,CAAC;KACnE;SAAM,IAAI,YAAY,KAAK,MAAM,EAAE;QAClC,QAAQ,GAAG,IAAI,CAAC;KACjB;SAAM;QACL,MAAM,IAAI,KAAK,CAAC,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AC,KAAK,CAAC;YACpD,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;SACjC;IACH,CAAC;;AAhDD;;;EAGE;AACa,eAAK,GAAG,IAAI,GAAG,EAAuB,CAAC;AAEtD;;;;GAIG;AACY,wBAAc,GAAG,GAAG,CAAC"}
+30
View File
@@ -0,0 +1,30 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
/**
* The VC API is used to issue, present and verify VCs
*
* @beta
*/
export class VcApi {
constructor(options) {
this.agent = options.agent;
this.connectedDid = options.connectedDid;
}
/**
* Issues a VC (Not implemented yet)
*/
create() {
return __awaiter(this, void 0, void 0, function* () {
// TODO: implement
throw new Error('Not implemented.');
});
}
}
//# sourceMappingURL=vc-api.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"vc-api.js","sourceRoot":"","sources":["../../src/vc-api.ts"],"names":[],"mappings":";;;;;;;;;AAEA;;;;GAIG;AACH,MAAM,OAAO,KAAK;IAUhB,YAAY,OAAmD;QAC7D,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAC3B,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3C,CAAC;IAED;;OAEG;IACG,MAAM;;YACV,kBAAkB;YAClB,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;QACtC,CAAC;KAAA;CACF"}
+28
View File
@@ -0,0 +1,28 @@
/**
* Installs the DWeb networking features in the current environment.
*/
export function installNetworkingFeatures(path) {
var _a;
const workerSelf = self;
try {
if (typeof ServiceWorkerGlobalScope !== 'undefined' && workerSelf instanceof ServiceWorkerGlobalScope) {
// Dynamically import service worker code only if we're in a Service Worker context
import('./service-worker.js').catch(error => {
console.error('Error loading service worker module:', error);
});
}
else if ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.serviceWorker) {
if (path)
navigator.serviceWorker.register(path).catch(error => {
console.error('DWeb networking feature installation failed: ', error);
});
}
else {
throw new Error('DWeb networking features are not available for install in this environment');
}
}
catch (error) {
console.error('Error in installing networking features:', error);
}
}
//# sourceMappingURL=web-features.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"web-features.js","sourceRoot":"","sources":["../../src/web-features.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,UAAU,yBAAyB,CAAC,IAAY;;IACpD,MAAM,UAAU,GAAG,IAAW,CAAC;IAE/B,IAAI;QACF,IAAI,OAAO,wBAAwB,KAAK,WAAW,IAAI,UAAU,YAAY,wBAAwB,EAAE;YACrG,mFAAmF;YACnF,MAAM,CAAC,qBAAqB,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;gBAC1C,OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,KAAK,CAAC,CAAC;YAC/D,CAAC,CAAC,CAAC;SACJ;aACI,IAAI,MAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,SAAS,0CAAE,aAAa,EAAE;YAC7C,IAAI,IAAI;gBAAE,SAAS,CAAC,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;oBAC7D,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,KAAK,CAAC,CAAC;gBACxE,CAAC,CAAC,CAAC;SACJ;aACI;YACH,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;SAC/F;KACF;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,CAAC,KAAK,CAAC,0CAA0C,EAAE,KAAK,CAAC,CAAC;KAClE;AACH,CAAC"}
+127
View File
@@ -0,0 +1,127 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { Web5UserAgent } from '@web5/user-agent';
import { VcApi } from './vc-api.js';
import { DwnApi } from './dwn-api.js';
import { DidApi } from './did-api.js';
import { getTechPreviewDwnEndpoints } from './tech-preview.js';
/**
* The main Web5 API interface. It manages the creation of a DID if needed, the connection to the
* local DWN and all the web5 main foundational APIs such as VC, syncing, etc.
*/
export class Web5 {
constructor({ agent, connectedDid }) {
this.agent = agent;
this.connectedDid = connectedDid;
this.did = new DidApi({ agent, connectedDid });
this.dwn = new DwnApi({ agent, connectedDid });
this.vc = new VcApi({ agent, connectedDid });
}
/**
* Connects to a {@link Web5Agent}. Defaults to creating a local {@link Web5UserAgent} if one
* isn't provided.
*
* @param options - Optional overrides that can be provided when calling {@link Web5.connect}.
* @returns A promise that resolves to a {@link Web5} instance and the connected DID.
*/
static connect({ agent, agentVault, connectedDid, password, recoveryPhrase, sync, techPreview } = {}) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (agent === undefined) {
// A custom Web5Agent implementation was not specified, so use default managed user agent.
const userAgent = yield Web5UserAgent.create({ agentVault });
agent = userAgent;
// Warn the developer and application user of the security risks of using a static password.
if (password === undefined) {
password = 'insecure-static-phrase';
console.warn('%cSECURITY WARNING:%c ' +
'You have not set a password, which defaults to a static, guessable value. ' +
'This significantly compromises the security of your data. ' +
'Please configure a secure, unique password.', 'font-weight: bold; color: red;', 'font-weight: normal; color: inherit;');
}
// Initialize, if necessary, and start the agent.
if (yield userAgent.firstLaunch()) {
recoveryPhrase = yield userAgent.initialize({ password, recoveryPhrase });
}
yield userAgent.start({ password });
// TODO: Replace stubbed connection attempt once Connect Protocol has been implemented.
// Attempt to Connect to localhost agent or via Connect Server.
// userAgent.connect();
const notConnected = true;
if ( /* !userAgent.isConnected() */notConnected) {
// Connect attempt failed or was rejected so fallback to local user agent.
let identity;
// Query the Agent's DWN tenant for identity records.
const identities = yield userAgent.identity.list();
// If an existing identity is not found found, create a new one.
const existingIdentityCount = identities.length;
if (existingIdentityCount === 0) {
// Use the specified DWN endpoints or get default tech preview hosted nodes.
const serviceEndpointNodes = (_a = techPreview === null || techPreview === void 0 ? void 0 : techPreview.dwnEndpoints) !== null && _a !== void 0 ? _a : yield getTechPreviewDwnEndpoints();
// Generate a new Identity for the end-user.
identity = yield userAgent.identity.create({
didMethod: 'dht',
metadata: { name: 'Default' },
didOptions: {
services: [
{
id: 'dwn',
type: 'DecentralizedWebNode',
serviceEndpoint: serviceEndpointNodes,
enc: '#enc',
sig: '#sig',
}
],
verificationMethods: [
{
algorithm: 'Ed25519',
id: 'sig',
purposes: ['assertionMethod', 'authentication']
},
{
algorithm: 'secp256k1',
id: 'enc',
purposes: ['keyAgreement']
}
]
}
});
// The User Agent will manage the Identity, which ensures it will be available on future
// sessions.
yield userAgent.identity.manage({ portableIdentity: yield identity.export() });
}
else if (existingIdentityCount === 1) {
// An existing identity was found in the User Agent's tenant.
identity = identities[0];
}
else {
throw new Error(`connect() failed due to unexpected state: Expected 1 but found ${existingIdentityCount} stored identities.`);
}
// Set the stored identity as the connected DID.
connectedDid = identity.did.uri;
}
// Enable sync, unless explicitly disabled.
if (sync !== 'off') {
// First, register the user identity for sync.
yield userAgent.sync.registerIdentity({ did: connectedDid });
// Enable sync using the specified interval or default.
sync !== null && sync !== void 0 ? sync : (sync = '2m');
userAgent.sync.startSync({ interval: sync })
.catch((error) => {
console.error(`Sync failed: ${error}`);
});
}
}
const web5 = new Web5({ agent, connectedDid });
return { web5, did: connectedDid, recoveryPhrase };
});
}
}
//# sourceMappingURL=web5.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"web5.js","sourceRoot":"","sources":["../../src/web5.ts"],"names":[],"mappings":";;;;;;;;;AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAsH/D;;;GAGG;AACH,MAAM,OAAO,IAAI;IAmBf,YAAY,EAAE,KAAK,EAAE,YAAY,EAAc;QAC7C,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,GAAG,GAAG,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;QAC/C,IAAI,CAAC,GAAG,GAAG,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;QAC/C,IAAI,CAAC,EAAE,GAAG,IAAI,KAAK,CAAC,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAO,OAAO,CAAC,EACnB,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,WAAW,KACtD,EAAE;;;YACxB,IAAI,KAAK,KAAK,SAAS,EAAE;gBACvB,0FAA0F;gBAC1F,MAAM,SAAS,GAAG,MAAM,aAAa,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC;gBAC7D,KAAK,GAAG,SAAS,CAAC;gBAElB,4FAA4F;gBAC5F,IAAI,QAAQ,KAAK,SAAS,EAAE;oBAC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