@ddd-qc/cell-proxy 0.9.0

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.
package/LICENSE ADDED
@@ -0,0 +1,160 @@
1
+ # Cryptographic Autonomy License version 1.0
2
+
3
+ *This Cryptographic Autonomy License (the “License”) applies to any Work whose owner has marked it with any of the following notices:*
4
+
5
+ *“Licensed under the Cryptographic Autonomy License version 1.0,” or*
6
+
7
+ *“SPDX-License-Identifier: CAL-1.0,” or*
8
+
9
+ *“Licensed under the Cryptographic Autonomy License version 1.0, with Combined Work Exception,” or*
10
+
11
+ *“SPDX-License-Identifier: CAL-1.0 with Combined-Work-Exception.”*
12
+
13
+ ------
14
+
15
+ ## 1. Purpose
16
+
17
+ This License gives You unlimited permission to use and modify the software to which it applies (the “Work”), either as-is or in modified form, for Your private purposes, while protecting the owners and contributors to the software from liability.
18
+
19
+ This License also strives to protect the freedom and autonomy of third parties who receive the Work from you. If any non-affiliated third party receives any part, aspect, or element of the Work from You, this License requires that You provide that third party all the permissions and materials needed to independently use and modify the Work without that third party having a loss of data or capability due to your actions.
20
+
21
+ The full permissions, conditions, and other terms are laid out below.
22
+
23
+ ## 2. Receiving a License
24
+
25
+ In order to receive this License, You must agree to its rules. The rules of this License are both obligations of Your agreement with the Licensor and conditions to your License. You must not do anything with the Work that triggers a rule You cannot or will not follow.
26
+
27
+ ### 2.1. Application
28
+
29
+ The terms of this License apply to the Work as you receive it from Licensor, as well as to any modifications, elaborations, or implementations created by You that contain any licenseable portion of the Work (a “Modified Work”). Unless specified, any reference to the Work also applies to a Modified Work.
30
+
31
+ ### 2.2. Offer and Acceptance
32
+
33
+ This License is automatically offered to every person and organization. You show that you accept this License and agree to its conditions by taking any action with the Work that, absent this License, would infringe any intellectual property right held by Licensor.
34
+
35
+ ### 2.3. Compliance and Remedies
36
+
37
+ Any failure to act according to the terms and conditions of this License places Your use of the Work outside the scope of the License and infringes the intellectual property rights of the Licensor. In the event of infringement, the terms and conditions of this License may be enforced by Licensor under the intellectual property laws of any jurisdiction to which You are subject. You also agree that either the Licensor or a Recipient (as an intended third-party beneficiary) may enforce the terms and conditions of this License against You via specific performance.
38
+
39
+ ## 3. Permissions and Conditions
40
+
41
+ ### 3.1. Permissions Granted
42
+
43
+ Conditioned on compliance with section 4, and subject to the limitations of section 3.2, Licensor grants You the world-wide, royalty-free, non-exclusive permission to:
44
+
45
+ > a) Take any action with the Work that would infringe the non-patent intellectual property laws of any jurisdiction to which You are subject; and
46
+ >
47
+ > b) Take any action with the Work that would infringe any patent claims that Licensor can license or becomes able to license, to the extent that those claims are embodied in the Work as distributed by Licensor.
48
+
49
+ ### 3.2. Limitations on Permissions Granted
50
+
51
+ The following limitations apply to the permissions granted in section 3.1:
52
+
53
+ > a) Licensor does not grant any patent license for claims that are only infringed due to modification of the Work as provided by Licensor, or the combination of the Work as provided by Licensor, directly or indirectly, with any other component, including other software or hardware.
54
+ >
55
+ > b) Licensor does not grant any license to the trademarks, service marks, or logos of Licensor, except to the extent necessary to comply with the attribution conditions in section 4.1 of this License.
56
+
57
+ ## 4. Conditions
58
+
59
+ If You exercise any permission granted by this License, such that the Work, or any part, aspect, or element of the Work, is distributed, communicated, made available, or made perceptible to a non-Affiliate third party (a “Recipient”), either via physical delivery or via a network connection to the Recipient, You must comply with the following conditions:
60
+
61
+ ### 4.1. Provide Access to Source Code
62
+
63
+ Subject to the exception in section 4.4, You must provide to each Recipient a copy of, or no-charge unrestricted network access to, the Source Code corresponding to the Work.
64
+
65
+ The “Source Code” of the Work means the form of the Work preferred for making modifications, including any comments, configuration information, documentation, help materials, installation instructions, cryptographic seeds or keys, and any information reasonably necessary for the Recipient to independently compile and use the Source Code and to have full access to the functionality contained in the Work.
66
+
67
+ #### 4.1.1. Providing Network Access to the Source Code
68
+
69
+ Network access to the Notices and Source Code may be provided by You or by a third party, such as a public software repository, and must persist during the same period in which You exercise any of the permissions granted to You under this License and for at least one year thereafter.
70
+
71
+ #### 4.1.2. Source Code for a Modified Work
72
+
73
+ Subject to the exception in section 4.5, You must provide to each Recipient of a Modified Work Access to Source Code corresponding to those portions of the Work remaining in the Modified Work as well as the modifications used by You to create the Modified Work. The Source Code corresponding to the modifications in the Modified Work must be provided to the Recipient either a) under this License, or b) under a Compatible Open Source License.
74
+
75
+ A “Compatible Open Source License” means a license accepted by the Open Source Initiative that allows object code created using both Source Code provided under this License and Source Code provided under the other open source license to be distributed together as a single work.
76
+
77
+ #### 4.1.3. Coordinated Disclosure of Security Vulnerabilities
78
+
79
+ You may delay providing the Source Code corresponding to a particular modification of the Work for up to ninety (90) days (the “Embargo Period”) if: a) the modification is intended to address a newly-identified vulnerability or a security flaw in the Work, b) disclosure of the vulnerability or security flaw before the end of the Embargo Period would put the data, identity, or autonomy of one or more Recipients of the Work at significant risk, c) You are participating in a coordinated disclosure of the vulnerability or security flaw with one or more additional Licensees, and d) Access to the Source Code pertaining to the modification is provided to all Recipients at the end of the Embargo Period.
80
+
81
+ ### 4.2. Maintain User Autonomy
82
+
83
+ In addition to providing each Recipient the opportunity to have Access to the Source Code, You cannot use the permissions given under this License to interfere with a Recipient’s ability to fully use an independent copy of the Work generated from the Source Code You provide with the Recipient’s own User Data.
84
+
85
+ “User Data” means any data that is an input to or an output from the Work, where the presence of the data is necessary for substantially identical use of the Work in an equivalent context chosen by the Recipient, and where the Recipient has an existing ownership interest, an existing right to possess, or where the data has been generated by, for, or has been assigned to the Recipient.
86
+
87
+ #### 4.2.1. No Withholding User Data
88
+
89
+ Throughout any period in which You exercise any of the permissions granted to You under this License, You must also provide to any Recipient to whom you provide services via the Work, a no-charge copy, provided in a commonly used electronic form, of the Recipient’s User Data in your possession, to the extent that such User Data is available to You for use in conjunction with the Work.
90
+
91
+ #### 4.2.2. No Technical Measures that Limit Access
92
+
93
+ You may not, by the use of cryptographic methods applied to anything provided to the Recipient, by possession or control of cryptographic keys, seeds, or hashes, by other technological protection measures, or by any other method, limit a Recipient's ability to access any functionality present in the Recipient's independent copy of the Work, or deny a Recipient full control of the Recipient's User Data.
94
+
95
+ #### 4.2.3. No Legal or Contractual Measures that Limit Access
96
+
97
+ You may not contractually restrict a Recipient's ability to independently exercise the permissions granted under this License. You waive any legal power to forbid circumvention of technical protection measures that include use of the Work, and You waive any claim that the capabilities of the Work were limited or modified as a means of enforcing the legal rights of third parties against Recipients.
98
+
99
+ ### 4.3. Provide Notices and Attribution
100
+
101
+ You must retain all licensing, authorship, or attribution notices contained in the Source Code (the “Notices”), and provide all such Notices to each Recipient, together with a statement acknowledging the use of the Work. Notices may be provided directly to a Recipient or via an easy-to-find hyperlink to an Internet location also providing Access to Source Code.
102
+
103
+ ### 4.4. Scope of Conditions in this License
104
+
105
+ You are required to uphold the conditions of this License only relative to those who are Recipients of the Work from You. Other than providing Recipients with the applicable Notices, Access to Source Code, and a copy of and full control of their User Data, nothing in this License requires You to provide processing services to or engage in network interactions with anyone.
106
+
107
+ ### 4.5. Combined Work Exception
108
+
109
+ As an exception to condition that You provide Recipients Access to Source Code, any Source Code files marked by the Licensor as having the “Combined Work Exception,” or any object code exclusively resulting from Source Code files so marked, may be combined with other Software into a “Larger Work.” So long as you comply with the requirements to provide Recipients the applicable Notices and Access to the Source Code provided to You by Licensor, and you provide Recipients access to their User Data and do not limit Recipient’s ability to independently work with their User Data, any other Software in the Larger Work as well as the Larger Work as a whole may be licensed under the terms of your choice.
110
+
111
+ ## 5. Term and Termination
112
+
113
+ The term of this License begins when You receive the Work, and continues until terminated for any of the reasons described herein, or until all Licensor’s intellectual property rights in the Software expire, whichever comes first (“Term”). This License cannot be revoked, only terminated for the reasons listed below.
114
+
115
+ ### 5.1. Effect of Termination
116
+
117
+ If this License is terminated for any reason, all permissions granted to You under Section 3 by any Licensor automatically terminate. You will immediately cease exercising any permissions granted in this License relative to the Work, including as part of any Modified Work.
118
+
119
+ ### 5.2. Termination for Non-Compliance; Reinstatement
120
+
121
+ This License terminates automatically if You fail to comply with any of the conditions in section 4. As a special exception to termination for non-compliance, Your permissions for the Work under this License will automatically be reinstated if You come into compliance with all the conditions in section 2 within sixty (60) days of being notified by Licensor or an intended third party beneficiary of Your noncompliance. You are eligible for reinstatement of permissions for the Work one time only, and only for the sixty days immediately after becoming aware of noncompliance. Loss of permissions granted for the Work under this License due to either a) sustained noncompliance lasting more than sixty days or b) subsequent termination for noncompliance after reinstatement, is permanent, unless rights are specifically restored by Licensor in writing.
122
+
123
+ ### 5.3 Termination Due to Litigation
124
+
125
+ If You initiate litigation against Licensor, or any Recipient of the Work, either direct or indirect, asserting that the Work directly or indirectly infringes any patent, then all permissions granted to You by this License shall terminate. In the event of termination due to litigation, all permissions validly granted by You under this License, directly or indirectly, shall survive termination. Administrative review procedures, declaratory judgment actions, counterclaims in response to patent litigation, and enforcement actions against former Licensees terminated under this section do not cause termination due to litigation.
126
+
127
+ ## 6. Disclaimer of Warranty and Limit on Liability
128
+
129
+ As far as the law allows, the Work comes AS-IS, without any warranty of any kind, and no Licensor or contributor will be liable to anyone for any damages related to this software or this license, under any kind of legal claim, or for any type of damages, including indirect, special, incidental, or consequential damages of any type arising as a result of this License or the use of the Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss of profits, revenue, or any and all other commercial damages or losses.
130
+
131
+ ## 7. Other Provisions
132
+
133
+ ### 7.1. Affiliates
134
+
135
+ An “Affiliate” means any other entity that, directly or indirectly through one or more intermediaries, controls, is controlled by, or is under common control with, the Licensee. Employees of a Licensee and natural persons acting as contractors exclusively providing services to Licensee are also Affiliates.
136
+
137
+ ### 7.2. Choice of Jurisdiction and Governing Law
138
+
139
+ A Licensor may require that any action or suit by a Licensee relating to a Work provided by Licensor under this License may be brought only in the courts of a particular jurisdiction and under the laws of a particular jurisdiction (excluding its conflict-of-law provisions), if Licensor provides conspicuous notice of the particular jurisdiction to all Licensees.
140
+
141
+ ### 7.3. No Sublicensing
142
+
143
+ This License is not sublicensable. Each time You provide the Work or a Modified Work to a Recipient, the Recipient automatically receives a license under the terms described in this License. You may not impose any further reservations, conditions, or other provisions on any Recipients’ exercise of the permissions granted herein.
144
+
145
+ ### 7.4. Attorneys' Fees
146
+
147
+ In any action to enforce the terms of this License, or seeking damages relating thereto, including by an intended third party beneficiary, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. A “prevailing party” is the party that achieves, or avoids, compliance with this License, including through settlement. This section shall survive the termination of this License.
148
+
149
+ ### 7.5. No Waiver
150
+
151
+ Any failure by Licensor to enforce any provision of this License will not constitute a present or future waiver of such provision nor limit Licensor’s ability to enforce such provision at a later time.
152
+
153
+ ### 7.6. Severability
154
+
155
+ If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any invalid or unenforceable portion will be interpreted to the effect and intent of the original portion. If such a construction is not possible, the invalid or unenforceable portion will be severed from this License but the rest of this License will remain in full force and effect.
156
+
157
+ ### 7.7. License for the Text of this License
158
+
159
+ The text of this license is released under the Creative Commons Attribution-ShareAlike 4.0 International License, with the caveat that any modifications of this license may not use the name “Cryptographic Autonomy License” or any name confusingly similar thereto to describe any derived work of this License.
160
+
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # cell-proxy
2
+
3
+ Wrapper for AppWebsocket
4
+
5
+
6
+ ## Installing
7
+
8
+ ```bash
9
+ npm i @ddd-qc/cell-proxy
10
+ ```
11
+
12
+ ## Setup
13
+
14
+ FIXME
@@ -0,0 +1,57 @@
1
+ import { CallZomeRequest, CapSecret, CellId, InstalledCell, ZomeName } from "@holochain/client";
2
+ import { AgentPubKeyB64, DnaHashB64 } from "@holochain-open-dev/core-types";
3
+ import { ConductorAppProxy } from "./ConductorAppProxy";
4
+ import { IInstalledCell, RoleInstanceId } from "./types";
5
+ export interface RequestLog {
6
+ request: CallZomeRequest;
7
+ timeout: number;
8
+ requestTimestamp: number;
9
+ executionTimestamp: number;
10
+ }
11
+ export interface ResponseLog {
12
+ success?: any;
13
+ failure?: any;
14
+ timestamp: number;
15
+ requestIndex: number;
16
+ }
17
+ /**
18
+ * Proxy for a running DNA.
19
+ * It logs and queues ZomeCalls.
20
+ * It holds a reference to its ConductorAppProxy and its InstalledCell.
21
+ * This class is expected to be used by ZomeProxies.
22
+ */
23
+ export declare class CellProxy implements IInstalledCell {
24
+ private _conductor;
25
+ readonly installedCell: InstalledCell;
26
+ /** Ctor */
27
+ constructor(_conductor: ConductorAppProxy, installedCell: InstalledCell, defaultTimeout?: number);
28
+ /** -- Fields -- */
29
+ defaultTimeout: number;
30
+ /** append only logs */
31
+ private _requestLog;
32
+ private _responseLog;
33
+ private _canCallBlocking;
34
+ /** -- InstalledCell interface -- */
35
+ get roleInstanceId(): RoleInstanceId;
36
+ get cellId(): CellId;
37
+ get dnaHash(): DnaHashB64;
38
+ get agentPubKey(): AgentPubKeyB64;
39
+ /** -- Methods -- */
40
+ dumpSignals(): void;
41
+ /** Pass call request to conductor proxy and log it */
42
+ executeZomeCall(reqLog: RequestLog): Promise<ResponseLog>;
43
+ /**
44
+ * callZome() with "Mutex" (for calls that writes to source-chain)
45
+ * TODO: Implement call queue instead of mutex
46
+ */
47
+ callZomeBlocking(zome_name: ZomeName, fn_name: string, payload: any, cap_secret: CapSecret | null, timeout?: number): Promise<any>;
48
+ /** */
49
+ callZome(zome_name: ZomeName, fn_name: string, payload: any, cap_secret: CapSecret | null, timeout?: number): Promise<any>;
50
+ /**
51
+ * Calls the `entry_defs()` zome function and
52
+ * returns an array of all the zome's AppEntryDefNames and visibility
53
+ */
54
+ callEntryDefs(zomeName: ZomeName): Promise<[string, boolean][]>;
55
+ /** */
56
+ dumpLogs(zomeName?: ZomeName): void;
57
+ }
@@ -0,0 +1,155 @@
1
+ import { serializeHash } from "@holochain-open-dev/utils";
2
+ import { anyToB64, delay, prettyDate, prettyDuration } from "./utils";
3
+ /**
4
+ * Proxy for a running DNA.
5
+ * It logs and queues ZomeCalls.
6
+ * It holds a reference to its ConductorAppProxy and its InstalledCell.
7
+ * This class is expected to be used by ZomeProxies.
8
+ */
9
+ export class CellProxy {
10
+ /** Ctor */
11
+ constructor(_conductor, installedCell,
12
+ //public readonly dnaDef: MyDnaDef,
13
+ defaultTimeout) {
14
+ this._conductor = _conductor;
15
+ this.installedCell = installedCell;
16
+ //private _blockingRequestQueue: Queue<RequestLog> = new Queue();
17
+ /** append only logs */
18
+ this._requestLog = [];
19
+ this._responseLog = [];
20
+ this._canCallBlocking = true;
21
+ this.defaultTimeout = defaultTimeout ? defaultTimeout : 10 * 1000;
22
+ }
23
+ /** -- InstalledCell interface -- */
24
+ get roleInstanceId() { return this.installedCell.role_id; }
25
+ get cellId() { return this.installedCell.cell_id; }
26
+ get dnaHash() { return serializeHash(this.installedCell.cell_id[0]); }
27
+ get agentPubKey() { return serializeHash(this.installedCell.cell_id[1]); }
28
+ /** -- Methods -- */
29
+ // /** */
30
+ // addSignalHandler(handler: AppSignalCb): SignalUnsubscriber {
31
+ // return this._conductor.addSignalHandler(handler, this.cellId);
32
+ // }
33
+ dumpSignals() {
34
+ this._conductor.dumpSignals(this.cellId);
35
+ }
36
+ /** Pass call request to conductor proxy and log it */
37
+ async executeZomeCall(reqLog) {
38
+ reqLog.executionTimestamp = Date.now();
39
+ const requestIndex = this._requestLog.length;
40
+ this._requestLog.push(reqLog);
41
+ try {
42
+ const response = await this._conductor.callZome(reqLog.request, reqLog.timeout);
43
+ const respLog = { requestIndex, success: response, timestamp: Date.now() };
44
+ this._responseLog.push(respLog);
45
+ return respLog;
46
+ }
47
+ catch (e) {
48
+ const respLog = { requestIndex, failure: e, timestamp: Date.now() };
49
+ this._responseLog.push(respLog);
50
+ return respLog;
51
+ }
52
+ }
53
+ /**
54
+ * callZome() with "Mutex" (for calls that writes to source-chain)
55
+ * TODO: Implement call queue instead of mutex
56
+ */
57
+ async callZomeBlocking(zome_name, fn_name, payload, cap_secret, timeout) {
58
+ timeout = timeout ? timeout : this.defaultTimeout;
59
+ const req = {
60
+ cap_secret, zome_name, fn_name, payload,
61
+ cell_id: this.installedCell.cell_id,
62
+ provenance: this.installedCell.cell_id[1],
63
+ };
64
+ const log = { request: req, timeout, requestTimestamp: Date.now() };
65
+ while (!this._canCallBlocking && Date.now() - log.requestTimestamp < timeout) {
66
+ await delay(1);
67
+ }
68
+ if (Date.now() - log.requestTimestamp >= timeout) {
69
+ console.warn({ requestLogs: this._requestLog });
70
+ return Promise.reject("Waiting for zomeCall execution timed-out");
71
+ }
72
+ this._canCallBlocking = false;
73
+ const respLog = await this.executeZomeCall(log);
74
+ this._canCallBlocking = true;
75
+ if (respLog.failure) {
76
+ this.dumpSignals();
77
+ this.dumpLogs(zome_name);
78
+ return Promise.reject(respLog.failure);
79
+ }
80
+ return respLog.success;
81
+ }
82
+ /** */
83
+ async callZome(zome_name, fn_name, payload, cap_secret, timeout) {
84
+ timeout = timeout ? timeout : this.defaultTimeout;
85
+ const req = {
86
+ cap_secret, zome_name, fn_name, payload,
87
+ cell_id: this.installedCell.cell_id,
88
+ provenance: this.installedCell.cell_id[1],
89
+ };
90
+ const log = { request: req, timeout, requestTimestamp: Date.now() };
91
+ const respLog = await this.executeZomeCall(log);
92
+ if (respLog.failure) {
93
+ this.dumpSignals();
94
+ this.dumpLogs(zome_name);
95
+ return Promise.reject(respLog.failure);
96
+ }
97
+ return respLog.success;
98
+ }
99
+ /**
100
+ * Calls the `entry_defs()` zome function and
101
+ * returns an array of all the zome's AppEntryDefNames and visibility
102
+ */
103
+ async callEntryDefs(zomeName) {
104
+ //console.log("callEntryDefs()", zomeName)
105
+ try {
106
+ const entryDefs = await this.callZome(zomeName, "entry_defs", null, null, 2 * 1000);
107
+ //console.debug("getEntryDefs() for " + this.zomeName + " result:")
108
+ //console.log({entryDefs})
109
+ let result = [];
110
+ for (const def of entryDefs.Defs) {
111
+ const name = def.id.App;
112
+ result.push([name, def.visibility.hasOwnProperty('Public')]);
113
+ }
114
+ //console.log({result})
115
+ return result;
116
+ }
117
+ catch (e) {
118
+ console.error("Calling getEntryDefs() on " + zomeName + " failed: ");
119
+ console.error({ e });
120
+ return Promise.reject(e);
121
+ }
122
+ }
123
+ // /** TODO once we have getDnaDefinition() api */
124
+ // dumpAllZomes() {
125
+ // // FIXME get DNA DEF
126
+ // for (const zomeName of dnaDef) {
127
+ // this.dumpLogs(zomeName)
128
+ // }
129
+ // }
130
+ /** */
131
+ dumpLogs(zomeName) {
132
+ let result = [];
133
+ for (const response of this._responseLog) {
134
+ const requestLog = this._requestLog[response.requestIndex];
135
+ if (zomeName && requestLog.request.zome_name != zomeName) {
136
+ continue;
137
+ }
138
+ const startTime = prettyDate(new Date(requestLog.requestTimestamp));
139
+ const waitTime = prettyDuration(new Date(requestLog.executionTimestamp - requestLog.requestTimestamp));
140
+ const duration = prettyDuration(new Date(response.timestamp - requestLog.requestTimestamp));
141
+ const input = requestLog.request.payload instanceof Uint8Array ? serializeHash(requestLog.request.payload) : requestLog.request.payload;
142
+ const output = anyToB64(response.failure ? response.failure : response.success);
143
+ const log = zomeName
144
+ ? { startTime, fnName: requestLog.request.fn_name, input, output, duration, waitTime }
145
+ : { startTime, zomeName: requestLog.request.zome_name, fnName: requestLog.request.fn_name, input, output, duration, waitTime };
146
+ result.push(log);
147
+ }
148
+ console.warn(`Dumping logs for cell "${this._conductor.getHcls(this.cellId)}"`);
149
+ if (zomeName) {
150
+ console.warn(` - For zome "${zomeName}"`);
151
+ }
152
+ console.table(result);
153
+ }
154
+ }
155
+ //# sourceMappingURL=CellProxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CellProxy.js","sourceRoot":"","sources":["../src/CellProxy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAI1D,OAAO,EAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,cAAc,EAAQ,MAAM,SAAS,CAAC;AAkB3E;;;;;GAKG;AACH,MAAM,OAAO,SAAS;IAEpB,WAAW;IACX,YACU,UAA6B,EACrB,aAA4B;IAC5C,mCAAmC;IACnC,cAAuB;QAH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MAAM,CAAC,GAAG,CAAC,CAAA;QAC/E,IAAI,QAAQ,EAAE;YACZ,OAAO,CAAC,IAAI,CAAC,gBAAgB,QAAQ,GAAG,CAAC,CAAC;SAC3C;QACD,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACvB,CAAC;CAEF"}
@@ -0,0 +1,74 @@
1
+ import { AppApi, AppInfoRequest, AppInfoResponse, AppSignal, AppSignalCb, AppWebsocket, CallZomeRequest, CellId, InstalledAppId, InstalledCell } from "@holochain/client";
2
+ import { CellProxy } from "./CellProxy";
3
+ import { HCL, CloneIndex, CellLocation, InstalledCellsMap, BaseRoleName, RoleInstanceId, RoleInstalledCells } from "./types";
4
+ import { ArchiveCloneCellRequest, CreateCloneCellRequest } from "@holochain/client/lib/api/app/types";
5
+ /** */
6
+ export interface SignalUnsubscriber {
7
+ unsubscribe: () => void;
8
+ }
9
+ /**
10
+ * Creates, connects and holds a appWebsocket.
11
+ * Creates and holds Cell proxies for this appWebsocket.
12
+ * Maintains a mapping between CellIds and HCLs
13
+ * Handles SignalHandlers per HCL
14
+ * Stores appSignal logs
15
+ * TODO Implement Singleton per App port?
16
+ */
17
+ export declare class ConductorAppProxy implements AppApi {
18
+ defaultTimeout: number;
19
+ /** -- Fields -- */
20
+ private _appWs;
21
+ /** [Timestamp, CellIdStr, Signal] */
22
+ private _signalLogs;
23
+ /** InstalledAppId -> (BaseRoleName -> RoleInstalledCells) */
24
+ private _installedCellsByApp;
25
+ /** CellIdStr -> [HCL] */
26
+ private _hclMap;
27
+ /** HCL -> AppSignalCb */
28
+ private _signalHandlers;
29
+ /** CellIdStr -> CellProxy */
30
+ private _cellProxies;
31
+ /** -- Getters -- */
32
+ /** */
33
+ getAppCells(appId: InstalledAppId): InstalledCellsMap | undefined;
34
+ /** */
35
+ getHcls(cellId: CellId): HCL[] | undefined;
36
+ /** */
37
+ getInstalledCellByLocation(cellLoc: CellLocation): InstalledCell | undefined;
38
+ /** */
39
+ getCellProxy(cellId: CellId): CellProxy | undefined;
40
+ /** Get stored CellProxy or attempt to create it */
41
+ getCellProxyByLocation(cellLoc: CellLocation): CellProxy;
42
+ /** */
43
+ getRoles(installedAppId: InstalledAppId): RoleInstanceId[] | undefined;
44
+ /** */
45
+ getClones(appId: InstalledAppId, baseRoleName: BaseRoleName): InstalledCell[];
46
+ /** */
47
+ getInstalledCell(installedAppId: InstalledAppId, baseRoleName: BaseRoleName, cloneIndex?: CloneIndex): InstalledCell;
48
+ /** -- AppApi (Passthrough to appWebsocket) -- */
49
+ createCloneCell(request: CreateCloneCellRequest): Promise<InstalledCell>;
50
+ archiveCloneCell(request: ArchiveCloneCellRequest): Promise<void>;
51
+ appInfo(args: AppInfoRequest): Promise<AppInfoResponse>;
52
+ callZome(req: CallZomeRequest, timeout?: number): Promise<any>;
53
+ /** -- Creation -- */
54
+ /** async Factory */
55
+ static new(port_or_socket: number | AppWebsocket, defaultTimeout?: number): Promise<ConductorAppProxy>;
56
+ /** */
57
+ private static fromSocket;
58
+ /** Ctor */
59
+ private constructor();
60
+ /** -- Methods -- */
61
+ createRoleInstalledCells(installed_app_id: InstalledAppId, baseRoleName: BaseRoleName): Promise<RoleInstalledCells>;
62
+ /** */
63
+ addCloneInstalledCell(cellLoc: CellLocation, cloneCell: InstalledCell): void;
64
+ /** */
65
+ createCellProxy(installedAppId: InstalledAppId, baseRoleName: BaseRoleName, cloneIndex?: CloneIndex): CellProxy;
66
+ /** */
67
+ dumpSignals(cellId?: CellId): void;
68
+ /** Log all signals received */
69
+ private logSignal;
70
+ /** */
71
+ onSignal(signal: AppSignal): void;
72
+ /** Store signalHandler to internal handler array */
73
+ addSignalHandler(handler: AppSignalCb, hcl?: HCL): SignalUnsubscriber;
74
+ }
@@ -0,0 +1,306 @@
1
+ import { AppWebsocket, } from "@holochain/client";
2
+ import { CellProxy } from "./CellProxy";
3
+ import { CellIdStr, destructureRoleInstanceId, CellLocation, } from "./types";
4
+ import { prettyDate, printAppInfo } from "./utils";
5
+ /**
6
+ * Creates, connects and holds a appWebsocket.
7
+ * Creates and holds Cell proxies for this appWebsocket.
8
+ * Maintains a mapping between CellIds and HCLs
9
+ * Handles SignalHandlers per HCL
10
+ * Stores appSignal logs
11
+ * TODO Implement Singleton per App port?
12
+ */
13
+ export class ConductorAppProxy {
14
+ /** -- Getters -- */
15
+ /** */
16
+ getAppCells(appId) {
17
+ return this._installedCellsByApp[appId];
18
+ }
19
+ /** */
20
+ getHcls(cellId) {
21
+ return this._hclMap[CellIdStr(cellId)];
22
+ }
23
+ /** */
24
+ getInstalledCellByLocation(cellLoc) {
25
+ try {
26
+ return this.getInstalledCell(cellLoc.appId, cellLoc.baseRoleName, cellLoc.cloneIndex);
27
+ }
28
+ catch (e) {
29
+ //console.warn(e);
30
+ return undefined;
31
+ }
32
+ }
33
+ /** */
34
+ getCellProxy(cellId) {
35
+ const sId = CellIdStr(cellId);
36
+ return this._cellProxies[sId];
37
+ }
38
+ /** Get stored CellProxy or attempt to create it */
39
+ getCellProxyByLocation(cellLoc) {
40
+ const installedCell = this.getInstalledCell(cellLoc.appId, cellLoc.baseRoleName, cellLoc.cloneIndex);
41
+ const maybeProxy = this.getCellProxy(installedCell.cell_id);
42
+ if (!maybeProxy)
43
+ throw Error("getCellProxyByLocation() failed. Proxy not found for cell " + CellIdStr(installedCell.cell_id));
44
+ return maybeProxy;
45
+ }
46
+ /** */
47
+ getRoles(installedAppId) {
48
+ if (!this._installedCellsByApp[installedAppId])
49
+ return undefined;
50
+ return Object.values(this._installedCellsByApp[installedAppId]).map((roleCells) => {
51
+ return roleCells.original.role_id;
52
+ });
53
+ }
54
+ /** */
55
+ getClones(appId, baseRoleName) {
56
+ const maybeApp = this._installedCellsByApp[appId];
57
+ if (!maybeApp)
58
+ return [];
59
+ const roleInstalledCells = maybeApp[baseRoleName];
60
+ if (!roleInstalledCells)
61
+ return [];
62
+ return Object.values(roleInstalledCells.clones);
63
+ }
64
+ /** */
65
+ getInstalledCell(installedAppId, baseRoleName, cloneIndex) {
66
+ const roleCellsMap = this._installedCellsByApp[installedAppId];
67
+ if (!roleCellsMap)
68
+ throw Error(`getInstalledCell() failed. No hApp with ID "${installedAppId}" found.`);
69
+ const roleCells = roleCellsMap[baseRoleName];
70
+ if (!roleCells)
71
+ throw Error(`getInstalledCell() failed: BaseRoleName "${baseRoleName}" not found in happ "${installedAppId}"`);
72
+ if (cloneIndex !== undefined) {
73
+ const clone = roleCells.clones["" + cloneIndex];
74
+ if (!clone) {
75
+ throw Error(`getInstalledCell() failed: cloneIndex "${cloneIndex}" not found for role "${installedAppId}/${baseRoleName}"`);
76
+ }
77
+ return roleCells.clones["" + cloneIndex];
78
+ }
79
+ return roleCells.original;
80
+ }
81
+ /** -- AppApi (Passthrough to appWebsocket) -- */
82
+ async createCloneCell(request) {
83
+ console.log("createCloneCell() called:", request);
84
+ return this._appWs.createCloneCell(request);
85
+ }
86
+ async archiveCloneCell(request) {
87
+ console.log("archiveCloneCell() called:", request);
88
+ this._appWs.archiveCloneCell(request);
89
+ }
90
+ async appInfo(args) {
91
+ return this._appWs.appInfo(args);
92
+ }
93
+ async callZome(req, timeout) {
94
+ timeout = timeout ? timeout : this.defaultTimeout;
95
+ return this._appWs.callZome(req, timeout);
96
+ }
97
+ /** -- Creation -- */
98
+ /** async Factory */
99
+ static async new(port_or_socket, defaultTimeout) {
100
+ if (typeof port_or_socket == 'object') {
101
+ return ConductorAppProxy.fromSocket(port_or_socket);
102
+ }
103
+ else {
104
+ const timeout = defaultTimeout ? defaultTimeout : 10 * 1000;
105
+ let wsUrl = `ws://localhost:${port_or_socket}`;
106
+ try {
107
+ let conductor = new ConductorAppProxy(timeout);
108
+ conductor._appWs = await AppWebsocket.connect(wsUrl, timeout, (sig) => { conductor.onSignal(sig); });
109
+ return conductor;
110
+ }
111
+ catch (e) {
112
+ console.error("ConductorAppProxy initialization failed", e);
113
+ return Promise.reject("ConductorAppProxy initialization failed");
114
+ }
115
+ }
116
+ }
117
+ /** */
118
+ static async fromSocket(appWebsocket) {
119
+ try {
120
+ let conductor = new ConductorAppProxy(appWebsocket.defaultTimeout);
121
+ conductor._appWs = appWebsocket;
122
+ console.warn("Using pre-existing AppWebsocket. ConductorAppProxy's 'onSignal()' SignalHandler needs to be set by the provider of the AppWebsocket.");
123
+ return conductor;
124
+ }
125
+ catch (e) {
126
+ console.error("ConductorAppProxy initialization failed", e);
127
+ return Promise.reject("ConductorAppProxy initialization failed");
128
+ }
129
+ }
130
+ /** Ctor */
131
+ constructor(defaultTimeout) {
132
+ this.defaultTimeout = defaultTimeout;
133
+ /** [Timestamp, CellIdStr, Signal] */
134
+ this._signalLogs = [];
135
+ /** InstalledAppId -> (BaseRoleName -> RoleInstalledCells) */
136
+ this._installedCellsByApp = {};
137
+ /** CellIdStr -> [HCL] */
138
+ this._hclMap = {};
139
+ /** HCL -> AppSignalCb */
140
+ this._signalHandlers = {};
141
+ /** CellIdStr -> CellProxy */
142
+ this._cellProxies = {};
143
+ //const _unsubscribe = _appWs.addSignalHandler(this.onSignal);
144
+ const _unsub = this.addSignalHandler((sig) => this.logSignal(sig));
145
+ }
146
+ /** -- Methods -- */
147
+ async createRoleInstalledCells(installed_app_id, baseRoleName) {
148
+ /** Make sure hApp exists */
149
+ const installedAppInfo = await this.appInfo({ installed_app_id });
150
+ if (installedAppInfo == null) {
151
+ Promise.reject(`createCellProxy() failed. App "${installed_app_id}" not found on AppWebsocket "${this._appWs.client.socket.url}"`);
152
+ }
153
+ console.log("createRoleInstalledCells() installedAppInfo:\n", printAppInfo(installedAppInfo));
154
+ /** Make sure app Object exists */
155
+ if (!this._installedCellsByApp[installed_app_id]) {
156
+ this._installedCellsByApp[installed_app_id] = {};
157
+ }
158
+ /** Get all cells with that baseRoleName */
159
+ let original;
160
+ let clones = {};
161
+ for (const curCell of installedAppInfo.cell_data) {
162
+ //console.log(`CreateCellProxy(): Found cell "${installedCell.role_id}":`, CellIdStr(installedCell.cell_id));
163
+ const maybePair = destructureRoleInstanceId(curCell.role_id);
164
+ const curBaseName = maybePair ? maybePair[0] : curCell.role_id;
165
+ if (curBaseName !== baseRoleName) {
166
+ continue;
167
+ }
168
+ if (maybePair) {
169
+ if (clones["" + maybePair[1]]) {
170
+ console.error(`createRoleInstalledCells() Proxy already exist for clone: "${maybePair[0]}/${maybePair[1]}"`);
171
+ }
172
+ clones["" + maybePair[1]] = curCell;
173
+ }
174
+ else {
175
+ original = curCell;
176
+ }
177
+ }
178
+ if (!original) {
179
+ Promise.reject("Original cell not found for role " + baseRoleName);
180
+ }
181
+ let roleInstalledCells = { original, clones };
182
+ /** Store it*/
183
+ this._installedCellsByApp[installed_app_id][baseRoleName] = roleInstalledCells;
184
+ return roleInstalledCells;
185
+ }
186
+ /** */
187
+ addCloneInstalledCell(cellLoc, cloneCell) {
188
+ if (!this._installedCellsByApp[cellLoc.appId])
189
+ throw Error("addCloneInstalledCell() failed. no appId. " + cellLoc.asHcl());
190
+ if (!this._installedCellsByApp[cellLoc.appId][cellLoc.baseRoleName])
191
+ throw Error("addCloneInstalledCell() failed. no baseRoleName. " + cellLoc.asHcl());
192
+ if (cellLoc.cloneIndex === undefined)
193
+ throw Error("addCloneInstalledCell() failed. Missing cloneIndex " + cellLoc.asHcl());
194
+ this._installedCellsByApp[cellLoc.appId][cellLoc.baseRoleName].clones[cellLoc.cloneIndex] = cloneCell;
195
+ // const sCellId = CellIdStr(cloneCell.cell_id);
196
+ // console.log("CreateCellProxy() adding to hclMap", sCellId, cellLoc.asHcl())
197
+ // if (this._hclMap[sCellId]) {
198
+ // this._hclMap[sCellId].push(cellLoc.asHcl());
199
+ // } else {
200
+ // this._hclMap[sCellId] = [cellLoc.asHcl()];
201
+ // }
202
+ }
203
+ /** */
204
+ createCellProxy(installedAppId, baseRoleName, cloneIndex) {
205
+ /** Build HCL */
206
+ const cellLoc = CellLocation.from(installedAppId, baseRoleName, cloneIndex);
207
+ const hcl = cellLoc.asHcl();
208
+ console.log("createCellProxy() for", hcl);
209
+ /** Make sure cell exists */
210
+ const maybeInstalledCell = this.getInstalledCellByLocation(cellLoc);
211
+ if (!maybeInstalledCell) {
212
+ Promise.reject("createCellProxy() failed. Cell not found for " + hcl);
213
+ }
214
+ console.log("createCellProxy() Currently stored cellProxies:", this._cellProxies);
215
+ const sCellId = CellIdStr(maybeInstalledCell.cell_id);
216
+ /** Create proxy for this cell if none exist yet, otherwise reuse */
217
+ let cellProxy = this._cellProxies[sCellId];
218
+ if (!cellProxy) {
219
+ const roleInstalledCells = this._installedCellsByApp[installedAppId][baseRoleName];
220
+ /** Make sure cell exists */
221
+ if (!roleInstalledCells || cloneIndex !== undefined && cloneIndex >= Object.values(roleInstalledCells.clones).length) {
222
+ Promise.reject(`createCellProxy() failed. Cell "${hcl}" not found on AppWebsocket "${this._appWs.client.socket.url}"`);
223
+ }
224
+ //console.log({_installedCells: this._installedCells})
225
+ const installedCell = cloneIndex !== undefined ? roleInstalledCells.clones[cloneIndex] : roleInstalledCells.original;
226
+ /** Create and store Proxy */
227
+ cellProxy = new CellProxy(this, installedCell, this.defaultTimeout);
228
+ this._cellProxies[sCellId] = cellProxy;
229
+ }
230
+ /** Create CellId -> HCL mapping */
231
+ console.log("CreateCellProxy() adding to hclMap", sCellId, hcl);
232
+ if (this._hclMap[sCellId]) {
233
+ this._hclMap[sCellId].push(hcl);
234
+ }
235
+ else {
236
+ this._hclMap[sCellId] = [hcl];
237
+ }
238
+ console.log("createCellProxy() Currently stored hclMap:", this._hclMap);
239
+ return cellProxy;
240
+ }
241
+ /** */
242
+ dumpSignals(cellId) {
243
+ if (cellId) {
244
+ const cellStr = CellIdStr(cellId);
245
+ console.warn(`Dumping signal logs for cell "${this._hclMap[cellStr]}"`);
246
+ const logs = this._signalLogs
247
+ .filter((log) => log[1] == cellStr)
248
+ .map((log) => {
249
+ return { timestamp: prettyDate(new Date(log[0])), payload: log[2].data.payload };
250
+ });
251
+ console.table(logs);
252
+ }
253
+ else {
254
+ console.warn("Dumping all signal logs");
255
+ const logs = this._signalLogs
256
+ .map((log) => {
257
+ return { timestamp: prettyDate(new Date(log[0])), cell: this._hclMap[log[1]], payload: log[2].data.payload };
258
+ });
259
+ console.table(logs);
260
+ }
261
+ }
262
+ /** Log all signals received */
263
+ logSignal(signal) {
264
+ this._signalLogs.push([Date.now(), CellIdStr(signal.data.cellId), signal]);
265
+ console.log("signal logged", this._signalLogs);
266
+ }
267
+ /** */
268
+ onSignal(signal) {
269
+ /** Grabe cell specific handlers */
270
+ const hcls = this.getHcls(signal.data.cellId);
271
+ const handlers = hcls ? hcls.map((hcl) => this._signalHandlers[hcl]) : [];
272
+ /** Grab common handler */
273
+ const allHandler = this._signalHandlers["__all"];
274
+ if (allHandler)
275
+ handlers.push(allHandler);
276
+ /** Send to all handlers */
277
+ for (const handler of handlers) {
278
+ handler(signal);
279
+ }
280
+ }
281
+ /** Store signalHandler to internal handler array */
282
+ addSignalHandler(handler, hcl) {
283
+ hcl = hcl ? hcl : "__all";
284
+ console.log("addSignalHandler()", hcl, Object.keys(this._signalHandlers));
285
+ //const maybeHandler = this._signalHandlers[cellIdStr]
286
+ if (hcl != "__all") {
287
+ const maybeHandler = Object.getOwnPropertyDescriptor(this._signalHandlers, hcl);
288
+ if (maybeHandler && maybeHandler.value) {
289
+ throw new Error(`SignalHandler already added for "${hcl}"`);
290
+ }
291
+ }
292
+ this._signalHandlers[hcl] = handler;
293
+ /* return tailored unsubscribe function to the caller */
294
+ return {
295
+ unsubscribe: () => {
296
+ const maybeHandler = this._signalHandlers[hcl];
297
+ if (!maybeHandler) {
298
+ console.warn("unsubscribe failed: Couldn't find signalHandler for", hcl);
299
+ return;
300
+ }
301
+ delete this._signalHandlers[hcl];
302
+ }
303
+ };
304
+ }
305
+ }
306
+ //# sourceMappingURL=ConductorAppProxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConductorAppProxy.js","sourceRoot":"","sources":["../src/ConductorAppProxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAEQ,YAAY,GAE1B,MAAM,mBAAmB,CAA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types";
3
+ import { ZomeSpecific } from "./mixins";
4
+ import { CellProxy } from "./CellProxy";
5
+ import { IInstalledCell, RoleInstanceId } from "./types";
6
+ export type ZomeProxyConstructor = {
7
+ new (cellProxy: CellProxy, zomeName?: ZomeName): ZomeProxy;
8
+ } & typeof ZomeSpecific;
9
+ /**
10
+ * ABC for representing the zome function bindings of a Zome.
11
+ * It holds the zomeName and reference to a CellProxy.
12
+ */
13
+ export declare abstract class ZomeProxy extends ZomeSpecific implements IInstalledCell {
14
+ protected _cellProxy: CellProxy;
15
+ /** Ctor */
16
+ constructor(_cellProxy: CellProxy, zomeName?: ZomeName);
17
+ /** InstalledCell interface */
18
+ get installedCell(): InstalledCell;
19
+ get roleInstanceId(): RoleInstanceId;
20
+ get cellId(): CellId;
21
+ get dnaHash(): EntryHashB64;
22
+ get agentPubKey(): AgentPubKeyB64;
23
+ /** Helper for calling a zome function on its zome */
24
+ protected call(fn_name: string, payload: any, maybeSecret?: CapSecret, timeout?: number): Promise<any>;
25
+ /** Helper for calling a zome function on its zome */
26
+ protected callBlocking(fn_name: string, payload: any, maybeSecret?: CapSecret, timeout?: number): Promise<any>;
27
+ }
@@ -0,0 +1,39 @@
1
+ import { ZomeSpecific } from "./mixins";
2
+ /**
3
+ * ABC for representing the zome function bindings of a Zome.
4
+ * It holds the zomeName and reference to a CellProxy.
5
+ */
6
+ export class ZomeProxy extends ZomeSpecific {
7
+ /** Ctor */
8
+ constructor(_cellProxy, zomeName) {
9
+ super();
10
+ this._cellProxy = _cellProxy;
11
+ if (zomeName) {
12
+ this.zomeName = zomeName;
13
+ }
14
+ else {
15
+ if (!this.getDefaultZomeName()) {
16
+ throw Error("zomeName not defined in ZomeProxy subclass " + this.constructor.name);
17
+ }
18
+ }
19
+ }
20
+ /** InstalledCell interface */
21
+ get installedCell() { return this._cellProxy.installedCell; }
22
+ get roleInstanceId() { return this._cellProxy.roleInstanceId; }
23
+ get cellId() { return this._cellProxy.cellId; }
24
+ get dnaHash() { return this._cellProxy.dnaHash; }
25
+ get agentPubKey() { return this._cellProxy.agentPubKey; }
26
+ /** Helper for calling a zome function on its zome */
27
+ async call(fn_name, payload, maybeSecret, timeout) {
28
+ //console.log("ZomeProxy.call", this.zomeName)
29
+ const cap_secret = maybeSecret ? maybeSecret : null;
30
+ return this._cellProxy.callZome(this.zomeName, fn_name, payload, cap_secret, timeout);
31
+ }
32
+ /** Helper for calling a zome function on its zome */
33
+ async callBlocking(fn_name, payload, maybeSecret, timeout) {
34
+ //console.log("ZomeProxy.call", this.zomeName)
35
+ const cap_secret = maybeSecret ? maybeSecret : null;
36
+ return this._cellProxy.callZomeBlocking(this.zomeName, fn_name, payload, cap_secret, timeout);
37
+ }
38
+ }
39
+ //# sourceMappingURL=ZomeProxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ZomeProxy.js","sourceRoot":"","sources":["../src/ZomeProxy.ts"],"names":[],"mappings":"AAEA,OAAO,EAAC,YAAY,EAAC,MAAM,UAAU,CAAC;AAQtC;;;GAGG;AACH,MAAM,OAAgB,SAAU,SAAQ,YAAY;IAElD,WAAW;IACX,YAAsB,UAAqB,EAAE,QAAmB;QAC9D,KAAK,EAAE,CAAC;QADY,eAAU,GAAV,UAAU,CAAW;QAEzC,IAAI,QAAQ,EAAE;YAAC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;SAAC;aAClC;YACH,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE;gBAC9B,MAAM,KAAK,CAAC,6CAA6C,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;aACpF;SACF;IACL,CAAC;IAED,8BAA8B;IAC9B,IAAI,aAAa,KAAoB,OAAO,IAAI,CAAC,UAAU,CAAC,aAAa,CAAA,CAAC,CAAC;IAC3E,IAAI,cAAc,KAAqB,OAAO,IAAI,CAAC,UAAU,CAAC,cAAc,CAAA,CAAC,CAAC;IAC9E,IAAI,MAAM,KAAa,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAA,CAAC,CAAC;IACtD,IAAI,OAAO,KAAmB,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAA,CAAA,CAAC;IAC7D,IAAI,WAAW,KAAqB,OAAO,IAAI,CAAC,UAAU,CAAC,WAAW,CAAA,CAAC,CAAC;IAExE,qDAAqD;IAC3C,KAAK,CAAC,IAAI,CAAC,OAAe,EAAE,OAAY,EAAE,WAAuB,EAAE,OAAgB;QAC3F,8CAA8C;QAC9C,MAAM,UAAU,GAAG,WAAW,CAAA,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC;QACnD,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IACxF,CAAC;IAED,qDAAqD;IAC3C,KAAK,CAAC,YAAY,CAAC,OAAe,EAAE,OAAY,EAAE,WAAuB,EAAE,OAAgB;QACnG,8CAA8C;QAC9C,MAAM,UAAU,GAAG,WAAW,CAAA,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC;QACnD,OAAO,IAAI,CAAC,UAAU,CAAC,gBAAgB,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;IAChG,CAAC;CAEF"}
@@ -0,0 +1,6 @@
1
+ export * from "./ConductorAppProxy";
2
+ export * from "./CellProxy";
3
+ export * from "./ZomeProxy";
4
+ export * from "./utils";
5
+ export * from "./types";
6
+ export * from "./mixins";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./ConductorAppProxy";
2
+ export * from "./CellProxy";
3
+ export * from "./ZomeProxy";
4
+ export * from "./utils";
5
+ export * from "./types";
6
+ export * from "./mixins";
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC"}
@@ -0,0 +1,42 @@
1
+ import { InstalledAppId, ZomeName } from "@holochain/client";
2
+ import { BaseRoleName } from "./types";
3
+ type AbstractConstructor<T = {}> = abstract new (...args: any[]) => T;
4
+ declare class Empty {
5
+ constructor(...args: any[]);
6
+ }
7
+ /** ------------------------------------------------------------------------------------------- **/
8
+ export declare function ZomeSpecificMixin<TBase extends AbstractConstructor>(Base: TBase): ((abstract new (...args: any[]) => {
9
+ getDefaultZomeName(): ZomeName;
10
+ zomeName: ZomeName;
11
+ }) & {
12
+ readonly DEFAULT_ZOME_NAME: ZomeName;
13
+ }) & TBase;
14
+ export declare const ZomeSpecific: ((abstract new (...args: any[]) => {
15
+ getDefaultZomeName(): ZomeName;
16
+ zomeName: ZomeName;
17
+ }) & {
18
+ readonly DEFAULT_ZOME_NAME: ZomeName;
19
+ }) & typeof Empty;
20
+ /** ------------------------------------------------------------------------------------------- **/
21
+ export declare function RoleSpecificMixin<TBase extends AbstractConstructor>(Base: TBase): ((abstract new (...args: any[]) => {
22
+ baseRoleName: BaseRoleName;
23
+ }) & {
24
+ readonly DEFAULT_BASE_ROLE_NAME: BaseRoleName;
25
+ }) & TBase;
26
+ export declare const RoleSpecific: ((abstract new (...args: any[]) => {
27
+ baseRoleName: BaseRoleName;
28
+ }) & {
29
+ readonly DEFAULT_BASE_ROLE_NAME: BaseRoleName;
30
+ }) & typeof Empty;
31
+ /** ------------------------------------------------------------------------------------------- **/
32
+ export declare function HappSpecificMixin<TBase extends AbstractConstructor>(Base: TBase): ((abstract new (...args: any[]) => {
33
+ happId: InstalledAppId;
34
+ }) & {
35
+ readonly DEFAULT_HAPP_ID: InstalledAppId;
36
+ }) & TBase;
37
+ export declare const HappSpecific: ((abstract new (...args: any[]) => {
38
+ happId: InstalledAppId;
39
+ }) & {
40
+ readonly DEFAULT_HAPP_ID: InstalledAppId;
41
+ }) & typeof Empty;
42
+ export {};
package/dist/mixins.js ADDED
@@ -0,0 +1,37 @@
1
+ class Empty {
2
+ constructor(...args) { }
3
+ }
4
+ /** ------------------------------------------------------------------------------------------- **/
5
+ export function ZomeSpecificMixin(Base) {
6
+ class AZomeSpecific extends Base {
7
+ constructor(...args) {
8
+ super(args);
9
+ this.zomeName = this.constructor.DEFAULT_ZOME_NAME;
10
+ }
11
+ getDefaultZomeName() {
12
+ return this.constructor.DEFAULT_ZOME_NAME;
13
+ }
14
+ }
15
+ ;
16
+ return AZomeSpecific;
17
+ }
18
+ export const ZomeSpecific = ZomeSpecificMixin(Empty);
19
+ /** ------------------------------------------------------------------------------------------- **/
20
+ export function RoleSpecificMixin(Base) {
21
+ class ARoleSpecific extends Base {
22
+ constructor(...args) { super(); this.baseRoleName = this.constructor.DEFAULT_BASE_ROLE_NAME; }
23
+ }
24
+ ;
25
+ return ARoleSpecific;
26
+ }
27
+ export const RoleSpecific = RoleSpecificMixin(Empty);
28
+ /** ------------------------------------------------------------------------------------------- **/
29
+ export function HappSpecificMixin(Base) {
30
+ class AHappSpecific extends Base {
31
+ constructor(...args) { super(); this.happId = this.constructor.DEFAULT_HAPP_ID; }
32
+ }
33
+ ;
34
+ return AHappSpecific;
35
+ }
36
+ export const HappSpecific = HappSpecificMixin(Empty);
37
+ //# sourceMappingURL=mixins.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mixins.js","sourceRoot":"","sources":["../src/mixins.ts"],"names":[],"mappings":"AAOA,MAAM,KAAK;IACT,YAAY,GAAG,IAAW,IAAG,CAAC;CAC/B;AAGD,mGAAmG;AAEnG,MAAM,UAAU,iBAAiB,CAAoC,IAAW;IAC9E,MAAe,aAAc,SAAQ,IAAI;QACvC,YAAY,GAAG,IAAW;YACxB,KAAK,CAAC,IAAI,CAAC,CAAC;YACZ,IAAI,CAAC,QAAQ,GAAI,IAAI,CAAC,WAAmB,CAAC,iBAAiB,CAAA;QAC7D,CAAC;QACD,kBAAkB;YAChB,OAAQ,IAAI,CAAC,WAAoC,CAAC,iBAAiB,CAAC;QACxE,CAAC;KAGA;IAAA,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC;AAGrD,mGAAmG;AAEnG,MAAM,UAAU,iBAAiB,CAAoC,IAAW;IAC9E,MAAe,aAAc,SAAQ,IAAI;QACvC,YAAY,GAAG,IAAW,IAAE,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,YAAY,GAAI,IAAI,CAAC,WAAmB,CAAC,sBAAsB,CAAA,CAAA,CAAC;KAG3G;IAAA,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC;AAGrD,mGAAmG;AAEnG,MAAM,UAAU,iBAAiB,CAAoC,IAAW;IAC9E,MAAe,aAAc,SAAQ,IAAI;QACvC,YAAY,GAAG,IAAW,IAAE,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,GAAI,IAAI,CAAC,WAAmB,CAAC,eAAe,CAAA,CAAA,CAAC;KAG9F;IAAA,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC"}
@@ -0,0 +1,46 @@
1
+ import { CellId, InstalledAppId, InstalledCell } from "@holochain/client";
2
+ import { AgentPubKeyB64, Dictionary, DnaHashB64 } from "@holochain-open-dev/core-types";
3
+ import { AgentPubKey, DnaHash } from "@holochain/client/lib/types";
4
+ /**
5
+ *
6
+ */
7
+ export interface IInstalledCell {
8
+ get installedCell(): InstalledCell;
9
+ get roleInstanceId(): RoleInstanceId;
10
+ get dnaHash(): DnaHashB64;
11
+ get agentPubKey(): AgentPubKeyB64;
12
+ get cellId(): CellId;
13
+ }
14
+ export type BaseRoleName = string;
15
+ export type CloneIndex = number;
16
+ export type RoleInstalledCells = {
17
+ original: InstalledCell;
18
+ /** CloneName / Index -> InstalledCell */
19
+ clones: Dictionary<InstalledCell>;
20
+ };
21
+ /** BaseRoleName -> RoleInstalledCells */
22
+ export type InstalledCellsMap = Dictionary<RoleInstalledCells>;
23
+ /** -- RoleInstanceId -- */
24
+ /** type for string "<baseRoleName>.<cloneIndex>" */
25
+ export type RoleInstanceId = string;
26
+ export declare function RoleInstanceId(baseRoleName: BaseRoleName, cloneIndex?: CloneIndex): RoleInstanceId;
27
+ export declare function destructureRoleInstanceId(id: RoleInstanceId): [BaseRoleName, CloneIndex] | undefined;
28
+ /** -- HCL & Cell Location -- */
29
+ /** HCL: Holochain Cell Location */
30
+ export type HCL = string;
31
+ /** */
32
+ export declare class CellLocation {
33
+ readonly appId: InstalledAppId;
34
+ readonly roleInstanceId: RoleInstanceId;
35
+ constructor(appId: InstalledAppId, roleInstanceId: RoleInstanceId);
36
+ /** */
37
+ static from(appId: InstalledAppId, baseRoleName: BaseRoleName, cloneIndex?: CloneIndex): CellLocation;
38
+ get baseRoleName(): BaseRoleName;
39
+ get cloneIndex(): CloneIndex | undefined;
40
+ asHcl(): HCL;
41
+ }
42
+ /** -- CellIdStr -- */
43
+ export type CellIdStr = string;
44
+ export declare function CellIdStr(hash_or_id: DnaHash | CellId, key?: AgentPubKey): CellIdStr;
45
+ /** */
46
+ export declare function str2CellId(str: CellIdStr): CellId;
package/dist/types.js ADDED
@@ -0,0 +1,65 @@
1
+ import { deserializeHash, serializeHash } from "@holochain-open-dev/utils";
2
+ export function RoleInstanceId(baseRoleName, cloneIndex) {
3
+ if (!cloneIndex)
4
+ return baseRoleName;
5
+ return "" + baseRoleName + "." + cloneIndex;
6
+ }
7
+ export function destructureRoleInstanceId(id) {
8
+ const subs = id.split(".");
9
+ if (subs.length != 2) {
10
+ //throw Error(`Bad RoleInstance id format: "${id}"`);
11
+ return undefined;
12
+ }
13
+ return [subs[0], Number(subs[1])];
14
+ }
15
+ /** */
16
+ export class CellLocation {
17
+ constructor(appId, roleInstanceId) {
18
+ this.appId = appId;
19
+ this.roleInstanceId = roleInstanceId;
20
+ }
21
+ /** */
22
+ static from(appId, baseRoleName, cloneIndex) {
23
+ const instanceId = cloneIndex === undefined
24
+ ? baseRoleName
25
+ : baseRoleName + "." + cloneIndex;
26
+ return new CellLocation(appId, instanceId);
27
+ }
28
+ // TODO
29
+ //static fromHcl(hcl: HCL): CellLocation {}
30
+ get baseRoleName() {
31
+ const maybe = destructureRoleInstanceId(this.roleInstanceId);
32
+ return maybe ? maybe[0] : this.roleInstanceId;
33
+ }
34
+ get cloneIndex() {
35
+ const maybe = destructureRoleInstanceId(this.roleInstanceId);
36
+ return maybe ? maybe[1] : undefined;
37
+ }
38
+ asHcl() {
39
+ let hcl = "hcl://" + this.appId + "/" + this.baseRoleName;
40
+ const maybeCloneIndex = this.cloneIndex;
41
+ if (maybeCloneIndex !== undefined) {
42
+ hcl += "/" + maybeCloneIndex;
43
+ }
44
+ return hcl;
45
+ }
46
+ }
47
+ const CELL_ID_SEPARATOR = "||";
48
+ export function CellIdStr(hash_or_id, key) {
49
+ if (Array.isArray(hash_or_id)) {
50
+ return "" + serializeHash(hash_or_id[0]) + CELL_ID_SEPARATOR + serializeHash(hash_or_id[1]);
51
+ }
52
+ if (!key) {
53
+ throw Error("CellIdStr() failed. AgentPubKey not provided");
54
+ }
55
+ return "" + serializeHash(hash_or_id) + CELL_ID_SEPARATOR + serializeHash(key);
56
+ }
57
+ /** */
58
+ export function str2CellId(str) {
59
+ const subs = str.split(CELL_ID_SEPARATOR);
60
+ if (subs.length != 2) {
61
+ throw Error("str2CellId() failed. Bad input string format");
62
+ }
63
+ return [deserializeHash(subs[0]), deserializeHash(subs[1])];
64
+ }
65
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sour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,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAC7D,CAAC"}
@@ -0,0 +1,30 @@
1
+ import { CellId, InstalledAppInfo } from "@holochain/client";
2
+ import { IInstalledCell } from "./types";
3
+ /** */
4
+ export declare function areArraysEqual(first: Uint8Array, second: Uint8Array): boolean;
5
+ /** */
6
+ export declare function areCellsEqual(cellA: CellId, cellB: CellId): boolean;
7
+ /** */
8
+ export declare const delay: (ms: number) => Promise<unknown>;
9
+ /**
10
+ * Checks if obj is a Hash or list of hashes and tries to convert it a B64 or list of B64
11
+ */
12
+ export declare function anyToB64(obj: any): any;
13
+ export declare function prettyDuration(date: Date): string;
14
+ /** */
15
+ export declare function prettyDate(date: Date): string;
16
+ /** */
17
+ export declare function printAppInfo(appInfo: InstalledAppInfo): string;
18
+ /** */
19
+ export declare function printInstalledCell(installedCell: IInstalledCell): string;
20
+ /** -- Experimental -- */
21
+ /**
22
+ *
23
+ */
24
+ export declare class Queue<T> {
25
+ private _store;
26
+ get length(): number;
27
+ push(val: T): void;
28
+ pop(): T | undefined;
29
+ isEmpty(): boolean;
30
+ }
package/dist/utils.js ADDED
@@ -0,0 +1,81 @@
1
+ import { serializeHash } from "@holochain-open-dev/utils";
2
+ import { CellIdStr } from "./types";
3
+ /** */
4
+ export function areArraysEqual(first, second) {
5
+ return first.length === second.length && first.every((value, index) => value === second[index]);
6
+ }
7
+ /** */
8
+ export function areCellsEqual(cellA, cellB) {
9
+ return areArraysEqual(cellA[0], cellB[0]) && areArraysEqual(cellA[1], cellB[1]);
10
+ }
11
+ /** */
12
+ export const delay = (ms) => new Promise(r => setTimeout(r, ms));
13
+ /**
14
+ * Checks if obj is a Hash or list of hashes and tries to convert it a B64 or list of B64
15
+ */
16
+ export function anyToB64(obj) {
17
+ /** Check if it's a hash */
18
+ if (obj instanceof Uint8Array) {
19
+ return serializeHash(obj);
20
+ }
21
+ else {
22
+ /** Check if its an array of hashes */
23
+ if (Array.isArray(obj)) {
24
+ const isUint8Array = obj.length > 0 &&
25
+ obj.every((value) => {
26
+ return value instanceof Uint8Array;
27
+ });
28
+ if (isUint8Array) {
29
+ let result = [];
30
+ for (const cur of obj) {
31
+ result.push(serializeHash(cur));
32
+ }
33
+ return result;
34
+ }
35
+ }
36
+ }
37
+ return obj;
38
+ }
39
+ /** -- Pretty print -- */
40
+ const zeroPad = (num, places) => String(num).padStart(places, '0');
41
+ export function prettyDuration(date) {
42
+ return date.getSeconds() + "." + zeroPad(date.getMilliseconds(), 3);
43
+ }
44
+ /** */
45
+ export function prettyDate(date) {
46
+ return ""
47
+ + zeroPad(date.getHours(), 2)
48
+ + ":" + zeroPad(date.getMinutes(), 2)
49
+ + ":" + zeroPad(date.getSeconds(), 2)
50
+ + "." + zeroPad(date.getMilliseconds(), 3);
51
+ }
52
+ /** */
53
+ export function printAppInfo(appInfo) {
54
+ let print = `Happ "${appInfo.installed_app_id}" info: (status: ${JSON.stringify(appInfo.status)})`;
55
+ for (const installedCell of appInfo.cell_data) {
56
+ print += "\n - " + installedCell.role_id + ": " + CellIdStr(installedCell.cell_id);
57
+ }
58
+ return print;
59
+ }
60
+ /** */
61
+ export function printInstalledCell(installedCell) {
62
+ return `InstalledCell "${installedCell.roleInstanceId}": ${installedCell.dnaHash}`;
63
+ }
64
+ /** -- Experimental -- */
65
+ /**
66
+ *
67
+ */
68
+ export class Queue {
69
+ constructor() {
70
+ this._store = [];
71
+ }
72
+ get length() { return this._store.length; }
73
+ push(val) {
74
+ this._store.push(val);
75
+ }
76
+ pop() {
77
+ return this._store.shift();
78
+ }
79
+ isEmpty() { return this._store.length == 0; }
80
+ }
81
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE1D,OAAO,EAAC,SAAS,EAAiB,MAAM,SAAS,CAAC;AAElD,MAAM;AACN,MA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AAC;AAGD,yBAAyB;AAEzB;;GAEG;AACH,MAAM,OAAO,KAAK;IAAlB;QACU,WAAM,GAAQ,EAAE,CAAC;IAY3B,CAAC;IAVC,IAAI,MAAM,KAAY,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA,CAAA,CAAC;IAEhD,IAAI,CAAC,GAAM;QACT,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;IACD,GAAG;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED,OAAO,KAAc,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,CAAA,CAAA,CAAC;CACrD"}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@ddd-qc/cell-proxy",
3
+ "version": "0.9.0",
4
+ "description": "Wrapper for AppWebsocket",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.js",
7
+ "type": "module",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "lint": "eslint --ext .ts .",
13
+ "build": "tsc"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/ddd-mtl/dna-client.git"
18
+ },
19
+ "author": "",
20
+ "license": "CAL-1.0",
21
+ "bugs": {
22
+ "url": "https://github.com/ddd-mtl/dna-client/issues"
23
+ },
24
+ "homepage": "https://github.com/ddd-mtl/dna-client#readme",
25
+ "dependencies": {
26
+ "@holochain-open-dev/core-types": "^0.5.0",
27
+ "@holochain-open-dev/utils": "0.4.0",
28
+ "@holochain/client": "^0.9.3"
29
+ },
30
+ "devDependencies": {
31
+ "tslib": "^2.3.0",
32
+ "typescript": "^4.3.5"
33
+ }
34
+ }