holosphere 1.0.6 → 1.0.8

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,56 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+
6
+ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
7
+
8
+ This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
9
+
10
+ 0. Additional Definitions.
11
+ As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
12
+
13
+ “The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
14
+
15
+ An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
16
+
17
+ A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
18
+
19
+ The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
20
+
21
+ The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
22
+
23
+ 1. Exception to Section 3 of the GNU GPL.
24
+ You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
25
+
26
+ 2. Conveying Modified Versions.
27
+ If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
28
+
29
+ a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
30
+ b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
31
+ 3. Object Code Incorporating Material from Library Header Files.
32
+ The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
33
+
34
+ a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
35
+ b) Accompany the object code with a copy of the GNU GPL and this license document.
36
+ 4. Combined Works.
37
+ You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
38
+
39
+ a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
40
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
41
+ c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
42
+ d) Do one of the following:
43
+ 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
44
+ 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
45
+ e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
46
+ 5. Combined Libraries.
47
+ You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
48
+
49
+ a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
50
+ b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
51
+ 6. Revised Versions of the GNU Lesser General Public License.
52
+ The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
53
+
54
+ Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
55
+
56
+ If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
package/README.md ADDED
@@ -0,0 +1,176 @@
1
+ # HoloSphere
2
+
3
+ HoloSphere is a decentralized geospatial data management system that combines hierarchical hexagonal tiling (H3) with distributed data storage (GunDB) and AI-powered processing of information.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install holosphere
9
+ ```
10
+
11
+ ## Basic Usage
12
+
13
+ ```javascript
14
+ import HoloSphere from 'holosphere';
15
+
16
+ // Initialize HoloSphere
17
+ const holo = new HoloSphere('my-app');
18
+
19
+ // Optional: Initialize with OpenAI
20
+ const holoAI = new HoloSphere('my-app', 'your-openai-key');
21
+ ```
22
+
23
+ ## Core Features
24
+
25
+ ### User Management
26
+
27
+ ```javascript
28
+ // Create a new user
29
+ await holo.createUser('username', 'password');
30
+
31
+ // Login
32
+ await holo.login('username', 'password');
33
+
34
+ // Logout
35
+ await holo.logout();
36
+ ```
37
+
38
+ ### Schema Operations
39
+
40
+ ```javascript
41
+ // Define a schema for a lens
42
+ const schema = {
43
+ type: 'object',
44
+ properties: {
45
+ id: { type: 'string' },
46
+ data: { type: 'string' }
47
+ },
48
+ required: ['id', 'data']
49
+ };
50
+
51
+ // Set schema for a lens
52
+ await holo.setLensSchema('myLens', schema);
53
+
54
+ // Get schema for a lens
55
+ const lensSchema = await holo.getLensSchema('myLens');
56
+ ```
57
+
58
+ ### Global Data Operations
59
+
60
+ ```javascript
61
+ // Store data globally
62
+ await holo.putGlobalData('settings', {
63
+ id: 'config1',
64
+ theme: 'dark'
65
+ });
66
+
67
+ // Get all data from a table
68
+ const allSettings = await holo.getGlobalData('settings');
69
+
70
+ // Get specific data by key
71
+ const config = await holo.getGlobalDataKey('settings', 'config1');
72
+
73
+ // Delete a global table
74
+ await holo.deleteGlobalData('settings');
75
+ ```
76
+
77
+ ### Hex Data Operations
78
+
79
+ ```javascript
80
+ // Store data in a hex
81
+ await holo.putHexData('hex123', 'observations', {
82
+ id: 'obs1',
83
+ data: 'value'
84
+ });
85
+
86
+ // Get all data from a hex/lens
87
+ const data = await holo.getHexData('hex123', 'observations');
88
+
89
+ // Get specific data by key
90
+ const item = await holo.getHexKey('hex123', 'observations', 'obs1');
91
+
92
+ // Get raw GunDB node
93
+ const node = await holo.getHexNode('hex123', 'observations', 'obs1');
94
+
95
+ // Delete specific data
96
+ await holo.deleteHexData('hex123', 'observations', 'obs1');
97
+
98
+ // Delete a node by tag
99
+ await holo.deleteNode('nodeId', 'tag');
100
+
101
+ // Clear all data in a lens
102
+ await holo.clearlens('hex123', 'observations');
103
+ ```
104
+
105
+ ### Encrypted Data
106
+
107
+ ```javascript
108
+ // Store encrypted data (requires authenticated user)
109
+ await holo.putHexData('hex123', 'private', {
110
+ id: 'secret1',
111
+ data: 'sensitive'
112
+ }, true, 'encryption-key');
113
+
114
+ // Encrypt specific data
115
+ const encrypted = await holo.encrypt(data, 'secret-key');
116
+
117
+ // Decrypt data
118
+ const decrypted = await holo.decrypt(encrypted, 'secret-key');
119
+ ```
120
+
121
+ ### Geospatial Operations
122
+
123
+ ```javascript
124
+ // Get hex from coordinates
125
+ const hex = await holo.getHex(37.7749, -74.0060, 7);
126
+
127
+ // Get all scales for coordinates
128
+ const scales = holo.getScalespace(37.7749, -74.0060);
129
+
130
+ // Get all parent hexes
131
+ const parents = holo.getHexScalespace('hex123');
132
+
133
+ // Compute operations on hex data
134
+ await holo.compute('hex123', 'observations', 'summarize');
135
+
136
+ // Upcast data to parent hexes
137
+ await holo.upcast('hex123', 'observations', data);
138
+ ```
139
+
140
+ ### Real-time Subscriptions
141
+
142
+ ```javascript
143
+ // Subscribe to changes
144
+ holo.subscribe('hex123', 'observations', (data, key) => {
145
+ console.log('Updated data:', data);
146
+ console.log('Key:', key);
147
+ });
148
+ ```
149
+
150
+ ### Voting System
151
+
152
+ ```javascript
153
+ // Get final vote (including delegations)
154
+ const finalVote = holo.getFinalVote(userId, topic, votes);
155
+
156
+ // Get aggregated votes for a hex
157
+ const results = holo.aggregateVotes(hexId, topic);
158
+
159
+ // Delegate voting power
160
+ await holo.delegateVote(userId, topic, delegateId);
161
+
162
+ // Cast a vote
163
+ await holo.vote(userId, hexId, topic, voteChoice);
164
+ ```
165
+
166
+ ## License
167
+
168
+ GPL-3.0-or-later
169
+
170
+ ## Dependencies
171
+
172
+ - h3-js: Uber's H3 geospatial indexing system
173
+ - gun: Decentralized graph database
174
+ - ajv: JSON Schema validation
175
+ - openai: OpenAI API client (optional)
176
+
@@ -0,0 +1,12 @@
1
+ {
2
+ "presets": [
3
+ [
4
+ "@babel/preset-env",
5
+ {
6
+ "targets": {
7
+ "node": "current"
8
+ }
9
+ }
10
+ ]
11
+ ]
12
+ }
@@ -0,0 +1 @@
1
+
package/holosphere.d.ts CHANGED
@@ -1,20 +1,47 @@
1
1
  declare module 'holosphere' {
2
2
  export default class HoloSphere {
3
- constructor(name: string, openaikey?: string | null);
4
- subscribe(hex: string, lense: string, callback: (item: any, key: string) => void): void;
5
- put(hex: string, lense: string, content: any): Promise<void>;
6
- delete(id: string, tag: string): Promise<void>;
7
- get(hex: string, lense: string): Promise<any[]>;
8
- getKey(hex: string, lense: string, key: string): Promise<any | null>;
9
- getNode(hex: string, lense: string, key: string): Promise<any | null>;
10
- compute(hex: string, lense: string, operation: string): Promise<void>;
11
- clearlense(hex: string, lense: string): Promise<void>;
12
- summarize(history: string): Promise<string>;
13
- upcast(hex: string, lense: string, content: any): Promise<any>;
14
- updateParent(id: string, report: string): Promise<any>;
3
+ constructor(appName: string, openaikey?: string | null);
4
+
5
+ // User Management
6
+ createUser(username: string, password: string): Promise<object>;
7
+ login(username: string, password: string): Promise<object>;
8
+ logout(): Promise<void>;
9
+
10
+ // Schema Operations
11
+ setLensSchema(lens: string, schema: object): Promise<void>;
12
+ getLensSchema(lens: string): Promise<object | null>;
13
+
14
+ // Encryption Operations
15
+ encrypt(data: any, secret: string): Promise<string>;
16
+ decrypt(encryptedData: string, secret: string): Promise<any>;
17
+
18
+ // Global Data Operations
19
+ putGlobalData(tableName: string, data: object): Promise<void>;
20
+ getGlobalData(tableName: string): Promise<object | null>;
21
+ getGlobalDataKey(tableName: string, key: string): Promise<object | null>;
22
+ deleteGlobalData(tableName: string): Promise<void>;
23
+
24
+ // Hex Data Operations
25
+ putHexData(hexId: string, lens: string, content: object, encrypt?: boolean, secret?: string | null): Promise<void>;
26
+ getHexData(hexId: string, lens: string, secret?: string | null): Promise<Array<any>>;
27
+ getHexKey(hexId: string, lens: string, key: string): Promise<any | null>;
28
+ getHexNode(hexId: string, lens: string, key: string): Promise<any>;
29
+ deleteHexData(hexId: string, lens: string, contentId: string): Promise<void>;
30
+ deleteNode(nodeId: string, tag: string): Promise<void>;
31
+ clearlens(hex: string, lens: string): Promise<void>;
32
+
33
+ // Geospatial Operations
15
34
  getHex(lat: number, lng: number, resolution: number): Promise<string>;
16
35
  getScalespace(lat: number, lng: number): string[];
17
36
  getHexScalespace(hex: string): string[];
37
+ compute(hex: string, lens: string, operation: string): Promise<void>;
38
+ upcast(hex: string, lens: string, content: any): Promise<any>;
39
+
40
+ // Subscription
41
+ subscribe(hex: string, lens: string, callback: (data: any, key: string) => void): void;
42
+
43
+ // Voting System
44
+ getFinalVote(userId: string, topic: string, votes: object, visited?: Set<string>): string | null;
18
45
  aggregateVotes(hexId: string, topic: string): object;
19
46
  delegateVote(userId: string, topic: string, delegateTo: string): Promise<void>;
20
47
  vote(userId: string, hexId: string, topic: string, vote: string): Promise<void>;
package/holosphere.js CHANGED
@@ -12,7 +12,7 @@ class HoloSphere {
12
12
  constructor(appname, openaikey = null) {
13
13
  this.validator = new Ajv2019({ allErrors: false, strict: false });
14
14
  this.gun = Gun({
15
- peers: ['https://59.src.eco/gun'],
15
+ peers: ['http://gun.holons.io','https://59.src.eco/gun'],
16
16
  axe: false,
17
17
  // uuid: (content) => { // generate a unique id for each node
18
18
  // console.log('uuid', content);
@@ -21,7 +21,7 @@ class HoloSphere {
21
21
 
22
22
  this.gun = this.gun.get(appname)
23
23
  this.users = {}; // Initialize users
24
- this.hexagonVotes = {}; // Initialize hexagonVotes
24
+ this.holonagonVotes = {}; // Initialize holonagonVotes
25
25
 
26
26
  if (openaikey != null) {
27
27
  this.openai = new OpenAI({
@@ -31,18 +31,18 @@ class HoloSphere {
31
31
  }
32
32
 
33
33
  /**
34
- * Sets the JSON schema for a specific lense.
35
- * @param {string} lense - The lense identifier.
34
+ * Sets the JSON schema for a specific lens.
35
+ * @param {string} lens - The lens identifier.
36
36
  * @param {object} schema - The JSON schema to set.
37
37
  * @returns {Promise} - Resolves when the schema is set.
38
38
  */
39
- async setSchema(lense, schema) {
39
+ async setSchema(lens, schema) {
40
40
  return new Promise((resolve, reject) => {
41
- this.gun.get(lense).get('schema').put(JSON.stringify(schema), ack => {
41
+ this.gun.get(lens).get('schema').put(JSON.stringify(schema), ack => {
42
42
  if (ack.err) {
43
43
  resolve(new Error('Failed to add schema: ' + ack.err));
44
44
  } else {
45
- console.log('Schema added successfully under lense:', lense);
45
+ console.log('Schema added successfully under lens:', lens);
46
46
  resolve(ack);
47
47
  }
48
48
  })
@@ -50,13 +50,13 @@ class HoloSphere {
50
50
  }
51
51
 
52
52
  /**
53
- * Retrieves the JSON schema for a specific lense.
54
- * @param {string} lense - The lense identifier.
53
+ * Retrieves the JSON schema for a specific lens.
54
+ * @param {string} lens - The lens identifier.
55
55
  * @returns {Promise<object|null>} - The retrieved schema or null if not found.
56
56
  */
57
- async getSchema(lense) {
57
+ async getSchema(lens) {
58
58
  return new Promise((resolve) => {
59
- this.gun.get(lense).get('schema').once(data => {
59
+ this.gun.get(lens).get('schema').once(data => {
60
60
  if (data) {
61
61
  let parsed;
62
62
  try {
@@ -82,14 +82,16 @@ class HoloSphere {
82
82
  }
83
83
 
84
84
  /**
85
- * Stores content in the specified hex and lense.
86
- * @param {string} hex - The hex identifier.
87
- * @param {string} lense - The lense under which to store the content.
85
+ * Stores content in the specified holon and lens.
86
+ * @param {string} holon - The holon identifier.
87
+ * @param {string} lens - The lens under which to store the content.
88
88
  * @param {object} content - The content to store.
89
89
  */
90
- async put(hex, lense, content) {
91
- // Retrieve the schema for the lense
92
- let schema = await this.getSchema(lense)
90
+ async put(holon, lens, content) {
91
+ if (!holon || !lens || !content) return;
92
+ console.error('Error in put:', holon, lens, content);
93
+ // Retrieve the schema for the lens
94
+ let schema = await this.getSchema(lens)
93
95
  if (schema) {
94
96
  // Validate the content against the schema
95
97
  const valid = this.validator.validate(schema, content);
@@ -105,68 +107,92 @@ class HoloSphere {
105
107
  let noderef;
106
108
 
107
109
  if (content.id) { //use the user-defined id. Important to be able to send updates using put
108
- noderef = this.gun.get(lense).get(content.id).put(payload)
109
- this.gun.get(hex.toString()).get(lense).get(content.id).put(payload)
110
+ noderef = this.gun.get(lens).get(content.id).put(payload)
111
+ this.gun.get(holon.toString()).get(lens).get(content.id).put(payload)
110
112
  } else { // create a content-addressable reference like IPFS. Note: no updates possible using put
111
113
  const hashBuffer = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(payload));
112
114
  const hashArray = Array.from(new Uint8Array(hashBuffer));
113
- const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, "0")).join("");
114
- noderef = this.gun.get(lense).get(hashHex).put(payload)
115
- this.gun.get(hex.toString()).get(lense).get(hashHex).put(payload)
115
+ const hashholon = hashArray.map(byte => byte.toString(16).padStart(2, "0")).join("");
116
+ noderef = this.gun.get(lens).get(hashholon).put(payload)
117
+ this.gun.get(holon.toString()).get(lens).get(hashholon).put(payload)
116
118
  }
117
119
 
118
120
  }
119
121
 
120
- async putNode(hex, lense, node) {
121
- this.gun.get(hex).get(lense).set(node)
122
+ async putNode(holon, lens, node) {
123
+ this.gun.get(holon).get(lens).set(node)
122
124
  }
123
125
 
124
126
  async parse(data) {
125
- var parsed = {}
126
-
127
- if (data._ && data._["#"]) {
128
- // If the data is a reference, fetch the actual content
129
- let query = data._['#'].split('/')
130
- let hex = query[1]
131
- let lense = query[2]
132
- let key = query[3]
133
- parsed = await this.getKey(hex, lense, key)
134
-
135
- } else
136
-
137
- try {
138
- parsed = JSON.parse(data);
139
- } catch (e) {
140
- console.log('Invalid JSON:', data);
141
- parsed = data //return the raw data
127
+ let parsed = {};
128
+
129
+ if (typeof data === 'object' && data !== null) {
130
+ if (data._ && data._["#"]) {
131
+ // If the data is a reference, fetch the actual content
132
+ let query = data._['#'].split('/');
133
+ let holon = query[1];
134
+ let lens = query[2];
135
+ let key = query[3];
136
+ parsed = await this.getKey(holon, lens, key);
137
+ } else if (data._ && data._['>']) {
138
+ // This might be a gun node, try to get its value
139
+ const nodeValue = Object.values(data).find(v => typeof v !== 'object' && v !== '_');
140
+ if (nodeValue) {
141
+ try {
142
+ parsed = JSON.parse(nodeValue);
143
+ } catch (e) {
144
+ console.log('Invalid JSON in node value:', nodeValue);
145
+ parsed = nodeValue; // return the raw data
146
+ }
147
+ } else {
148
+ console.log('Unable to parse gun node:', data);
149
+ parsed = data; // return the original data
150
+ }
151
+ } else {
152
+ // Treat it as regular data
153
+ parsed = data;
154
+ }
155
+ } else {
156
+ // If it's not an object, try parsing it as JSON
157
+ try {
158
+ parsed = JSON.parse(data);
159
+ } catch (e) {
160
+ console.log('Invalid JSON:', data);
161
+ parsed = data; // return the raw data
162
+ }
142
163
  }
143
- return parsed
164
+
165
+ return parsed;
144
166
  }
145
167
 
146
168
  /**
147
- * Retrieves content from the specified hex and lense.
148
- * @param {string} hex - The hex identifier.
149
- * @param {string} lense - The lense from which to retrieve content.
169
+ * Retrieves content from the specified holon and lens.
170
+ * @param {string} holon - The holon identifier.
171
+ * @param {string} lens - The lens from which to retrieve content.
150
172
  * @returns {Promise<Array<object>>} - The retrieved content.
151
173
  */
152
- async get(hex, lense) {
153
- // Wrap the GunDB operation in a promise
154
- //retrieve lense schema
155
- const schema = await this.getSchema(lense);
174
+ async get(holon, lens) {
175
+ if (!holon || !lens) {
176
+ console.log('Wrong get:', holon, lens)
177
+ return;
178
+ }
179
+ // Wrap the gun operation in a promise
180
+ //retrieve lens schema
181
+ const schema = await this.getSchema(lens);
156
182
 
157
183
  if (!schema) {
158
- console.log('The schema for "' + lense + '" is not defined');
184
+ console.log('The schema for "' + lens + '" is not defined');
159
185
  // return null; // No schema found, return null if strict about it
160
186
  }
161
187
 
162
188
  return new Promise(async (resolve, reject) => {
163
189
  let output = []
164
190
  let counter = 0
165
- this.gun.get(hex.toString()).get(lense).once((data, key) => {
191
+ this.gun.get(holon.toString()).get(lens).once((data, key) => {
166
192
  if (data) {
167
193
  const maplenght = Object.keys(data).length - 1
168
194
  console.log('Map length:', maplenght)
169
- this.gun.get(hex.toString()).get(lense).map().once(async (itemdata, key) => {
195
+ this.gun.get(holon.toString()).get(lens).map().once(async (itemdata, key) => {
170
196
  counter += 1
171
197
  if (itemdata) {
172
198
  let parsed = await this.parse (itemdata)
@@ -176,7 +202,7 @@ class HoloSphere {
176
202
  let valid = this.validator.validate(schema, parsed);
177
203
  if (!valid || parsed == null || parsed == undefined) {
178
204
  console.log('Removing Invalid content:', this.validator.errors);
179
- this.gun.get(hex).get(lense).get(key).put(null);
205
+ this.gun.get(holon).get(lens).get(key).put(null);
180
206
 
181
207
  } else {
182
208
  output.push(parsed);
@@ -199,18 +225,26 @@ class HoloSphere {
199
225
  }
200
226
 
201
227
  /**
202
- * Retrieves a specific key from the specified hex and lense.
203
- * @param {string} hex - The hex identifier.
204
- * @param {string} lense - The lense from which to retrieve the key.
228
+ * Retrieves a specific key from the specified holon and lens.
229
+ * @param {string} holon - The holon identifier.
230
+ * @param {string} lens - The lens from which to retrieve the key.
205
231
  * @param {string} key - The specific key to retrieve.
206
232
  * @returns {Promise<object|null>} - The retrieved content or null if not found.
207
233
  */
208
- async getKey(hex, lense, key) {
234
+ async getKey(holon, lens, key) {
209
235
  return new Promise((resolve) => {
210
236
  // Use Gun to get the data
211
- this.gun.get(hex).get(lense).get(key).once((data, key) => {
237
+ this.gun.get(holon).get(lens).get(key).once((data, key) => {
212
238
  if (data) {
213
- resolve(JSON.parse(data)); // Resolve the promise with the data if data is found
239
+ console.log('Data getting parsed:', data)
240
+ try {
241
+ let parsed = JSON.parse(data); // Resolve the promise with the data if data is found
242
+ resolve(parsed);
243
+ }
244
+ catch (e) {
245
+ resolve(data)
246
+ }
247
+
214
248
  } else {
215
249
  resolve(null); // Reject the promise if no data is found
216
250
  }
@@ -220,33 +254,132 @@ class HoloSphere {
220
254
  }
221
255
 
222
256
  /**
223
- * Retrieves a specific gundb node from the specified hex and lense.
224
- * @param {string} hex - The hex identifier.
225
- * @param {string} lense - The lense from which to retrieve the key.
257
+ * Retrieves a specific gun node from the specified holon and lens.
258
+ * @param {string} holon - The holon identifier.
259
+ * @param {string} lens - The lens from which to retrieve the key.
226
260
  * @param {string} key - The specific key to retrieve.
227
261
  * @returns {Promise<object|null>} - The retrieved content or null if not found.
228
262
  */
229
- getNode(hex, lense, key) {
263
+ getNode(holon, lens, key) {
230
264
  // Use Gun to get the data
231
- return this.gun.get(hex).get(lense).get(key)
265
+ return this.gun.get(holon).get(lens).get(key)
266
+ }
267
+
268
+ //GLOBAL FUNCTIONS
269
+ async deleteNode(nodeId, tag) {
270
+ await this.gun.get(nodeId).get(tag).put(null)
271
+ }
272
+ // ================================ GLOBAL FUNCTIONS ================================
273
+ /**
274
+ * Stores data in a global (non-holon-specific) table.
275
+ * @param {string} table - The table name to store data in.
276
+ * @param {object} data - The data to store. If it has an 'id' field, it will be used as the key.
277
+ * @returns {Promise<void>}
278
+ */
279
+ async putGlobal(tableName, data) {
280
+ return new Promise((resolve, reject) => {
281
+ if (!tableName || !data) {
282
+ reject(new Error('Table name and data are required'));
283
+ return;
284
+ }
285
+
286
+ if (data.id) {
287
+ this.gun.get(tableName).get(data.id).put(JSON.stringify(data), ack => {
288
+ if (ack.err) {
289
+ reject(new Error(ack.err));
290
+ } else {
291
+ resolve();
292
+ }
293
+ });
294
+ } else {
295
+ this.gun.get(tableName).put(JSON.stringify(data), ack => {
296
+ if (ack.err) {
297
+ reject(new Error(ack.err));
298
+ } else {
299
+ resolve();
300
+ }
301
+ });
302
+ }
303
+ });
304
+ }
305
+
306
+ /**
307
+ * Retrieves a specific key from a global table.
308
+ * @param {string} tableName - The table name to retrieve from.
309
+ * @param {string} key - The key to retrieve.
310
+ * @returns {Promise<object|null>} - The parsed data for the key or null if not found.
311
+ */
312
+ async getGlobal(tableName, key) {
313
+ return new Promise((resolve) => {
314
+ this.gun.get(tableName).get(key).once((data) => {
315
+ if (!data) {
316
+ resolve(null);
317
+ return;
318
+ }
319
+ try {
320
+ const parsed = JSON.parse(data);
321
+ resolve(parsed);
322
+ } catch (e) {
323
+ resolve(null);
324
+ }
325
+ });
326
+ });
232
327
  }
233
328
 
329
+ /**
330
+ * Retrieves all data from a global table.
331
+ * @param {string} tableName - The table name to retrieve data from.
332
+ * @returns {Promise<object|null>} - The parsed data from the table or null if not found.
333
+ */
334
+ async getAllGlobal(tableName) {
335
+ return new Promise((resolve) => {
336
+ this.gun.get(tableName).once((data) => {
337
+ if (!data) {
338
+ resolve(null);
339
+ return;
340
+ }
341
+ try {
342
+ const parsed = JSON.parse(data);
343
+ resolve(parsed);
344
+ } catch (e) {
345
+ resolve(null);
346
+ }
347
+ });
348
+ });
349
+ }
234
350
 
351
+
352
+
353
+ /**
354
+ * Deletes an entire global table.
355
+ * @param {string} table - The table name to delete.
356
+ * @returns {Promise<void>}
357
+ */
358
+ async deleteAllGlobal(tableName) {
359
+
360
+ return new Promise((resolve) => {
361
+ this.gun.get(tableName).map().put(null)
362
+ this.gun.get(tableName).put(null, ack => {
363
+ resolve();
364
+ });
365
+ });
366
+ }
235
367
 
368
+ // ================================ COMPUTE FUNCTIONS ================================
236
369
  /**
237
- * Computes summaries based on the content within a hex and lense.
238
- * @param {string} hex - The hex identifier.
239
- * @param {string} lense - The lense to compute.
370
+ * Computes summaries based on the content within a holon and lens.
371
+ * @param {string} holon - The holon identifier.
372
+ * @param {string} lens - The lens to compute.
240
373
  * @param {string} operation - The operation to perform.
241
374
  */
242
- async compute(hex, lense, operation) {
375
+ async compute(holon, lens, operation) {
243
376
 
244
- let res = h3.getResolution(hex);
377
+ let res = h3.getResolution(holon);
245
378
  if (res < 1 || res > 15) return;
246
379
  console.log(res)
247
- let parent = h3.cellToParent(hex, res - 1);
380
+ let parent = h3.cellToParent(holon, res - 1);
248
381
  let siblings = h3.cellToChildren(parent, res);
249
- console.log(hex, parent, siblings, res)
382
+ console.log(holon, parent, siblings, res)
250
383
 
251
384
  let content = [];
252
385
  let promises = [];
@@ -258,7 +391,7 @@ class HoloSphere {
258
391
  resolve(); // Resolve the promise to prevent it from hanging
259
392
  }, 1000); // Timeout of 5 seconds
260
393
 
261
- this.gun.get(siblings[i]).get(lense).map().once((data, key) => {
394
+ this.gun.get(siblings[i]).get(lens).map().once((data, key) => {
262
395
  clearTimeout(timeout); // Clear the timeout if data is received
263
396
  if (data) {
264
397
  content.push(data.content);
@@ -274,23 +407,23 @@ class HoloSphere {
274
407
  console.log('Computed:', computed)
275
408
  let node = await this.gun.get(parent + '_summary').put({ id: parent + '_summary', content: computed })
276
409
 
277
- this.put(parent, lense, node);
278
- this.compute(parent, lense, operation)
410
+ this.put(parent, lens, node);
411
+ this.compute(parent, lens, operation)
279
412
  }
280
413
 
281
414
  /**
282
- * Clears all entities under a specific hex and lense.
283
- * @param {string} hex - The hex identifier.
284
- * @param {string} lense - The lense to clear.
415
+ * Clears all entities under a specific holon and lens.
416
+ * @param {string} holon - The holon identifier.
417
+ * @param {string} lens - The lens to clear.
285
418
  */
286
- async clearlense(hex, lense) {
419
+ async clearlens(holon, lens) {
287
420
  let entities = {};
288
421
 
289
422
  // Get list out of Gun
290
- this.gun.get(hex).get(lense).map().once((data, key) => {
423
+ this.gun.get(holon).get(lens).map().once((data, key) => {
291
424
  //entities = data;
292
425
  //const id = Object.keys(entities)[0] // since this would be in object form, you can manipulate it as you would like.
293
- this.gun.get(hex).get(lense).put({ [key]: null })
426
+ this.gun.get(holon).get(lens).put({ [key]: null })
294
427
  })
295
428
  }
296
429
 
@@ -333,30 +466,30 @@ class HoloSphere {
333
466
  }
334
467
 
335
468
  /**
336
- * Upcasts content to parent hexagons recursively.
337
- * @param {string} hex - The current hex identifier.
338
- * @param {string} lense - The lense under which to upcast.
469
+ * Upcasts content to parent holonagons recursively.
470
+ * @param {string} holon - The current holon identifier.
471
+ * @param {string} lens - The lens under which to upcast.
339
472
  * @param {object} content - The content to upcast.
340
473
  * @returns {Promise<object>} - The upcasted content.
341
474
  */
342
- async upcast(hex, lense, content) {
343
- let res = h3.getResolution(hex)
475
+ async upcast(holon, lens, content) {
476
+ let res = h3.getResolution(holon)
344
477
  if (res == 0) {
345
- await this.putNode(hex, lense, content)
478
+ await this.putNode(holon, lens, content)
346
479
  return content
347
480
  }
348
481
  else {
349
- console.log('Upcasting ', hex, lense, content, res)
350
- await this.putNode(hex, lense, content)
351
- let parent = h3.cellToParent(hex, res - 1)
352
- return this.upcast(parent, lense, content)
482
+ console.log('Upcasting ', holon, lens, content, res)
483
+ await this.putNode(holon, lens, content)
484
+ let parent = h3.cellToParent(holon, res - 1)
485
+ return this.upcast(parent, lens, content)
353
486
  }
354
487
  }
355
488
 
356
489
 
357
490
  /**
358
- * Updates the parent hexagon with a new report.
359
- * @param {string} id - The child hex identifier.
491
+ * Updates the parent holonagon with a new report.
492
+ * @param {string} id - The child holon identifier.
360
493
  * @param {string} report - The report to update.
361
494
  * @returns {Promise<object>} - The updated parent information.
362
495
  */
@@ -376,21 +509,21 @@ class HoloSphere {
376
509
 
377
510
 
378
511
  /**
379
- * Converts latitude and longitude to a hex identifier.
512
+ * Converts latitude and longitude to a holon identifier.
380
513
  * @param {number} lat - The latitude.
381
514
  * @param {number} lng - The longitude.
382
515
  * @param {number} resolution - The resolution level.
383
- * @returns {Promise<string>} - The resulting hex identifier.
516
+ * @returns {Promise<string>} - The resulting holon identifier.
384
517
  */
385
- async getHex(lat, lng, resolution) {
518
+ async getHolon(lat, lng, resolution) {
386
519
  return h3.latLngToCell(lat, lng, resolution);
387
520
  }
388
521
 
389
522
  /**
390
- * Retrieves all containing hexagons at all scales for given coordinates.
523
+ * Retrieves all containing holonagons at all scales for given coordinates.
391
524
  * @param {number} lat - The latitude.
392
525
  * @param {number} lng - The longitude.
393
- * @returns {Array<string>} - List of hex identifiers.
526
+ * @returns {Array<string>} - List of holon identifiers.
394
527
  */
395
528
  getScalespace(lat, lng) {
396
529
  let list = []
@@ -403,31 +536,32 @@ class HoloSphere {
403
536
  }
404
537
 
405
538
  /**
406
- * Retrieves all containing hexagons at all scales for a given hex.
407
- * @param {string} hex - The hex identifier.
408
- * @returns {Array<string>} - List of hex identifiers.
539
+ * Retrieves all containing holonagons at all scales for a given holon.
540
+ * @param {string} holon - The holon identifier.
541
+ * @returns {Array<string>} - List of holon identifiers.
409
542
  */
410
- getHexScalespace(hex) {
543
+ getHolonScalespace(holon) {
411
544
  let list = []
412
- let res = h3.getResolution(hex)
545
+ let res = h3.getResolution(holon)
413
546
  for (let i = res; i >= 0; i--) {
414
- list.push(h3.cellToParent(hex, i))
547
+ list.push(h3.cellToParent(holon, i))
415
548
  }
416
549
  return list
417
550
  }
418
551
 
419
552
  /**
420
- * Subscribes to changes in a specific hex and lense.
421
- * @param {string} hex - The hex identifier.
422
- * @param {string} lense - The lense to subscribe to.
553
+ * Subscribes to changes in a specific holon and lens.
554
+ * @param {string} holon - The holon identifier.
555
+ * @param {string} lens - The lens to subscribe to.
423
556
  * @param {function} callback - The callback to execute on changes.
424
557
  */
425
- subscribe(hex, lense, callback) {
426
- this.gun.get(hex).get(lense).map().on((data, key) => {
558
+ subscribe(holon, lens, callback) {
559
+ this.gun.get(holon).get(lens).map().on((data, key) => {
427
560
  callback(data, key)
428
561
  })
429
562
  }
430
563
 
564
+ // ================================ GOVERNANCE FUNCTIONS ================================
431
565
  /**
432
566
  * Retrieves the final vote for a user, considering delegations.
433
567
  * @param {string} userId - The user's identifier.
@@ -454,16 +588,16 @@ class HoloSphere {
454
588
  }
455
589
 
456
590
  /**
457
- * Aggregates votes for a specific hex and topic.
458
- * @param {string} hexId - The hex identifier.
591
+ * Aggregates votes for a specific holon and topic.
592
+ * @param {string} holonId - The holon identifier.
459
593
  * @param {string} topic - The voting topic.
460
594
  * @returns {object} - Aggregated vote counts.
461
595
  */
462
- aggregateVotes(hexId, topic) {
463
- if (!this.hexagonVotes[hexId] || !this.hexagonVotes[hexId][topic]) {
596
+ aggregateVotes(holonId, topic) {
597
+ if (!this.holonagonVotes[holonId] || !this.holonagonVotes[holonId][topic]) {
464
598
  return {}; // Handle undefined votes
465
599
  }
466
- const votes = this.hexagonVotes[hexId][topic];
600
+ const votes = this.holonagonVotes[holonId][topic];
467
601
  const aggregatedVotes = {};
468
602
 
469
603
  Object.keys(votes).forEach(userId => {
@@ -492,24 +626,21 @@ class HoloSphere {
492
626
  }
493
627
 
494
628
  /**
495
- * Casts a vote for a user on a specific topic and hex.
629
+ * Casts a vote for a user on a specific topic and holon.
496
630
  * @param {string} userId - The user's identifier.
497
- * @param {string} hexId - The hex identifier.
631
+ * @param {string} holonId - The holon identifier.
498
632
  * @param {string} topic - The voting topic.
499
633
  * @param {string} vote - The vote choice.
500
634
  */
501
- async vote(userId, hexId, topic, vote) {
635
+ async vote(userId, holonId, topic, vote) {
502
636
  const response = await fetch('/vote', {
503
637
  method: 'POST',
504
638
  headers: { 'Content-Type': 'application/json' },
505
- body: JSON.stringify({ userId, hexId, topic, vote })
639
+ body: JSON.stringify({ userId, holonId, topic, vote })
506
640
  });
507
641
  alert(await response.text());
508
642
  }
509
643
 
510
-
511
-
512
-
513
644
  }
514
645
 
515
646
  export default HoloSphere;
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "holosphere",
3
- "version": "1.0.6",
4
- "description": "Holonic Geospatial Communication Infrastructure based on h3.js and gun.js",
3
+ "version": "1.0.8",
4
+ "description": "Holonic Geospatial Communication Infrastructure",
5
5
  "main": "holosphere.js",
6
+ "types": "holosphere.d.ts",
6
7
  "type": "module",
7
8
  "scripts": {
8
- "test": "echo \"Error: no test specified\" && exit 1"
9
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
9
10
  },
10
11
  "author": "Roberto Valenti",
11
12
  "license": "GPL-3.0-or-later",
@@ -14,5 +15,16 @@
14
15
  "gun": "^0.2020.1240",
15
16
  "h3-js": "^4.1.0",
16
17
  "openai": "^4.29.2"
18
+ },
19
+ "devDependencies": {
20
+ "jest": "^29.7.0",
21
+ "jest-environment-node": "^29.7.0"
22
+ },
23
+ "jest": {
24
+ "testEnvironment": "node",
25
+ "transform": {},
26
+ "moduleNameMapper": {
27
+ "^(\\.{1,2}/.*)\\.js$": "$1"
28
+ }
17
29
  }
18
30
  }
@@ -0,0 +1,199 @@
1
+ import HoloSphere from '../holosphere.js';
2
+ import * as h3 from 'h3-js';
3
+
4
+ describe('HoloSphere', () => {
5
+ let holoSphere;
6
+ const testAppName = 'test-app';
7
+
8
+ beforeEach(() => {
9
+ holoSphere = new HoloSphere(testAppName);
10
+ });
11
+
12
+ describe('Constructor', () => {
13
+ test('should create instance with app name', () => {
14
+ expect(holoSphere).toBeInstanceOf(HoloSphere);
15
+ expect(holoSphere.gunDb).toBeDefined();
16
+ expect(holoSphere.validator).toBeDefined();
17
+ expect(holoSphere.aiClient).toBeUndefined();
18
+ });
19
+
20
+ test('should initialize with OpenAI when key provided', () => {
21
+ const hsWithAI = new HoloSphere(testAppName, 'fake-key');
22
+ expect(hsWithAI.aiClient).toBeDefined();
23
+ });
24
+ });
25
+
26
+ describe('Schema Operations', () => {
27
+ const testLens = 'testLens';
28
+ const validSchema = {
29
+ type: 'object',
30
+ properties: {
31
+ id: { type: 'string' },
32
+ data: { type: 'string' }
33
+ },
34
+ required: ['id', 'data']
35
+ };
36
+
37
+ test('should set and get lens schema', async () => {
38
+ await holoSphere.setLensSchema(testLens, validSchema);
39
+ const result = await holoSphere.getLensSchema(testLens);
40
+ expect(result).toEqual(validSchema);
41
+ });
42
+
43
+ test('should validate data against schema', async () => {
44
+ const validData = { id: 'test123', data: 'test data' };
45
+ const invalidData = { id: 123, data: ['wrong type'] };
46
+
47
+ await holoSphere.setLensSchema(testLens, validSchema);
48
+
49
+ const validResult = holoSphere.validator.validate(validSchema, validData);
50
+ expect(validResult).toBe(true);
51
+
52
+ const invalidResult = holoSphere.validator.validate(validSchema, invalidData);
53
+ expect(invalidResult).toBe(false);
54
+ });
55
+ });
56
+
57
+ describe('Data Operations', () => {
58
+ const testHex = h3.latLngToCell(40.7128, -74.0060, 7);
59
+ const testLens = 'testLens';
60
+ const testContent = { id: '123', data: 'test' };
61
+
62
+ test('should put and get hex data', async () => {
63
+ await holoSphere.putHexData(testHex, testLens, testContent);
64
+ const result = await holoSphere.getHexData(testHex, testLens);
65
+ expect(Array.isArray(result)).toBeTruthy();
66
+ expect(result.some(item => item.id === testContent.id)).toBeTruthy();
67
+ }, 10000);
68
+
69
+ test('should get hex key', async () => {
70
+ await holoSphere.putHexData(testHex, testLens, testContent);
71
+ const result = await holoSphere.getHexKey(testHex, testLens, testContent.id);
72
+ expect(result).toBeDefined();
73
+ expect(result.id).toBe(testContent.id);
74
+ }, 10000);
75
+
76
+ test('should delete hex data', async () => {
77
+ await holoSphere.putHexData(testHex, testLens, testContent);
78
+ await holoSphere.deleteHexData(testHex, testLens, testContent.id);
79
+ const result = await holoSphere.getHexKey(testHex, testLens, testContent.id);
80
+ expect(result).toBeNull();
81
+ }, 10000);
82
+ });
83
+
84
+ describe('Global Data Operations', () => {
85
+ const tableName = 'testTable';
86
+ const testData = { id: 'test1', value: 'testValue' };
87
+
88
+ test('should put and get global data', async () => {
89
+ await holoSphere.putGlobalData(tableName, testData);
90
+ // Add delay to allow Gun to process
91
+ await new Promise(resolve => setTimeout(resolve, 1000));
92
+
93
+ const result = await holoSphere.getGlobalData(tableName);
94
+ expect(result).toBeDefined();
95
+ if (result) {
96
+ expect(result.id).toBe(testData.id);
97
+ }
98
+ }, 15000);
99
+
100
+ test('should get global data key', async () => {
101
+ await holoSphere.putGlobalData(tableName, testData);
102
+ // Add delay to allow Gun to process
103
+ await new Promise(resolve => setTimeout(resolve, 1000));
104
+
105
+ const result = await holoSphere.getGlobalDataKey(tableName, testData.id);
106
+ expect(result).toBeDefined();
107
+ if (result) {
108
+ expect(result.id).toBe(testData.id);
109
+ }
110
+ }, 15000);
111
+
112
+ test('should delete global data', async () => {
113
+ await holoSphere.putGlobalData(tableName, testData);
114
+ // Add delay to allow Gun to process
115
+ await new Promise(resolve => setTimeout(resolve, 1000));
116
+
117
+ await holoSphere.deleteGlobalData(tableName);
118
+ // Add delay to allow Gun to process
119
+ await new Promise(resolve => setTimeout(resolve, 1000));
120
+
121
+ const result = await holoSphere.getGlobalData(tableName);
122
+ expect(result).toBeNull();
123
+ }, 15000);
124
+
125
+ afterEach(async () => {
126
+ // Clean up after each test
127
+ await holoSphere.deleteGlobalData(tableName);
128
+ await new Promise(resolve => setTimeout(resolve, 1000));
129
+ });
130
+ });
131
+
132
+ describe('Encryption Operations', () => {
133
+ const testSecret = 'secret123';
134
+ const testData = { message: 'secret message' };
135
+
136
+ test('should encrypt and decrypt data', async () => {
137
+ const encrypted = await holoSphere.encrypt(testData, testSecret);
138
+ expect(encrypted).toBeDefined();
139
+
140
+ const decrypted = await holoSphere.decrypt(encrypted, testSecret);
141
+ expect(decrypted).toEqual(testData);
142
+ });
143
+
144
+ test('should handle encrypted hex data', async () => {
145
+ const testHex = h3.latLngToCell(40.7128, -74.0060, 7);
146
+ const testLens = 'testLens';
147
+ const testContent = { id: 'test123', data: 'secret data' };
148
+
149
+ // Create and login test user
150
+ try {
151
+ await holoSphere.createUser('testuser', 'testpass');
152
+ await holoSphere.login('testuser', 'testpass');
153
+ } catch (error) {
154
+ console.log('User already exists or login failed');
155
+ }
156
+
157
+ await holoSphere.putHexData(testHex, testLens, testContent, true, testSecret);
158
+ const result = await holoSphere.getHexData(testHex, testLens, testSecret);
159
+
160
+ expect(Array.isArray(result)).toBeTruthy();
161
+ await holoSphere.logout();
162
+ }, 15000);
163
+ });
164
+
165
+ describe('Geospatial Operations', () => {
166
+ const lat = 40.7128;
167
+ const lng = -74.0060;
168
+ const resolution = 7;
169
+
170
+ test('should get hex from coordinates', async () => {
171
+ const hex = await holoSphere.getHex(lat, lng, resolution);
172
+ expect(hex).toBeDefined();
173
+ expect(typeof hex).toBe('string');
174
+ });
175
+
176
+ test('should get scalespace from coordinates', () => {
177
+ const scales = holoSphere.getScalespace(lat, lng);
178
+ expect(Array.isArray(scales)).toBeTruthy();
179
+ expect(scales.length).toBe(15);
180
+ });
181
+
182
+ test('should get hex scalespace', () => {
183
+ const hex = h3.latLngToCell(lat, lng, resolution);
184
+ const scales = holoSphere.getHexScalespace(hex);
185
+ expect(Array.isArray(scales)).toBeTruthy();
186
+ expect(scales.length).toBe(resolution + 1);
187
+ });
188
+ });
189
+
190
+ afterAll(async () => {
191
+ // Clean up test data
192
+ const testLens = 'testLens';
193
+ const testHex = h3.latLngToCell(40.7128, -74.0060, 7);
194
+ await holoSphere.clearlens(testHex, testLens);
195
+
196
+ // Allow time for Gun to process
197
+ await new Promise(resolve => setTimeout(resolve, 1000));
198
+ });
199
+ });