@dyne/interfacer-client 0.1.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/dist/index.js ADDED
@@ -0,0 +1,2275 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/crypto/zenroom-bridge.ts
12
+ var zenroom_bridge_exports = {};
13
+ __export(zenroom_bridge_exports, {
14
+ hashFinal: () => hashFinal,
15
+ hashInit: () => hashInit,
16
+ hashUpdate: () => hashUpdate,
17
+ zencodeExec: () => zencodeExec
18
+ });
19
+ async function zencodeExec(contract, params) {
20
+ const zenroom = await import("zenroom");
21
+ const { result, logs } = await zenroom.zencode_exec(contract, {
22
+ data: params.data,
23
+ keys: params.keys || ""
24
+ });
25
+ return { result, logs };
26
+ }
27
+ async function hashInit(algorithm) {
28
+ const zenroom = await import("zenroom");
29
+ const { result, logs } = await zenroom.zenroom_hash_init(algorithm);
30
+ return { result, logs };
31
+ }
32
+ async function hashUpdate(ctx, hexData) {
33
+ const zenroom = await import("zenroom");
34
+ const { result, logs } = await zenroom.zenroom_hash_update(ctx, hexData);
35
+ return { result, logs };
36
+ }
37
+ async function hashFinal(ctx) {
38
+ const zenroom = await import("zenroom");
39
+ const { result, logs } = await zenroom.zenroom_hash_final(ctx);
40
+ return { result, logs };
41
+ }
42
+ var init_zenroom_bridge = __esm({
43
+ "src/crypto/zenroom-bridge.ts"() {
44
+ "use strict";
45
+ }
46
+ });
47
+
48
+ // src/zenflows-crypto/src/sign_graphql.zen
49
+ var sign_graphql_default;
50
+ var init_sign_graphql = __esm({
51
+ "src/zenflows-crypto/src/sign_graphql.zen"() {
52
+ sign_graphql_default = "# SPDX-License-Identifier: AGPL-3.0-or-later\n# Copyright (C) 2022-2023 Dyne.org foundation <foundation@dyne.org>.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nScenario eddsa: sign a graph query\nGiven I have a 'base64' named 'gql'\nGiven I have the 'keyring'\n\n# Fix Apollo's mingling with query string\nWhen I remove spaces in 'gql'\nand I compact ascii strings in 'gql'\n\nWhen I create the eddsa signature of 'gql'\nAnd I create the hash of 'gql'\n\nThen print 'eddsa signature' as 'base64'\nThen print 'gql' as 'base64'\nThen print 'hash' as 'hex'\n";
53
+ }
54
+ });
55
+
56
+ // src/crypto/sign.ts
57
+ import base64url from "base64url";
58
+ async function signGraphQLRequest(body, store) {
59
+ const eddsaKey = store.getItem(SIGNING_KEYS.privateKey);
60
+ const username = store.getItem(SIGNING_KEYS.username);
61
+ if (!eddsaKey) {
62
+ throw new Error("Missing EdDSA private key. Authenticate first.");
63
+ }
64
+ const keys = JSON.stringify({ keyring: { eddsa: eddsaKey } });
65
+ const data = JSON.stringify({
66
+ gql: Buffer.from(body, "utf8").toString("base64")
67
+ });
68
+ const { result } = await zencodeExec(SIGN_CONTRACT, { data, keys });
69
+ const parsed = JSON.parse(result);
70
+ return {
71
+ "zenflows-sign": parsed.eddsa_signature,
72
+ "zenflows-user": username || "",
73
+ "zenflows-hash": parsed.hash
74
+ };
75
+ }
76
+ async function signDidRequest(body, store) {
77
+ const eddsaKey = store.getItem(SIGNING_KEYS.privateKey);
78
+ const pk = store.getItem(SIGNING_KEYS.publicKey);
79
+ if (!eddsaKey) {
80
+ throw new Error("Missing EdDSA private key. Authenticate first.");
81
+ }
82
+ const keys = JSON.stringify({ keyring: { eddsa: eddsaKey } });
83
+ const data = JSON.stringify({
84
+ gql: Buffer.from(body, "utf8").toString("base64")
85
+ });
86
+ const { result } = await zencodeExec(SIGN_CONTRACT, { data, keys });
87
+ const parsed = JSON.parse(result);
88
+ return {
89
+ "did-sign": parsed.eddsa_signature,
90
+ "did-pk": pk || ""
91
+ };
92
+ }
93
+ async function signFileUpload(checksumHex, store) {
94
+ const eddsaKey = store.getItem(SIGNING_KEYS.privateKey);
95
+ if (!eddsaKey) {
96
+ throw new Error("Missing EdDSA private key. Authenticate first.");
97
+ }
98
+ const keys = JSON.stringify({ keyring: { eddsa: eddsaKey } });
99
+ const data = JSON.stringify({ gql: checksumHex });
100
+ const { result } = await zencodeExec(SIGN_CONTRACT, { data, keys });
101
+ const parsed = JSON.parse(result);
102
+ return parsed.eddsa_signature;
103
+ }
104
+ async function hashFileForZenflows(arrayBuffer) {
105
+ const { hashInit: hashInit2, hashUpdate: hashUpdate2, hashFinal: hashFinal2 } = await Promise.resolve().then(() => (init_zenroom_bridge(), zenroom_bridge_exports));
106
+ const bytesChunkSize = 1024 * 64;
107
+ let ctx = await hashInit2("sha512");
108
+ for (let i = 0; i < arrayBuffer.byteLength; i += bytesChunkSize) {
109
+ const upperLimit = i + bytesChunkSize > arrayBuffer.byteLength ? arrayBuffer.byteLength : i + bytesChunkSize;
110
+ const chunk = new Uint8Array(arrayBuffer.slice(i, upperLimit));
111
+ const hex = uint8ArrayToHex(chunk);
112
+ ctx = await hashUpdate2(ctx.result, hex);
113
+ }
114
+ ctx = await hashFinal2(ctx.result);
115
+ return base64url.fromBase64(ctx.result);
116
+ }
117
+ function uint8ArrayToHex(uint8Array) {
118
+ return Array.from(uint8Array).map((byte) => byte.toString(16).padStart(2, "0")).join("");
119
+ }
120
+ var SIGN_CONTRACT, SIGNING_KEYS;
121
+ var init_sign = __esm({
122
+ "src/crypto/sign.ts"() {
123
+ "use strict";
124
+ init_sign_graphql();
125
+ init_zenroom_bridge();
126
+ SIGN_CONTRACT = sign_graphql_default;
127
+ SIGNING_KEYS = {
128
+ privateKey: "eddsaPrivateKey",
129
+ publicKey: "eddsaPublicKey",
130
+ username: "authUsername"
131
+ };
132
+ }
133
+ });
134
+
135
+ // src/files/hashing.ts
136
+ var hashing_exports = {};
137
+ __export(hashing_exports, {
138
+ dppAttachmentToProjectModel: () => dppAttachmentToProjectModel,
139
+ formatImageSrc: () => formatImageSrc,
140
+ getResourceImage: () => getResourceImage,
141
+ hashFileForZenflowsUpload: () => hashFileForZenflowsUpload,
142
+ hashFileSHA256: () => hashFileSHA256,
143
+ prepFileForZenflows: () => prepFileForZenflows,
144
+ prepFilesForZenflows: () => prepFilesForZenflows,
145
+ uploadFileToDpp: () => uploadFileToDpp,
146
+ uploadModelFilesToDpp: () => uploadModelFilesToDpp
147
+ });
148
+ async function hashFileForZenflowsUpload(file) {
149
+ return hashFileForZenflows(await file.arrayBuffer());
150
+ }
151
+ async function hashFileSHA256(file) {
152
+ const arrayBuffer = await file.arrayBuffer();
153
+ const hashBuffer = await crypto.subtle.digest("SHA-256", arrayBuffer);
154
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
155
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
156
+ }
157
+ async function prepFileForZenflows(file) {
158
+ const hash = await hashFileForZenflowsUpload(file);
159
+ return {
160
+ name: file.name,
161
+ description: file.name,
162
+ extension: file.name.split(".").at(-1) || "",
163
+ hash,
164
+ mimeType: file.type,
165
+ size: file.size
166
+ };
167
+ }
168
+ async function prepFilesForZenflows(files) {
169
+ return Promise.all(files.map(prepFileForZenflows));
170
+ }
171
+ function formatImageSrc(mimeType, bin) {
172
+ return `data:${mimeType};base64,${bin}`;
173
+ }
174
+ function getResourceImage(images) {
175
+ if (images && images.length > 0 && images[0]) {
176
+ return formatImageSrc(images[0].mimeType, images[0].bin || "");
177
+ }
178
+ return "";
179
+ }
180
+ async function uploadFileToDpp(file, dppUrl, store) {
181
+ const checksum = await hashFileSHA256(file);
182
+ const signature = await signFileUpload(checksum, store);
183
+ const publicKey = store.getItem("eddsaPublicKey") || "";
184
+ const formData = new FormData();
185
+ formData.append("file", file);
186
+ const response = await fetch(`${dppUrl}/upload`, {
187
+ method: "POST",
188
+ headers: {
189
+ "did-pk": publicKey,
190
+ "did-sign": signature
191
+ },
192
+ body: formData
193
+ });
194
+ if (!response.ok) {
195
+ const err = await response.json().catch(() => ({ error: response.statusText }));
196
+ throw new Error(`DPP upload failed: ${err.error || response.statusText}`);
197
+ }
198
+ return response.json();
199
+ }
200
+ function dppAttachmentToProjectModel(attachment, dppBaseUrl) {
201
+ const url = dppBaseUrl ? `${dppBaseUrl}/file/${encodeURIComponent(attachment.id)}` : attachment.url;
202
+ return {
203
+ contentType: attachment.contentType,
204
+ checksum: attachment.checksum,
205
+ downloadUrl: url,
206
+ extension: attachment.fileName.split(".").pop()?.toLowerCase() || "",
207
+ fileName: attachment.fileName,
208
+ id: attachment.id,
209
+ mimeType: attachment.contentType,
210
+ name: attachment.fileName,
211
+ size: attachment.size,
212
+ storage: "dpp",
213
+ uploadedAt: attachment.uploadedAt,
214
+ url
215
+ };
216
+ }
217
+ async function uploadModelFilesToDpp(files, dppUrl, store) {
218
+ const models = [];
219
+ for (const file of files) {
220
+ const attachment = await uploadFileToDpp(file, dppUrl, store);
221
+ models.push(dppAttachmentToProjectModel(attachment, dppUrl));
222
+ }
223
+ return models;
224
+ }
225
+ var init_hashing = __esm({
226
+ "src/files/hashing.ts"() {
227
+ "use strict";
228
+ init_sign();
229
+ }
230
+ });
231
+
232
+ // src/zenflows-crypto/src/keypairoomClient-8-9-10-11-12.zen
233
+ var keypairoomClient_8_9_10_11_12_default = "# SPDX-License-Identifier: AGPL-3.0-or-later\n# Copyright (C) 2022-2023 Dyne.org foundation <foundation@dyne.org>.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nScenario 'ecdh': Create the key\nScenario 'ethereum': Create key\nScenario 'reflow': Create the key\nScenario 'eddsa': Create the key\n\n\n# Loading the user name from data\nGiven my name is in a 'string' named 'username'\n\n# Loading the answers from 3 secret questions. The user will have to pick the 3 challenges from a list\n# and have to remember the questions - the order is not important cause Zenroom will sort alphabetically\n# the data in input\n#\n# NOTE: the challenges will never be communicated to the server or to anybody else!\nGiven I have a 'string dictionary' named 'userChallenges'\n\n# Loading the individual challenges, in order to have them hashed\n# and the hashes OPTIONALLY stored by the server, to improve regeneration of the keypair\nGiven I have a 'string' named 'whereParentsMet' in 'userChallenges'\nGiven I have a 'string' named 'nameFirstPet' in 'userChallenges'\nGiven I have a 'string' named 'whereHomeTown' in 'userChallenges'\nGiven I have a 'string' named 'nameFirstTeacher' in 'userChallenges'\nGiven I have a 'string' named 'nameMotherMaid' in 'userChallenges'\n\n# Loading the pbkdf received from the server, containing a signed hash of known data\nGiven that I have a 'base64' named 'seedServerSideShard.HMAC'\n\n# Save the backup for mnemonic dump, before factoring with the salt\n# it is shortened to 16 bytes by hashing sha512 the KDF and taking the first 16 bytes\nWhen I create the key derivation of 'userChallenges'\nand I create the hash of 'key derivation' using 'sha512'\nand I split the leftmost '16' bytes of 'hash'\nand I delete the 'key derivation'\nand I delete the 'hash'\nand I rename the 'leftmost' to 'seed'\n\n# Hash again the user's challenges with salt for the seed root\nWhen I rename 'seedServerSideShard.HMAC' to 'salt'\nand I create the key derivation of 'seed' with password 'salt'\nand I rename the 'key derivation' to 'seed.root'\n\n# In the following flow the order should NOT be changed\n\nWhen I create the hash of 'seed.root'\nWhen I rename the 'hash' to 'seed.ecdh'\n\nWhen I create the hash of 'seed.ecdh'\nWhen I rename the 'hash' to 'seed.eddsa'\n\nWhen I create the hash of 'seed.eddsa'\nWhen I rename the 'hash' to 'seed.ethereum'\n\nWhen I create the hash of 'seed.ethereum'\nWhen I rename the 'hash' to 'seed.reflow'\n\nWhen I create the hash of 'seed.reflow'\nWhen I rename the 'hash' to 'seed.bitcoin'\n\n# end of the sorted creation flow\n\nWhen I create the ecdh key with secret key 'seed.ecdh'\nWhen I create the eddsa key with secret key 'seed.eddsa'\nWhen I create the ethereum key with secret key 'seed.ethereum'\nWhen I create the reflow key with secret key 'seed.reflow'\nWhen I create the bitcoin key with secret key 'seed.bitcoin'\n\nWhen I create the ecdh public key\nWhen I create the eddsa public key\nWhen I create the ethereum address\nWhen I create the reflow public key\nWhen I create the bitcoin public key\n\n# Creating the hashes of the single challenges, to OPTIONALLY help\n# regeneration of the keypair\n\n# When I create the 'base64 dictionary'\n# and I rename the 'base64 dictionary' to 'hashedAnswers'\n\n# When I create the key derivation of 'whereParentsMet'\n# and I rename the 'key derivation' to 'whereParentsMet.kdf'\n# When I move 'whereParentsMet.kdf' in 'hashedAnswers'\n\n# When I create the key derivation of 'nameFirstPet'\n# and I rename the 'key derivation' to 'nameFirstPet.kdf'\n# When I move 'nameFirstPet.kdf' in 'hashedAnswers'\n\n# When I create the key derivation of 'whereHomeTown'\n# and I rename the 'key derivation' to 'whereHomeTown.kdf'\n# When I move 'whereHomeTown.kdf' in 'hashedAnswers'\n\n# When I create the key derivation of 'nameFirstTeacher'\n# and I rename the 'key derivation' to 'nameFirstTeacher.kdf'\n# When I move 'nameFirstTeacher.kdf' in 'hashedAnswers'\n\n# When I create the key derivation of 'nameMotherMaid'\n# and I rename the 'key derivation' to 'nameMotherMaid.kdf'\n# When I move 'nameMotherMaid.kdf' in 'hashedAnswers'\n\n# this prints the hashes of the challenges\n# Then print the 'hashedAnswers'\n\nThen print the 'keyring'\n\n# This prints the seed for the private keys as mnemonic\nThen print the 'seed' as 'mnemonic'\n\nThen print the 'ecdh public key' as 'base58'\nThen print the 'eddsa public key' as 'base58'\nThen print the 'ethereum address'\nThen print the 'reflow public key' as 'base58'\nThen print the 'bitcoin public key' as 'base58'\n";
234
+
235
+ // src/zenflows-crypto/src/keypairoomClientRecreateKeys.zen
236
+ var keypairoomClientRecreateKeys_default = "# SPDX-License-Identifier: AGPL-3.0-or-later\n# Copyright (C) 2022-2023 Dyne.org foundation <foundation@dyne.org>.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nScenario 'ecdh': Create the key\nScenario 'ethereum': Create key\nScenario 'reflow': Create the key\nScenario 'eddsa': Create the key\n\n# here we load the seed as a mnemonic\nGiven I have a 'mnemonic' named 'seed'\nand I have a 'base64' named 'seedServerSideShard.HMAC'\n\nWhen I rename 'seedServerSideShard.HMAC' to 'salt'\nand I create the key derivation of 'seed' with password 'salt'\nand I rename the 'key derivation' to 'seed.root'\n\n# SKs generation\n# In this flow the order should NOT be changed\nWhen I create the hash of 'seed.root'\nWhen I rename the 'hash' to 'seed.ecdh'\nWhen I create the hash of 'seed.ecdh'\nWhen I rename the 'hash' to 'seed.eddsa'\nWhen I create the hash of 'seed.eddsa'\nWhen I rename the 'hash' to 'seed.ethereum'\nWhen I create the hash of 'seed.ethereum'\nWhen I rename the 'hash' to 'seed.reflow'\nWhen I create the hash of 'seed.reflow'\nWhen I rename the 'hash' to 'seed.bitcoin'\n\nWhen I create the ecdh key with secret key 'seed.ecdh'\nWhen I create the eddsa key with secret key 'seed.eddsa'\nWhen I create the ethereum key with secret key 'seed.ethereum'\nWhen I create the reflow key with secret key 'seed.reflow'\nWhen I create the bitcoin key with secret key 'seed.bitcoin'\n\n# PKs generation\nWhen I create the ecdh public key\nWhen I create the eddsa public key\nWhen I create the ethereum address\nWhen I create the reflow public key\nWhen I create the bitcoin public key\n\n# This prints the keyring containing the SKs\nThen print the 'keyring'\n\n# This prints the PKs, one object each\nThen print the 'ecdh public key' as 'base58'\nThen print the 'eddsa public key' as 'base58'\nThen print the 'ethereum address'\nThen print the 'reflow public key' as 'base58'\nThen print the 'bitcoin public key' as 'base58'\n\n# This prints the seed for the private keys as mnemonic\nThen print the 'seed' as 'mnemonic'\n";
237
+
238
+ // src/crypto/keypair.ts
239
+ init_zenroom_bridge();
240
+ var KEYGEN_CONTRACT = keypairoomClient_8_9_10_11_12_default;
241
+ var RECREATE_CONTRACT = keypairoomClientRecreateKeys_default;
242
+ var KEYPAIR_STORAGE_KEYS = {
243
+ eddsaPrivateKey: "eddsaPrivateKey",
244
+ eddsaPublicKey: "eddsaPublicKey",
245
+ ethereumPrivateKey: "ethereumPrivateKey",
246
+ ethereumAddress: "ethereumAddress",
247
+ reflowPrivateKey: "reflowPrivateKey",
248
+ reflowPublicKey: "reflowPublicKey",
249
+ bitcoinPrivateKey: "bitcoinPrivateKey",
250
+ bitcoinPublicKey: "bitcoinPublicKey",
251
+ ecdhPrivateKey: "ecdhPrivateKey",
252
+ ecdhPublicKey: "ecdhPublicKey",
253
+ seed: "seed"
254
+ };
255
+ async function deriveKeys(challenges, email, hmac, store) {
256
+ const data = JSON.stringify({
257
+ userChallenges: {
258
+ whereParentsMet: challenges.whereParentsMet,
259
+ nameFirstPet: challenges.nameFirstPet,
260
+ nameFirstTeacher: challenges.nameFirstTeacher,
261
+ whereHomeTown: challenges.whereHomeTown,
262
+ nameMotherMaid: challenges.nameMotherMaid
263
+ },
264
+ username: email,
265
+ "seedServerSideShard.HMAC": hmac
266
+ });
267
+ const { result } = await zencodeExec(KEYGEN_CONTRACT, { data });
268
+ const keyring = parseKeyringResult(result);
269
+ persistKeyring(keyring, store);
270
+ return keyring;
271
+ }
272
+ async function recreateKeys(seed, hmac, store) {
273
+ const data = JSON.stringify({
274
+ seed,
275
+ "seedServerSideShard.HMAC": hmac
276
+ });
277
+ const { result } = await zencodeExec(RECREATE_CONTRACT, { data });
278
+ const keyring = parseKeyringResult(result);
279
+ persistKeyring(keyring, store);
280
+ return keyring;
281
+ }
282
+ function parseKeyringResult(result) {
283
+ const parsed = JSON.parse(result);
284
+ return {
285
+ eddsa: parsed.keyring.eddsa,
286
+ ethereum: parsed.keyring.ethereum,
287
+ reflow: parsed.keyring.reflow,
288
+ bitcoin: parsed.keyring.bitcoin,
289
+ ecdh: parsed.keyring.ecdh,
290
+ seed: parsed.seed,
291
+ eddsa_public_key: parsed.eddsa_public_key,
292
+ ethereum_address: parsed.ethereum_address,
293
+ reflow_public_key: parsed.reflow_public_key,
294
+ bitcoin_public_key: parsed.bitcoin_public_key,
295
+ ecdh_public_key: parsed.ecdh_public_key
296
+ };
297
+ }
298
+ function persistKeyring(keyring, store) {
299
+ const K = KEYPAIR_STORAGE_KEYS;
300
+ store.setItem(K.eddsaPrivateKey, keyring.eddsa);
301
+ store.setItem(K.eddsaPublicKey, keyring.eddsa_public_key);
302
+ store.setItem(K.ethereumPrivateKey, keyring.ethereum);
303
+ store.setItem(K.ethereumAddress, keyring.ethereum_address);
304
+ store.setItem(K.reflowPrivateKey, keyring.reflow);
305
+ store.setItem(K.reflowPublicKey, keyring.reflow_public_key);
306
+ store.setItem(K.bitcoinPrivateKey, keyring.bitcoin);
307
+ store.setItem(K.bitcoinPublicKey, keyring.bitcoin_public_key);
308
+ store.setItem(K.ecdhPrivateKey, keyring.ecdh);
309
+ store.setItem(K.ecdhPublicKey, keyring.ecdh_public_key);
310
+ store.setItem(K.seed, keyring.seed);
311
+ }
312
+
313
+ // src/graphql/gql.ts
314
+ function gql(strings, ...values) {
315
+ return strings.reduce((acc, str, i) => acc + str + (values[i] || ""), "");
316
+ }
317
+
318
+ // src/graphql/operations.ts
319
+ var REGISTER_USER = gql`
320
+ mutation RegisterUser($firstRegistration: Boolean!, $userData: JSONObject!) {
321
+ keypairoomServer(firstRegistration: $firstRegistration, userData: $userData)
322
+ }
323
+ `;
324
+ var SIGN_UP = gql`
325
+ mutation SignUp(
326
+ $name: String! $user: String! $email: String!
327
+ $eddsaPublicKey: String! $reflowPublicKey: String!
328
+ $ethereumAddress: String! $ecdhPublicKey: String! $bitcoinPublicKey: String!
329
+ ) {
330
+ createPerson(person: {
331
+ name: $name user: $user email: $email
332
+ eddsaPublicKey: $eddsaPublicKey reflowPublicKey: $reflowPublicKey
333
+ ethereumAddress: $ethereumAddress ecdhPublicKey: $ecdhPublicKey
334
+ bitcoinPublicKey: $bitcoinPublicKey
335
+ }) { agent { id name user email } }
336
+ }
337
+ `;
338
+ var FETCH_SELF = gql`
339
+ query FetchSelf($email: String!, $pubkey: String!) {
340
+ personCheck(email: $email, eddsaPublicKey: $pubkey) {
341
+ id name user email isVerified note
342
+ primaryLocation { id name mappableAddress lat long }
343
+ images { bin mimeType }
344
+ }
345
+ }
346
+ `;
347
+ var SEND_EMAIL_VERIFICATION = gql`
348
+ mutation SendEmailVerification($template: EmailTemplate!) {
349
+ personRequestEmailVerification(template: $template)
350
+ }
351
+ `;
352
+ var CLAIM_DID = gql`
353
+ mutation claimDID($id: ID!) {
354
+ claimPerson(id: $id)
355
+ }
356
+ `;
357
+ var QUERY_RESOURCE = gql`
358
+ query getResourceTable($id: ID!) {
359
+ economicResource(id: $id) {
360
+ id name note metadata license repo classifiedAs
361
+ conformsTo { id name }
362
+ onhandQuantity { hasUnit { id symbol label } hasNumericalValue }
363
+ accountingQuantity { hasUnit { label symbol } hasNumericalValue }
364
+ primaryAccountable { id name }
365
+ currentLocation { id name mappableAddress lat long }
366
+ images { hash name mimeType bin }
367
+ }
368
+ }
369
+ `;
370
+ var FETCH_RESOURCES = gql`
371
+ query FetchInventory(
372
+ $first: Int $after: ID $last: Int $before: ID
373
+ $filter: EconomicResourceFilterParams
374
+ ) {
375
+ economicResources(first: $first after: $after before: $before last: $last filter: $filter) {
376
+ pageInfo { startCursor endCursor hasPreviousPage hasNextPage totalCount pageLimit }
377
+ edges {
378
+ cursor
379
+ node {
380
+ conformsTo { id name }
381
+ currentLocation { id name mappableAddress lat long }
382
+ id name classifiedAs note metadata okhv repo license version licensor
383
+ images { hash name mimeType }
384
+ primaryAccountable { id name note images { bin mimeType } primaryLocation { name } }
385
+ custodian { id name note }
386
+ accountingQuantity { hasUnit { id label symbol } hasNumericalValue }
387
+ onhandQuantity { hasUnit { id label symbol } hasNumericalValue }
388
+ }
389
+ }
390
+ }
391
+ }
392
+ `;
393
+ var QUERY_PROJECTS = gql`
394
+ query GetProjects($first: Int $after: ID $last: Int $before: ID $filter: ProposalFilterParams) {
395
+ proposals(first: $first after: $after before: $before last: $last filter: $filter) {
396
+ pageInfo { startCursor endCursor hasPreviousPage hasNextPage totalCount pageLimit }
397
+ edges {
398
+ cursor
399
+ node {
400
+ id name created
401
+ primaryIntents {
402
+ resourceClassifiedAs
403
+ action { id }
404
+ hasPointInTime hasBeginning hasEnd
405
+ resourceInventoriedAs {
406
+ conformsTo { name }
407
+ classifiedAs
408
+ primaryAccountable { name id }
409
+ name id note metadata
410
+ onhandQuantity { hasUnit { label } }
411
+ images { hash name mimeType bin }
412
+ }
413
+ }
414
+ reciprocalIntents {
415
+ resourceQuantity { hasNumericalValue hasUnit { label symbol } }
416
+ }
417
+ }
418
+ }
419
+ }
420
+ }
421
+ `;
422
+ var QUERY_MACHINES = gql`
423
+ query getMachines($resourceSpecId: ID!) {
424
+ economicResources(filter: { conformsTo: [$resourceSpecId] }) {
425
+ edges { node { id name note metadata conformsTo { id name } } }
426
+ }
427
+ }
428
+ `;
429
+ var QUERY_CITED_RESOURCES = gql`
430
+ query getCitedResources($processId: ID!) {
431
+ economicEvents {
432
+ edges {
433
+ node {
434
+ id
435
+ action { id label }
436
+ resourceInventoriedAs { id name note metadata conformsTo { id name } }
437
+ }
438
+ }
439
+ }
440
+ }
441
+ `;
442
+ var QUERY_PROJECT_FOR_METADATA_UPDATE = gql`
443
+ query queryProjectForMetadataUpdate($id: ID!) {
444
+ economicResource(id: $id) {
445
+ id name classifiedAs metadata
446
+ onhandQuantity { hasUnit { id symbol label } hasNumericalValue }
447
+ accountingQuantity { hasUnit { id label symbol } hasNumericalValue }
448
+ primaryAccountable { id }
449
+ }
450
+ }
451
+ `;
452
+ var ASK_RESOURCE_PRIMARY_ACCOUNTABLE = gql`
453
+ query askResourcePrimaryAccountable($id: ID!) {
454
+ economicResource(id: $id) {
455
+ id name primaryAccountable { id name images { bin mimeType } }
456
+ }
457
+ }
458
+ `;
459
+ var CREATE_PROPOSAL = gql`
460
+ mutation CreateProposal($name: String!, $note: String!) {
461
+ createProposal(proposal: { name: $name, note: $note }) { proposal { id } }
462
+ }
463
+ `;
464
+ var CREATE_INTENT = gql`
465
+ mutation CreateIntent($agent: ID!, $resource: ID!, $oneUnit: ID!, $currency: ID!, $howMuch: Decimal!) {
466
+ item: createIntent(intent: { name: "project" action: "transfer" provider: $agent
467
+ resourceInventoriedAs: $resource resourceQuantity: { hasNumericalValue: 1 hasUnit: $oneUnit }
468
+ }) { intent { id } }
469
+ payment: createIntent(intent: { name: "payment" action: "transfer" receiver: $agent
470
+ resourceConformsTo: $currency resourceQuantity: { hasNumericalValue: $howMuch hasUnit: $oneUnit }
471
+ }) { intent { id } }
472
+ }
473
+ `;
474
+ var LINK_PROPOSAL_AND_INTENT = gql`
475
+ mutation LinkProposalAndIntent($proposal: ID!, $item: ID!, $payment: ID!) {
476
+ linkItem: proposeIntent(publishedIn: $proposal publishes: $item reciprocal: false) { proposedIntent { id } }
477
+ linkPayment: proposeIntent(publishedIn: $proposal publishes: $payment reciprocal: true) { proposedIntent { id } }
478
+ }
479
+ `;
480
+ var PROPOSE_CONTRIBUTION = gql`
481
+ mutation proposeContribution(
482
+ $process: ID! $owner: ID! $proposer: ID! $creationTime: DateTime!
483
+ $resourceForked: ID! $unitOne: ID! $resourceOrigin: ID!
484
+ ) {
485
+ citeResourceForked: createIntent(intent: {
486
+ action: "cite" inputOf: $process provider: $proposer hasPointInTime: $creationTime
487
+ resourceInventoriedAs: $resourceForked resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
488
+ }) { intent { id } }
489
+ acceptResourceOrigin: createIntent(intent: {
490
+ action: "accept" inputOf: $process receiver: $owner hasPointInTime: $creationTime
491
+ resourceInventoriedAs: $resourceOrigin resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
492
+ }) { intent { id } }
493
+ modifyResourceOrigin: createIntent(intent: {
494
+ action: "modify" outputOf: $process receiver: $owner hasPointInTime: $creationTime
495
+ resourceInventoriedAs: $resourceOrigin resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
496
+ }) { intent { id } }
497
+ }
498
+ `;
499
+ var LINK_CONTRIBUTION_PROPOSAL_INTENT = gql`
500
+ mutation LinkContributionAndProposalAndIntent(
501
+ $proposal: ID! $citeIntent: ID! $acceptIntent: ID! $modifyIntent: ID!
502
+ ) {
503
+ proposeCite: proposeIntent(publishedIn: $proposal publishes: $citeIntent) { proposedIntent { id } }
504
+ proposeAccept: proposeIntent(publishedIn: $proposal publishes: $acceptIntent) { proposedIntent { id } }
505
+ proposeModify: proposeIntent(publishedIn: $proposal publishes: $modifyIntent) { proposedIntent { id } }
506
+ }
507
+ `;
508
+ var QUERY_PROPOSAL = gql`
509
+ query QueryProposal($id: ID!) {
510
+ proposal(id: $id) {
511
+ id name note status
512
+ primaryIntents {
513
+ id provider { id name } receiver { id name }
514
+ inputOf { name id } outputOf { id name } hasPointInTime
515
+ resourceInventoriedAs {
516
+ id name repo metadata images { hash name mimeType bin }
517
+ primaryAccountable { id name } onhandQuantity { hasNumericalValue hasUnit { id } }
518
+ }
519
+ resourceConformsTo { id name }
520
+ }
521
+ }
522
+ }
523
+ `;
524
+ var QUERY_RESOURCE_PROPOSALS = gql`
525
+ query resourceProposals($id: ID!) {
526
+ proposals(filter: { primaryIntentsResourceInventoriedAsId: [$id] }) {
527
+ edges {
528
+ node { id status note created primaryIntents { provider { id name images { bin mimeType } } } }
529
+ }
530
+ }
531
+ }
532
+ `;
533
+ var ACCEPT_PROPOSAL = gql`
534
+ mutation acceptProposal(
535
+ $process: ID! $owner: ID! $proposer: ID! $unitOne: ID!
536
+ $resourceForked: ID! $resourceOrigin: ID! $creationTime: DateTime! $metadata: JSONObject
537
+ ) {
538
+ cite: createEconomicEvent(event: {
539
+ action: "cite" inputOf: $process provider: $proposer receiver: $owner
540
+ resourceInventoriedAs: $resourceForked resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
541
+ hasPointInTime: $creationTime
542
+ }) { economicEvent { id } }
543
+ accept: createEconomicEvent(event: {
544
+ action: "accept" inputOf: $process provider: $owner receiver: $owner
545
+ resourceInventoriedAs: $resourceOrigin resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
546
+ hasPointInTime: $creationTime
547
+ }) { economicEvent { id } }
548
+ modify: createEconomicEvent(event: {
549
+ action: "modify" outputOf: $process provider: $owner receiver: $owner
550
+ resourceInventoriedAs: $resourceOrigin resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
551
+ hasPointInTime: $creationTime resourceMetadata: $metadata
552
+ }) { economicEvent { id } }
553
+ }
554
+ `;
555
+ var SATISFY_INTENTS = gql`
556
+ mutation satisfyIntents(
557
+ $unitOne: ID! $intentCited: ID! $intentAccepted: ID! $intentModify: ID!
558
+ $eventCite: ID! $eventAccept: ID! $eventModify: ID!
559
+ ) {
560
+ cite: createSatisfaction(satisfaction: {
561
+ satisfies: $intentCited satisfiedByEvent: $eventCite resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
562
+ }) { satisfaction { id } }
563
+ accept: createSatisfaction(satisfaction: {
564
+ satisfies: $intentAccepted satisfiedByEvent: $eventAccept resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
565
+ }) { satisfaction { id } }
566
+ modify: createSatisfaction(satisfaction: {
567
+ satisfies: $intentModify satisfiedByEvent: $eventModify resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
568
+ }) { satisfaction { id } }
569
+ }
570
+ `;
571
+ var REJECT_PROPOSAL = gql`
572
+ mutation rejectProposal($intentCite: ID!, $intentAccept: ID!, $intentModify: ID!) {
573
+ cite: updateIntent(intent: { id: $intentCite finished: true }) { intent { id } }
574
+ accept: updateIntent(intent: { id: $intentAccept finished: true }) { intent { id } }
575
+ modify: updateIntent(intent: { id: $intentModify finished: true }) { intent { id } }
576
+ }
577
+ `;
578
+ var CREATE_PROJECT = gql`
579
+ mutation CreateProject(
580
+ $name: String! $note: String! $metadata: JSONObject $agent: ID!
581
+ $creationTime: DateTime! $location: ID $tags: [URI!] $resourceSpec: ID!
582
+ $oneUnit: ID! $images: [IFile!] $repo: String $process: ID! $license: String!
583
+ ) {
584
+ createEconomicEvent(
585
+ event: {
586
+ action: "produce" provider: $agent receiver: $agent outputOf: $process
587
+ hasPointInTime: $creationTime resourceClassifiedAs: $tags
588
+ resourceConformsTo: $resourceSpec resourceQuantity: { hasNumericalValue: 1 hasUnit: $oneUnit }
589
+ toLocation: $location resourceMetadata: $metadata
590
+ }
591
+ newInventoriedResource: { name: $name note: $note images: $images repo: $repo license: $license }
592
+ ) {
593
+ economicEvent { id resourceInventoriedAs { id name } }
594
+ }
595
+ }
596
+ `;
597
+ var CREATE_MACHINE_RESOURCE = gql`
598
+ mutation createMachineResource(
599
+ $agent: ID! $creationTime: DateTime! $process: ID! $resourceSpec: ID!
600
+ $unitOne: ID! $name: String! $note: String $metadata: JSONObject
601
+ ) {
602
+ createEconomicEvent(
603
+ event: {
604
+ action: "produce" outputOf: $process provider: $agent receiver: $agent
605
+ hasPointInTime: $creationTime resourceConformsTo: $resourceSpec
606
+ resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne } resourceMetadata: $metadata
607
+ }
608
+ newInventoriedResource: { name: $name note: $note }
609
+ ) {
610
+ economicEvent { id resourceInventoriedAs { id name note metadata conformsTo { id name } } }
611
+ }
612
+ }
613
+ `;
614
+ var CREATE_DPP_RESOURCE = gql`
615
+ mutation createDppResource(
616
+ $agent: ID! $creationTime: DateTime! $process: ID! $resourceSpec: ID!
617
+ $unitOne: ID! $dppUlid: JSONObject! $name: String! $note: String
618
+ ) {
619
+ createEconomicEvent(
620
+ event: {
621
+ action: "produce" outputOf: $process provider: $agent receiver: $agent
622
+ hasPointInTime: $creationTime resourceConformsTo: $resourceSpec
623
+ resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne } resourceMetadata: $dppUlid
624
+ }
625
+ newInventoriedResource: { name: $name note: $note }
626
+ ) {
627
+ economicEvent { id resourceInventoriedAs { id name metadata } }
628
+ }
629
+ }
630
+ `;
631
+ var CREATE_LOCATION = gql`
632
+ mutation CreateLocation($name: String!, $addr: String!, $lat: Decimal!, $lng: Decimal!) {
633
+ createSpatialThing(spatialThing: { name: $name mappableAddress: $addr lat: $lat long: $lng }) {
634
+ spatialThing { id lat long }
635
+ }
636
+ }
637
+ `;
638
+ var CREATE_PROCESS = gql`
639
+ mutation CreateProcess($name: String!) {
640
+ createProcess(process: { name: $name }) { process { id } }
641
+ }
642
+ `;
643
+ var CITE_PROJECT = gql`
644
+ mutation citeProject($agent: ID! $creationTime: DateTime! $resource: ID! $process: ID! $unitOne: ID!) {
645
+ createEconomicEvent(event: {
646
+ action: "cite" inputOf: $process provider: $agent receiver: $agent
647
+ hasPointInTime: $creationTime resourceInventoriedAs: $resource
648
+ resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
649
+ }) { economicEvent { id } }
650
+ }
651
+ `;
652
+ var CONSUME_RESOURCE = gql`
653
+ mutation consumeResource($agent: ID! $creationTime: DateTime! $resource: ID! $process: ID! $unitOne: ID!) {
654
+ createEconomicEvent(event: {
655
+ action: "consume" inputOf: $process provider: $agent receiver: $agent
656
+ hasPointInTime: $creationTime resourceInventoriedAs: $resource
657
+ resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
658
+ }) { economicEvent { id } }
659
+ }
660
+ `;
661
+ var CONTRIBUTE_TO_PROJECT = gql`
662
+ mutation contributeToProject(
663
+ $agent: ID! $creationTime: DateTime! $process: ID! $unitOne: ID! $conformsTo: ID!
664
+ ) {
665
+ createEconomicEvent(event: {
666
+ action: "work" inputOf: $process provider: $agent receiver: $agent
667
+ resourceConformsTo: $conformsTo hasPointInTime: $creationTime
668
+ effortQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
669
+ }) { economicEvent { id } }
670
+ }
671
+ `;
672
+ var FORK_PROJECT = gql`
673
+ mutation ForkProject(
674
+ $agent: ID! $creationTime: DateTime! $resource: ID! $process: ID!
675
+ $unitOne: ID! $tags: [URI!] $location: ID $spec: ID!
676
+ $name: String! $note: String $repo: String $metadata: JSONObject
677
+ ) {
678
+ cite: createEconomicEvent(event: {
679
+ action: "cite" inputOf: $process provider: $agent receiver: $agent
680
+ hasPointInTime: $creationTime resourceInventoriedAs: $resource
681
+ resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
682
+ }) { economicEvent { id } }
683
+ produce: createEconomicEvent(event: {
684
+ action: "produce" outputOf: $process provider: $agent receiver: $agent
685
+ hasPointInTime: $creationTime resourceClassifiedAs: $tags resourceConformsTo: $spec
686
+ toLocation: $location resourceQuantity: { hasNumericalValue: 1 hasUnit: $unitOne }
687
+ resourceMetadata: $metadata
688
+ } newInventoriedResource: { name: $name note: $note repo: $repo }) {
689
+ economicEvent { id resourceInventoriedAs { id name } }
690
+ }
691
+ }
692
+ `;
693
+ var TRANSFER_PROJECT = gql`
694
+ mutation TransferProject(
695
+ $resource: ID! $name: String! $note: String! $metadata: JSONObject
696
+ $agent: ID! $creationTime: DateTime! $tags: [URI!] $oneUnit: ID!
697
+ $loshId: ID!
698
+ ) {
699
+ createEconomicEvent(event: {
700
+ resourceInventoriedAs: $resource action: "transfer"
701
+ provider: $loshId receiver: $agent
702
+ hasPointInTime: $creationTime resourceClassifiedAs: $tags
703
+ resourceQuantity: { hasNumericalValue: 1 hasUnit: $oneUnit } resourceMetadata: $metadata
704
+ } newInventoriedResource: { name: $name note: $note }) {
705
+ economicEvent { id toResourceInventoriedAs { id name } }
706
+ }
707
+ }
708
+ `;
709
+ var UPDATE_METADATA = gql`
710
+ mutation updateMetadata(
711
+ $process: ID! $agent: ID! $resource: ID! $quantity: IMeasure! $now: DateTime! $metadata: JSONObject!
712
+ ) {
713
+ accept: createEconomicEvent(event: {
714
+ action: "accept" inputOf: $process provider: $agent receiver: $agent
715
+ resourceInventoriedAs: $resource resourceQuantity: $quantity hasPointInTime: $now
716
+ }) { economicEvent { id } }
717
+ modify: createEconomicEvent(event: {
718
+ action: "modify" outputOf: $process provider: $agent receiver: $agent
719
+ resourceInventoriedAs: $resource resourceQuantity: $quantity
720
+ resourceMetadata: $metadata hasPointInTime: $now
721
+ }) { economicEvent { id } }
722
+ }
723
+ `;
724
+ var UPDATE_RESOURCE_CLASSIFIED_AS = gql`
725
+ mutation updateResourceClassifiedAs($id: ID!, $classifiedAs: [URI!]) {
726
+ updateEconomicResource(resource: { id: $id classifiedAs: $classifiedAs }) { economicResource { id } }
727
+ }
728
+ `;
729
+ var RELOCATE_PROJECT = gql`
730
+ mutation relocateProject(
731
+ $process: ID! $agent: ID! $resource: ID! $quantity: IMeasure! $now: DateTime! $location: ID!
732
+ ) {
733
+ pickup: createEconomicEvent(event: {
734
+ action: "pickup" inputOf: $process provider: $agent receiver: $agent
735
+ resourceInventoriedAs: $resource resourceQuantity: $quantity hasPointInTime: $now
736
+ }) { economicEvent { id } }
737
+ dropoff: createEconomicEvent(event: {
738
+ action: "dropoff" outputOf: $process provider: $agent receiver: $agent
739
+ resourceInventoriedAs: $resource resourceQuantity: $quantity toLocation: $location hasPointInTime: $now
740
+ }) { economicEvent { id } }
741
+ }
742
+ `;
743
+ var QUERY_AGENTS = gql`
744
+ query getAgent($first: Int, $id: ID) {
745
+ agents(first: $first after: $id) {
746
+ pageInfo { startCursor endCursor hasPreviousPage hasNextPage totalCount pageLimit }
747
+ edges { cursor node { id name } }
748
+ }
749
+ }
750
+ `;
751
+ var FETCH_AGENTS = gql`
752
+ query getAgents($userOrName: String!, $last: Int) {
753
+ people(last: $last filter: { userOrName: $userOrName }) {
754
+ pageInfo { startCursor endCursor hasPreviousPage hasNextPage totalCount pageLimit }
755
+ edges { cursor node { id name note images { bin mimeType } primaryLocation { id name } } }
756
+ }
757
+ }
758
+ `;
759
+ var FETCH_USER = gql`
760
+ query GetUser($id: ID!) {
761
+ person(id: $id) {
762
+ id name email user ethereumAddress primaryLocation { name mappableAddress }
763
+ }
764
+ }
765
+ `;
766
+ var GET_TAGS = gql`
767
+ query GetTags {
768
+ economicResourceClassifications
769
+ }
770
+ `;
771
+ var GET_RESOURCE_DETAILS = gql`
772
+ query GetResourceDetails($id: ID!) {
773
+ proposal(id: $id) {
774
+ created
775
+ primaryIntents {
776
+ hasPointInTime
777
+ resourceInventoriedAs {
778
+ conformsTo { name id } currentLocation { name } name id note
779
+ classifiedAs metadata primaryAccountable { name id }
780
+ onhandQuantity { hasUnit { label } } images { hash name mimeType bin }
781
+ }
782
+ }
783
+ }
784
+ }
785
+ `;
786
+
787
+ // src/auth/AuthClient.ts
788
+ var AuthClient = class {
789
+ constructor(config, store, graphql) {
790
+ this.config = config;
791
+ this.store = store;
792
+ this.graphql = graphql;
793
+ }
794
+ config;
795
+ store;
796
+ graphql;
797
+ // ─── Step 1: Request HMAC ─────────────────────────────────────────
798
+ /**
799
+ * Request the server-side HMAC shard from Zenflows keypairoomServer.
800
+ *
801
+ * @param email - User's email
802
+ * @param firstRegistration - true for sign-up, false for sign-in
803
+ * @returns The HMAC string (base64)
804
+ */
805
+ async requestHmac(email, firstRegistration) {
806
+ const userData = JSON.stringify({ email });
807
+ const res = await this.graphql.request(
808
+ REGISTER_USER,
809
+ { firstRegistration, userData }
810
+ );
811
+ if (res.errors?.length) {
812
+ throw new Error(`HMAC request failed: ${res.errors[0].message}`);
813
+ }
814
+ const hmac = res.data?.keypairoomServer;
815
+ if (!hmac) throw new Error("HMAC not returned from server. Email may not exist.");
816
+ return hmac;
817
+ }
818
+ // ─── Step 2: Key derivation ───────────────────────────────────────
819
+ /**
820
+ * Derive all keypairs from user challenges + server HMAC (registration).
821
+ * Keys are persisted to the store automatically.
822
+ */
823
+ async deriveKeys(challenges, email, hmac) {
824
+ return deriveKeys(challenges, email, hmac, this.store);
825
+ }
826
+ /**
827
+ * Recreate all keypairs from seed mnemonic + server HMAC (login).
828
+ * Keys are persisted to the store automatically.
829
+ */
830
+ async recreateKeys(seed, hmac) {
831
+ return recreateKeys(seed, hmac, this.store);
832
+ }
833
+ // ─── Step 3: Register ─────────────────────────────────────────────
834
+ /**
835
+ * Register a new person on Zenflows.
836
+ * Requires keys to already be derived (via deriveKeys).
837
+ */
838
+ async registerUser(params) {
839
+ const res = await this.graphql.request(
840
+ SIGN_UP,
841
+ {
842
+ name: params.name,
843
+ user: params.user,
844
+ email: params.email,
845
+ eddsaPublicKey: this.store.getItem("eddsaPublicKey") || "",
846
+ reflowPublicKey: this.store.getItem("reflowPublicKey") || "",
847
+ ethereumAddress: this.store.getItem("ethereumAddress") || "",
848
+ ecdhPublicKey: this.store.getItem("ecdhPublicKey") || "",
849
+ bitcoinPublicKey: this.store.getItem("bitcoinPublicKey") || ""
850
+ },
851
+ this.config.zenflowsAdmin ? { "zenflows-admin": this.config.zenflowsAdmin } : void 0
852
+ );
853
+ if (res.errors?.length) {
854
+ throw new Error(`Registration failed: ${res.errors[0].message}`);
855
+ }
856
+ const agent = res.data?.createPerson.agent;
857
+ if (!agent) throw new Error("Registration failed: no agent returned.");
858
+ this.store.setItem("authId", agent.id);
859
+ this.store.setItem("authName", agent.name);
860
+ this.store.setItem("authUsername", agent.user);
861
+ this.store.setItem("authEmail", agent.email);
862
+ return agent.id;
863
+ }
864
+ // ─── Step 4: Verify / Login ───────────────────────────────────────
865
+ /**
866
+ * Verify a user exists on Zenflows by email + EdDSA public key.
867
+ */
868
+ async verifyUser(email, eddsaPublicKey) {
869
+ const res = await this.graphql.request(FETCH_SELF, { email, pubkey: eddsaPublicKey });
870
+ const person = res.data?.personCheck;
871
+ if (!person) return null;
872
+ return {
873
+ id: person.id,
874
+ name: person.name,
875
+ username: person.user,
876
+ email: person.email,
877
+ isVerified: person.isVerified,
878
+ note: person.note,
879
+ location: person.primaryLocation ? {
880
+ id: person.primaryLocation.id,
881
+ name: person.primaryLocation.name,
882
+ address: person.primaryLocation.mappableAddress,
883
+ lat: person.primaryLocation.lat,
884
+ lng: person.primaryLocation.long
885
+ } : void 0,
886
+ image: person.images?.[0] ? `data:${person.images[0].mimeType};base64,${person.images[0].bin}` : void 0
887
+ };
888
+ }
889
+ /**
890
+ * Full login flow:
891
+ * 1. Verify user on Zenflows
892
+ * 2. Persist auth info to storage
893
+ * 3. Enable GraphQL request signing
894
+ */
895
+ async login(params) {
896
+ const pubkey = this.store.getItem("eddsaPublicKey");
897
+ if (!pubkey) throw new Error("No public key found. Derive keys first.");
898
+ const profile = await this.verifyUser(params.email, pubkey);
899
+ if (!profile) throw new Error("User not found. Check email and keys.");
900
+ this.store.setItem("authId", profile.id);
901
+ this.store.setItem("authName", profile.name);
902
+ this.store.setItem("authUsername", profile.username);
903
+ this.store.setItem("authEmail", profile.email);
904
+ this.graphql.setSigningEnabled(true);
905
+ return profile;
906
+ }
907
+ // ─── Step 5: Post-registration ────────────────────────────────────
908
+ /**
909
+ * Send email verification.
910
+ * The template is auto-detected from the Zenflows URL origin.
911
+ */
912
+ async sendEmailVerification() {
913
+ const template = this.detectTemplate();
914
+ const res = await this.graphql.request(SEND_EMAIL_VERIFICATION, { template });
915
+ if (res.errors?.length) {
916
+ throw new Error(`Email verification failed: ${res.errors[0].message}`);
917
+ }
918
+ }
919
+ /**
920
+ * Claim a DID for the current user.
921
+ */
922
+ async claimDid(personId) {
923
+ const res = await this.graphql.request(CLAIM_DID, { id: personId });
924
+ if (res.errors?.length) {
925
+ throw new Error(`DID claim failed: ${res.errors[0].message}`);
926
+ }
927
+ return res.data?.claimPerson || "";
928
+ }
929
+ // ─── Logout ───────────────────────────────────────────────────────
930
+ /** Clear all auth state from storage. */
931
+ logout() {
932
+ this.store.clear();
933
+ this.graphql.setSigningEnabled(false);
934
+ }
935
+ // ─── Helpers ──────────────────────────────────────────────────────
936
+ detectTemplate() {
937
+ if (typeof window === "undefined") return "InterfacerTesting" /* InterfacerTesting */;
938
+ const origin = window.location.origin;
939
+ switch (origin) {
940
+ case "https://interfacer.dyne.org":
941
+ return "InterfacerDeployment" /* InterfacerDeployment */;
942
+ case "https://interfacer-gui-staging.dyne.org":
943
+ return "InterfacerStaging" /* InterfacerStaging */;
944
+ case "https://beta.interfacer.dyne.org":
945
+ return "InterfacerBeta" /* InterfacerBeta */;
946
+ case "http://localhost:3000":
947
+ return "InterfacerTesting" /* InterfacerTesting */;
948
+ default:
949
+ return "InterfacerSelf" /* InterfacerSelf */;
950
+ }
951
+ }
952
+ };
953
+
954
+ // src/config/storage.ts
955
+ function createLocalStorageAdapter() {
956
+ if (typeof window === "undefined" || !window.localStorage) return null;
957
+ return {
958
+ getItem: (key) => window.localStorage.getItem(key),
959
+ setItem: (key, value) => window.localStorage.setItem(key, value),
960
+ removeItem: (key) => window.localStorage.removeItem(key),
961
+ clear: () => window.localStorage.clear()
962
+ };
963
+ }
964
+ function createMemoryStorage() {
965
+ const store = /* @__PURE__ */ new Map();
966
+ return {
967
+ getItem: (key) => store.get(key) ?? null,
968
+ setItem: (key, value) => store.set(key, value),
969
+ removeItem: (key) => store.delete(key),
970
+ clear: () => store.clear()
971
+ };
972
+ }
973
+
974
+ // src/dpp/DppClient.ts
975
+ init_sign();
976
+ init_hashing();
977
+ var DppClient = class {
978
+ constructor(config, store) {
979
+ this.config = config;
980
+ this.store = store;
981
+ this.baseUrl = config.dppUrl || "";
982
+ }
983
+ config;
984
+ store;
985
+ baseUrl;
986
+ get dppUrl() {
987
+ if (!this.baseUrl) throw new Error("dppUrl not configured");
988
+ return this.baseUrl;
989
+ }
990
+ /** Sign a request body and return DID headers + x-user-id. */
991
+ async signedRequest(body) {
992
+ const json = body != null ? JSON.stringify(body) : "";
993
+ const didHeaders = json ? await signDidRequest(json, this.store) : {};
994
+ const headers = { ...didHeaders };
995
+ const userId = this.store.getItem("authId");
996
+ if (userId) headers["x-user-id"] = userId;
997
+ if (json) headers["Content-Type"] = "application/json";
998
+ return headers;
999
+ }
1000
+ /** Generic request helper. */
1001
+ async request(method, path, body) {
1002
+ const url = `${this.dppUrl}${path}`;
1003
+ const headers = await this.signedRequest(body);
1004
+ const jsonBody = body != null ? JSON.stringify(body) : void 0;
1005
+ const res = await fetch(url, { method, headers, body: jsonBody });
1006
+ if (!res.ok) {
1007
+ let errMsg = res.statusText;
1008
+ try {
1009
+ const err = await res.json();
1010
+ errMsg = err.error || errMsg;
1011
+ } catch {
1012
+ }
1013
+ throw new Error(`DPP ${method} ${path} failed: ${errMsg}`);
1014
+ }
1015
+ if (res.status === 204) return void 0;
1016
+ return res.json();
1017
+ }
1018
+ // ─── CRUD ──────────────────────────────────────────────────────────
1019
+ async createDpp(data) {
1020
+ return this.request("POST", "/dpp", data);
1021
+ }
1022
+ async getDpp(id) {
1023
+ return this.request("GET", `/dpp/${encodeURIComponent(id)}`);
1024
+ }
1025
+ async updateDpp(id, data) {
1026
+ return this.request("PUT", `/dpp/${encodeURIComponent(id)}`, data);
1027
+ }
1028
+ async deleteDpp(id) {
1029
+ return this.request("DELETE", `/dpp/${encodeURIComponent(id)}`);
1030
+ }
1031
+ // ─── List / Query ──────────────────────────────────────────────────
1032
+ async listDpps(filters) {
1033
+ const params = new URLSearchParams();
1034
+ if (filters?.productId) params.set("productId", filters.productId);
1035
+ if (filters?.createdBy) params.set("createdBy", filters.createdBy);
1036
+ if (filters?.status) params.set("status", filters.status);
1037
+ if (filters?.q) params.set("q", filters.q);
1038
+ if (filters?.sortBy) params.set("sortBy", filters.sortBy);
1039
+ if (filters?.sortOrder) params.set("sortOrder", filters.sortOrder);
1040
+ if (filters?.limit != null) params.set("limit", String(filters.limit));
1041
+ if (filters?.offset != null) params.set("offset", String(filters.offset));
1042
+ const qs = params.toString();
1043
+ return this.request("GET", qs ? `/dpps?${qs}` : "/dpps");
1044
+ }
1045
+ async updateDppStatus(id, status) {
1046
+ return this.request("PUT", `/dpp/${encodeURIComponent(id)}/status`, { status });
1047
+ }
1048
+ // ─── QR Code ───────────────────────────────────────────────────────
1049
+ getQrCodeUrl(dppId, size) {
1050
+ const params = size ? `?size=${size}` : "";
1051
+ return `${this.dppUrl}/dpp/${encodeURIComponent(dppId)}/qr${params}`;
1052
+ }
1053
+ // ─── Attachments ───────────────────────────────────────────────────
1054
+ async addAttachment(dppId, section, file) {
1055
+ const checksum = await hashFileSHA256(file);
1056
+ const signHeaders = await signDidRequest(checksum, this.store);
1057
+ const formData = new FormData();
1058
+ formData.append("file", file);
1059
+ const res = await fetch(
1060
+ `${this.dppUrl}/dpp/${encodeURIComponent(dppId)}/attachments?section=${encodeURIComponent(section)}`,
1061
+ {
1062
+ method: "POST",
1063
+ headers: {
1064
+ "did-pk": signHeaders["did-pk"],
1065
+ "did-sign": signHeaders["did-sign"]
1066
+ },
1067
+ body: formData
1068
+ }
1069
+ );
1070
+ if (!res.ok) {
1071
+ let errMsg = res.statusText;
1072
+ try {
1073
+ const err = await res.json();
1074
+ errMsg = err.error || errMsg;
1075
+ } catch {
1076
+ }
1077
+ throw new Error(`DPP attachment upload failed: ${errMsg}`);
1078
+ }
1079
+ return res.json();
1080
+ }
1081
+ async deleteAttachment(dppId, attachmentId) {
1082
+ return this.request(
1083
+ "DELETE",
1084
+ `/dpp/${encodeURIComponent(dppId)}/attachments/${encodeURIComponent(attachmentId)}`
1085
+ );
1086
+ }
1087
+ /** Get the file download URL for an attachment. */
1088
+ getFileUrl(fileId) {
1089
+ return `${this.dppUrl}/file/${encodeURIComponent(fileId)}`;
1090
+ }
1091
+ };
1092
+
1093
+ // src/files/FileClient.ts
1094
+ init_hashing();
1095
+ var FileClient = class {
1096
+ constructor(config, store) {
1097
+ this.config = config;
1098
+ this.store = store;
1099
+ }
1100
+ config;
1101
+ store;
1102
+ // ─── Hashing ───────────────────────────────────────────────────────
1103
+ hashFileForZenflows = (file) => Promise.resolve().then(() => (init_hashing(), hashing_exports)).then((m) => m.hashFileForZenflowsUpload(file));
1104
+ hashFileSHA256 = (file) => Promise.resolve().then(() => (init_hashing(), hashing_exports)).then((m) => m.hashFileSHA256(file));
1105
+ // ─── Zenflows Upload ───────────────────────────────────────────────
1106
+ /** Prepare files for Zenflows (hash + descriptor). */
1107
+ async prepFilesForZenflows(files) {
1108
+ return prepFilesForZenflows(files);
1109
+ }
1110
+ /** Upload a file to the Zenflows file storage endpoint. */
1111
+ async uploadToZenflows(file) {
1112
+ const hash = await Promise.resolve().then(() => (init_hashing(), hashing_exports)).then((m) => m.hashFileForZenflowsUpload(file));
1113
+ const formData = new FormData();
1114
+ formData.append(hash, file);
1115
+ const url = this.config.zenflowsFileUrl;
1116
+ if (!url) throw new Error("zenflowsFileUrl not configured");
1117
+ const res = await fetch(url, { method: "POST", body: formData });
1118
+ if (!res.ok) throw new Error(`Zenflows upload failed: ${res.statusText}`);
1119
+ }
1120
+ /** Upload multiple files to Zenflows. */
1121
+ async uploadToZenflowsBatch(files) {
1122
+ for (const file of files) {
1123
+ await this.uploadToZenflows(file);
1124
+ }
1125
+ }
1126
+ /** Get the proxy URL for a file by its hash. */
1127
+ getFileUrl(hash) {
1128
+ return `/api/file/${hash}`;
1129
+ }
1130
+ /** Get a data URL for a file from its GraphQL response. */
1131
+ getImageSrc(image) {
1132
+ if (image.bin) {
1133
+ return `data:${image.mimeType};base64,${image.bin}`;
1134
+ }
1135
+ return this.getFileUrl(image.hash);
1136
+ }
1137
+ // ─── DPP Upload ────────────────────────────────────────────────────
1138
+ /** Upload a file to the DPP service. */
1139
+ async uploadToDpp(file) {
1140
+ const dppUrl = this.config.dppUrl;
1141
+ if (!dppUrl) throw new Error("dppUrl not configured");
1142
+ return uploadFileToDpp(file, dppUrl, this.store);
1143
+ }
1144
+ /** Upload multiple model files to DPP and convert to project model metadata. */
1145
+ async uploadModelsToDpp(files) {
1146
+ const dppUrl = this.config.dppUrl;
1147
+ if (!dppUrl) throw new Error("dppUrl not configured");
1148
+ return uploadModelFilesToDpp(files, dppUrl, this.store);
1149
+ }
1150
+ /** Convert a DPP attachment to project model metadata. */
1151
+ dppAttachmentToProjectModel(attachment) {
1152
+ return dppAttachmentToProjectModel(attachment, this.config.dppUrl || "");
1153
+ }
1154
+ };
1155
+
1156
+ // src/graphql/GraphQLClient.ts
1157
+ init_sign();
1158
+ var GraphQLClient = class {
1159
+ constructor(config, store, signingEnabled = false) {
1160
+ this.config = config;
1161
+ this.store = store;
1162
+ this.signingEnabled = signingEnabled;
1163
+ }
1164
+ config;
1165
+ store;
1166
+ signingEnabled;
1167
+ /** Enable or disable request signing (use after authentication). */
1168
+ setSigningEnabled(enabled) {
1169
+ this.signingEnabled = enabled;
1170
+ }
1171
+ /** Execute a GraphQL query or mutation. */
1172
+ async request(operation, variables, extraHeaders) {
1173
+ const bodyObj = { query: operation };
1174
+ if (variables) bodyObj.variables = variables;
1175
+ const opName = extractOperationName(operation);
1176
+ if (opName) bodyObj.operationName = opName;
1177
+ const body = JSON.stringify(bodyObj);
1178
+ const headers = {
1179
+ "Content-Type": "application/json"
1180
+ };
1181
+ if (extraHeaders) {
1182
+ Object.assign(headers, extraHeaders);
1183
+ }
1184
+ if (this.signingEnabled) {
1185
+ try {
1186
+ const signed = await signGraphQLRequest(body, this.store);
1187
+ Object.assign(headers, signed);
1188
+ } catch (err) {
1189
+ console.warn("[interfacer-client] GraphQL signing failed:", err);
1190
+ }
1191
+ }
1192
+ const res = await fetch(this.config.zenflowsUrl, {
1193
+ method: "POST",
1194
+ headers,
1195
+ body
1196
+ });
1197
+ if (!res.ok) {
1198
+ return {
1199
+ errors: [{ message: `HTTP ${res.status}: ${res.statusText}` }]
1200
+ };
1201
+ }
1202
+ return res.json();
1203
+ }
1204
+ };
1205
+ function extractOperationName(operation) {
1206
+ const match = operation.match(/(?:query|mutation)\s+(\w+)/);
1207
+ return match ? match[1] : null;
1208
+ }
1209
+
1210
+ // src/import/ImportClient.ts
1211
+ var ImportClient = class {
1212
+ constructor(config) {
1213
+ this.config = config;
1214
+ }
1215
+ config;
1216
+ /** Analyze a repository for Open Source Hardware compliance. */
1217
+ async analyzeRepoForOsh(repoUrl) {
1218
+ const oshUrl = this.config.oshUrl;
1219
+ if (!oshUrl) throw new Error("oshUrl not configured");
1220
+ try {
1221
+ const res = await fetch(`${oshUrl}/analyze`, {
1222
+ method: "POST",
1223
+ headers: { "Content-Type": "application/json" },
1224
+ body: JSON.stringify({ repo: repoUrl })
1225
+ });
1226
+ const data = await res.json();
1227
+ return data.ok === true;
1228
+ } catch {
1229
+ return false;
1230
+ }
1231
+ }
1232
+ /** Import project metadata from a GitHub URL. */
1233
+ async importFromGithub(url) {
1234
+ const parts = url.replace(/\/$/, "").split("/");
1235
+ const repoName = parts.pop() || "";
1236
+ const owner = parts.pop() || "";
1237
+ if (!owner || !repoName) throw new Error(`Invalid GitHub URL: ${url}`);
1238
+ const repoRes = await fetch(`https://api.github.com/repos/${owner}/${repoName}`, {
1239
+ headers: { Accept: "application/vnd.github.v3+json" }
1240
+ });
1241
+ if (!repoRes.ok) throw new Error(`GitHub API error: ${repoRes.statusText}`);
1242
+ const repoData = await repoRes.json();
1243
+ const main = {
1244
+ title: repoData.name || repoName,
1245
+ link: repoData.html_url || url,
1246
+ description: repoData.description || "",
1247
+ tags: repoData.topics || []
1248
+ };
1249
+ const licenses = [];
1250
+ try {
1251
+ const licenseRes = await fetch(`https://api.github.com/repos/${owner}/${repoName}/license`, {
1252
+ headers: { Accept: "application/vnd.github.v3+json" }
1253
+ });
1254
+ if (licenseRes.ok) {
1255
+ const licenseData = await licenseRes.json();
1256
+ if (licenseData.license?.spdx_id) {
1257
+ licenses.push({
1258
+ scope: "All",
1259
+ licenseId: licenseData.license.spdx_id
1260
+ });
1261
+ }
1262
+ }
1263
+ } catch {
1264
+ }
1265
+ try {
1266
+ const readmeRes = await fetch(
1267
+ `https://api.github.com/repos/${owner}/${repoName}/readme`,
1268
+ {
1269
+ headers: {
1270
+ Accept: "application/vnd.github.v3.raw"
1271
+ }
1272
+ }
1273
+ );
1274
+ if (readmeRes.ok) {
1275
+ const readme = await readmeRes.text();
1276
+ if (readme && !main.description) {
1277
+ main.description = readme.substring(0, 500);
1278
+ }
1279
+ }
1280
+ } catch {
1281
+ }
1282
+ return { main, licenses };
1283
+ }
1284
+ /** Import project metadata from a GitLab project. */
1285
+ async importFromGitlab(host, projectId) {
1286
+ const gitlabHost = host || "https://gitlab.com";
1287
+ const metadataRes = await fetch(`${gitlabHost}/api/v4/projects/${projectId}`);
1288
+ if (!metadataRes.ok) throw new Error(`GitLab API error: ${metadataRes.statusText}`);
1289
+ const metadata = await metadataRes.json();
1290
+ const main = {
1291
+ title: metadata.name || "",
1292
+ link: metadata.web_url || "",
1293
+ description: metadata.description || "",
1294
+ tags: metadata.tag_list || []
1295
+ };
1296
+ return { main };
1297
+ }
1298
+ };
1299
+
1300
+ // src/messaging/InboxClient.ts
1301
+ init_sign();
1302
+ var InboxClient = class {
1303
+ constructor(config, store) {
1304
+ this.config = config;
1305
+ this.store = store;
1306
+ }
1307
+ config;
1308
+ store;
1309
+ /** Sign a request body and return headers + body for POST. */
1310
+ async signedPost(url, body) {
1311
+ const json = JSON.stringify(body);
1312
+ const headers = await signGraphQLRequest(json, this.store);
1313
+ return fetch(url, {
1314
+ method: "POST",
1315
+ headers: {
1316
+ ...headers,
1317
+ "Content-Type": "application/json"
1318
+ },
1319
+ body: json
1320
+ });
1321
+ }
1322
+ /** Send a message to one or more receivers. */
1323
+ async sendMessage(message, receivers, subject = "Subject") {
1324
+ const userId = this.store.getItem("authId");
1325
+ if (!userId) throw new Error("Not authenticated");
1326
+ const inboxSend = this.config.inbox?.send;
1327
+ if (!inboxSend) throw new Error("inbox.send URL not configured");
1328
+ const res = await this.signedPost(inboxSend, {
1329
+ sender: userId,
1330
+ receivers,
1331
+ content: {
1332
+ message,
1333
+ subject,
1334
+ data: (/* @__PURE__ */ new Date()).toISOString()
1335
+ }
1336
+ });
1337
+ if (!res.ok) throw new Error(`Inbox send failed: ${res.statusText}`);
1338
+ }
1339
+ /** Read messages for the current user. */
1340
+ async getMessages(onlyUnread = false) {
1341
+ const userId = this.store.getItem("authId");
1342
+ if (!userId) throw new Error("Not authenticated");
1343
+ const inboxRead = this.config.inbox?.read;
1344
+ if (!inboxRead) throw new Error("inbox.read URL not configured");
1345
+ const res = await this.signedPost(inboxRead, {
1346
+ request_id: 50,
1347
+ receiver: userId,
1348
+ only_unread: onlyUnread
1349
+ });
1350
+ if (!res.ok) throw new Error(`Inbox read failed: ${res.statusText}`);
1351
+ const data = await res.json();
1352
+ const messages = data.messages || [];
1353
+ return messages.sort(
1354
+ (a, b) => new Date(b.content.data).getTime() - new Date(a.content.data).getTime()
1355
+ );
1356
+ }
1357
+ /** Get the count of unread messages. */
1358
+ async getUnreadCount() {
1359
+ const userId = this.store.getItem("authId");
1360
+ if (!userId) throw new Error("Not authenticated");
1361
+ const countUrl = this.config.inbox?.countUnread;
1362
+ if (!countUrl) throw new Error("inbox.countUnread URL not configured");
1363
+ const res = await this.signedPost(countUrl, { receiver: userId });
1364
+ if (!res.ok) throw new Error(`Inbox count failed: ${res.statusText}`);
1365
+ const data = await res.json();
1366
+ return data.count || 0;
1367
+ }
1368
+ /** Mark a message as read. */
1369
+ async markRead(messageId) {
1370
+ const userId = this.store.getItem("authId");
1371
+ if (!userId) throw new Error("Not authenticated");
1372
+ const setReadUrl = this.config.inbox?.setRead;
1373
+ if (!setReadUrl) throw new Error("inbox.setRead URL not configured");
1374
+ const res = await this.signedPost(setReadUrl, {
1375
+ message_id: messageId,
1376
+ receiver: userId,
1377
+ read: true
1378
+ });
1379
+ if (!res.ok) throw new Error(`Inbox setRead failed: ${res.statusText}`);
1380
+ }
1381
+ };
1382
+
1383
+ // src/graphql/instance-variables.ts
1384
+ var QUERY_INSTANCE_VARIABLES = gql`
1385
+ query GetInstanceVariables {
1386
+ instanceVariables {
1387
+ specs {
1388
+ specCurrency { id name }
1389
+ specProjectDesign { id name }
1390
+ specProjectProduct { id name }
1391
+ specProjectService { id name }
1392
+ specDpp { id name }
1393
+ specMachine { id name }
1394
+ specMaterial { id name }
1395
+ }
1396
+ units {
1397
+ unitOne { id }
1398
+ }
1399
+ }
1400
+ }
1401
+ `;
1402
+ var cachedVars = null;
1403
+ async function getInstanceVariables(client) {
1404
+ if (cachedVars) return cachedVars;
1405
+ const res = await client.request(QUERY_INSTANCE_VARIABLES);
1406
+ if (res.errors?.length) {
1407
+ throw new Error(`Failed to fetch instance variables: ${res.errors[0].message}`);
1408
+ }
1409
+ const d = res.data?.instanceVariables;
1410
+ if (!d) throw new Error("No instance variables returned.");
1411
+ cachedVars = {
1412
+ projectDesign: d.specs.specProjectDesign,
1413
+ projectProduct: d.specs.specProjectProduct,
1414
+ projectService: d.specs.specProjectService,
1415
+ dpp: d.specs.specDpp ?? void 0,
1416
+ machine: d.specs.specMachine ?? void 0,
1417
+ material: d.specs.specMaterial ?? void 0,
1418
+ currency: d.specs.specCurrency,
1419
+ unitOne: d.units.unitOne.id
1420
+ };
1421
+ return cachedVars;
1422
+ }
1423
+ function clearInstanceVariablesCache() {
1424
+ cachedVars = null;
1425
+ }
1426
+
1427
+ // src/resources/ResourceClient.ts
1428
+ var ResourceClient = class {
1429
+ constructor(config, store, graphql) {
1430
+ this.config = config;
1431
+ this.store = store;
1432
+ this.graphql = graphql;
1433
+ }
1434
+ config;
1435
+ store;
1436
+ graphql;
1437
+ get userId() {
1438
+ const id = this.store.getItem("authId");
1439
+ if (!id) throw new Error("Not authenticated");
1440
+ return id;
1441
+ }
1442
+ async getInstanceVars() {
1443
+ return getInstanceVariables(this.graphql);
1444
+ }
1445
+ // ─── Helpers ───────────────────────────────────────────────────────
1446
+ specIdForType(vars, type) {
1447
+ switch (type) {
1448
+ case "DESIGN" /* DESIGN */:
1449
+ return vars.projectDesign.id;
1450
+ case "PRODUCT" /* PRODUCT */:
1451
+ return vars.projectProduct.id;
1452
+ case "SERVICE" /* SERVICE */:
1453
+ return vars.projectService.id;
1454
+ case "MACHINE" /* MACHINE */:
1455
+ return vars.machine?.id || this.config.specs?.machine || "";
1456
+ case "DPP" /* DPP */:
1457
+ return vars.dpp?.id || this.config.specs?.dpp || "";
1458
+ }
1459
+ }
1460
+ // ─── Process ───────────────────────────────────────────────────────
1461
+ async createProcess(name) {
1462
+ const res = await this.graphql.request(
1463
+ CREATE_PROCESS,
1464
+ { name }
1465
+ );
1466
+ if (res.errors?.length) throw new Error(`createProcess failed: ${res.errors[0].message}`);
1467
+ return res.data.createProcess.process.id;
1468
+ }
1469
+ // ─── Location ──────────────────────────────────────────────────────
1470
+ async createLocation(params) {
1471
+ const res = await this.graphql.request(CREATE_LOCATION, {
1472
+ name: params.name,
1473
+ addr: params.address || "",
1474
+ lat: params.lat || 0,
1475
+ lng: params.lng || 0
1476
+ });
1477
+ if (res.errors?.length) throw new Error(`createLocation failed: ${res.errors[0].message}`);
1478
+ return res.data.createSpatialThing.spatialThing;
1479
+ }
1480
+ // ─── Create Project (Design, Product, Service) ─────────────────────
1481
+ async createProject(params) {
1482
+ const vars = await this.getInstanceVars();
1483
+ const specId = this.specIdForType(vars, params.projectType);
1484
+ const processId = await this.createProcess(`creation of ${params.name} by owner`);
1485
+ let locationId;
1486
+ if (params.location) {
1487
+ const loc = await this.createLocation(params.location);
1488
+ locationId = loc.id;
1489
+ }
1490
+ const res = await this.graphql.request(CREATE_PROJECT, {
1491
+ name: params.name,
1492
+ note: params.note || "",
1493
+ metadata: JSON.stringify(params.metadata || {}),
1494
+ agent: this.userId,
1495
+ creationTime: (/* @__PURE__ */ new Date()).toISOString(),
1496
+ location: locationId,
1497
+ tags: params.tags || [],
1498
+ resourceSpec: specId,
1499
+ oneUnit: vars.unitOne,
1500
+ images: params.images || [],
1501
+ repo: params.repo || "",
1502
+ process: processId,
1503
+ license: params.license || ""
1504
+ });
1505
+ if (res.errors?.length) throw new Error(`createProject failed: ${res.errors[0].message}`);
1506
+ return res.data.createEconomicEvent.economicEvent.resourceInventoriedAs;
1507
+ }
1508
+ // ─── Create Machine ────────────────────────────────────────────────
1509
+ async createMachine(params) {
1510
+ const vars = await this.getInstanceVars();
1511
+ const machineSpecId = vars.machine?.id || this.config.specs?.machine;
1512
+ if (!machineSpecId) throw new Error("Machine spec ID not found in instance variables or config");
1513
+ const processId = await this.createProcess(`creation of machine ${params.name}`);
1514
+ const res = await this.graphql.request(CREATE_MACHINE_RESOURCE, {
1515
+ agent: this.userId,
1516
+ creationTime: (/* @__PURE__ */ new Date()).toISOString(),
1517
+ process: processId,
1518
+ resourceSpec: machineSpecId,
1519
+ unitOne: vars.unitOne,
1520
+ name: params.name,
1521
+ note: params.note || "",
1522
+ metadata: JSON.stringify(params.metadata || {})
1523
+ });
1524
+ if (res.errors?.length) throw new Error(`createMachine failed: ${res.errors[0].message}`);
1525
+ return res.data.createEconomicEvent.economicEvent.resourceInventoriedAs;
1526
+ }
1527
+ // ─── Create DPP Resource ───────────────────────────────────────────
1528
+ async createDppResource(params) {
1529
+ const vars = await this.getInstanceVars();
1530
+ const dppSpecId = vars.dpp?.id || this.config.specs?.dpp;
1531
+ if (!dppSpecId) throw new Error("DPP spec ID not found in instance variables or config");
1532
+ const processId = await this.createProcess(`DPP creation for ${params.name}`);
1533
+ const res = await this.graphql.request(CREATE_DPP_RESOURCE, {
1534
+ agent: this.userId,
1535
+ creationTime: (/* @__PURE__ */ new Date()).toISOString(),
1536
+ process: processId,
1537
+ resourceSpec: dppSpecId,
1538
+ unitOne: vars.unitOne,
1539
+ dppUlid: JSON.stringify({ dppServiceUlid: params.dppUlid }),
1540
+ name: params.name,
1541
+ note: params.note || ""
1542
+ });
1543
+ if (res.errors?.length) throw new Error(`createDppResource failed: ${res.errors[0].message}`);
1544
+ return res.data.createEconomicEvent.economicEvent.resourceInventoriedAs;
1545
+ }
1546
+ // ─── Queries ───────────────────────────────────────────────────────
1547
+ async getResource(id) {
1548
+ const res = await this.graphql.request(
1549
+ QUERY_RESOURCE,
1550
+ { id }
1551
+ );
1552
+ return res.data?.economicResource ?? null;
1553
+ }
1554
+ async listResources(filter, pagination) {
1555
+ const res = await this.graphql.request(FETCH_RESOURCES, {
1556
+ ...pagination,
1557
+ filter: filter || {}
1558
+ });
1559
+ return res.data || {};
1560
+ }
1561
+ async getProjects(filter, pagination) {
1562
+ const res = await this.graphql.request(QUERY_PROJECTS, {
1563
+ ...pagination,
1564
+ filter: filter || {}
1565
+ });
1566
+ return res.data || {};
1567
+ }
1568
+ async getMachines() {
1569
+ const vars = await this.getInstanceVars();
1570
+ const machineSpecId = vars.machine?.id || this.config.specs?.machine;
1571
+ if (!machineSpecId) throw new Error("Machine spec ID not found in instance variables or config");
1572
+ const res = await this.graphql.request(QUERY_MACHINES, {
1573
+ resourceSpecId: machineSpecId
1574
+ });
1575
+ return res.data || {};
1576
+ }
1577
+ // ─── Relations ─────────────────────────────────────────────────────
1578
+ async citeResource(resourceId, processId) {
1579
+ const vars = await this.getInstanceVars();
1580
+ const res = await this.graphql.request(CITE_PROJECT, {
1581
+ agent: this.userId,
1582
+ creationTime: (/* @__PURE__ */ new Date()).toISOString(),
1583
+ resource: resourceId,
1584
+ process: processId,
1585
+ unitOne: vars.unitOne
1586
+ });
1587
+ if (res.errors?.length) throw new Error(`citeResource failed: ${res.errors[0].message}`);
1588
+ }
1589
+ async consumeResource(resourceId, processId) {
1590
+ const vars = await this.getInstanceVars();
1591
+ const res = await this.graphql.request(CONSUME_RESOURCE, {
1592
+ agent: this.userId,
1593
+ creationTime: (/* @__PURE__ */ new Date()).toISOString(),
1594
+ resource: resourceId,
1595
+ process: processId,
1596
+ unitOne: vars.unitOne
1597
+ });
1598
+ if (res.errors?.length) throw new Error(`consumeResource failed: ${res.errors[0].message}`);
1599
+ }
1600
+ async contributeToResource(processId, contributionTypeSpecId) {
1601
+ const vars = await this.getInstanceVars();
1602
+ const res = await this.graphql.request(CONTRIBUTE_TO_PROJECT, {
1603
+ agent: this.userId,
1604
+ creationTime: (/* @__PURE__ */ new Date()).toISOString(),
1605
+ process: processId,
1606
+ unitOne: vars.unitOne,
1607
+ conformsTo: contributionTypeSpecId
1608
+ });
1609
+ if (res.errors?.length) throw new Error(`contribute failed: ${res.errors[0].message}`);
1610
+ }
1611
+ // ─── Metadata ──────────────────────────────────────────────────────
1612
+ async updateMetadata(resourceId, metadata, quantity) {
1613
+ const res = await this.graphql.request(UPDATE_METADATA, {
1614
+ process: await this.createProcess(`metadata update`),
1615
+ agent: this.userId,
1616
+ resource: resourceId,
1617
+ quantity: quantity || { hasNumericalValue: 1, hasUnit: (await this.getInstanceVars()).unitOne },
1618
+ now: (/* @__PURE__ */ new Date()).toISOString(),
1619
+ metadata: JSON.stringify(metadata)
1620
+ });
1621
+ if (res.errors?.length) throw new Error(`updateMetadata failed: ${res.errors[0].message}`);
1622
+ }
1623
+ async updateClassifiedAs(resourceId, tags) {
1624
+ const res = await this.graphql.request(UPDATE_RESOURCE_CLASSIFIED_AS, {
1625
+ id: resourceId,
1626
+ classifiedAs: tags
1627
+ });
1628
+ if (res.errors?.length) throw new Error(`updateClassifiedAs failed: ${res.errors[0].message}`);
1629
+ }
1630
+ async relocateResource(resourceId, locationId) {
1631
+ const vars = await this.getInstanceVars();
1632
+ const res = await this.graphql.request(RELOCATE_PROJECT, {
1633
+ process: await this.createProcess(`relocate`),
1634
+ agent: this.userId,
1635
+ resource: resourceId,
1636
+ quantity: { hasNumericalValue: 1, hasUnit: vars.unitOne },
1637
+ now: (/* @__PURE__ */ new Date()).toISOString(),
1638
+ location: locationId
1639
+ });
1640
+ if (res.errors?.length) throw new Error(`relocate failed: ${res.errors[0].message}`);
1641
+ }
1642
+ // ─── Proposals ─────────────────────────────────────────────────────
1643
+ async proposeContribution(params) {
1644
+ const vars = await this.getInstanceVars();
1645
+ const processId = await this.createProcess("contribution proposal");
1646
+ const creationTime = (/* @__PURE__ */ new Date()).toISOString();
1647
+ const intentsRes = await this.graphql.request(PROPOSE_CONTRIBUTION, {
1648
+ process: processId,
1649
+ owner: params.ownerId,
1650
+ proposer: this.userId,
1651
+ creationTime,
1652
+ resourceForked: params.resourceForkedId,
1653
+ unitOne: vars.unitOne,
1654
+ resourceOrigin: params.resourceOriginId
1655
+ });
1656
+ if (intentsRes.errors?.length) throw new Error(`proposeContribution intents failed: ${intentsRes.errors[0].message}`);
1657
+ const proposalRes = await this.graphql.request(CREATE_PROPOSAL, {
1658
+ name: `Contribution to resource`,
1659
+ note: params.note
1660
+ });
1661
+ if (proposalRes.errors?.length) throw new Error(`createProposal failed: ${proposalRes.errors[0].message}`);
1662
+ const proposalId = proposalRes.data.createProposal.proposal.id;
1663
+ const citeIntentId = intentsRes.data.citeResourceForked.intent.id;
1664
+ const acceptIntentId = intentsRes.data.acceptResourceOrigin.intent.id;
1665
+ const modifyIntentId = intentsRes.data.modifyResourceOrigin.intent.id;
1666
+ const linkRes = await this.graphql.request(LINK_CONTRIBUTION_PROPOSAL_INTENT, {
1667
+ proposal: proposalId,
1668
+ citeIntent: citeIntentId,
1669
+ acceptIntent: acceptIntentId,
1670
+ modifyIntent: modifyIntentId
1671
+ });
1672
+ if (linkRes.errors?.length) throw new Error(`linkIntents failed: ${linkRes.errors[0].message}`);
1673
+ return { proposalId, citeIntentId, acceptIntentId, modifyIntentId };
1674
+ }
1675
+ async acceptProposal(params) {
1676
+ const vars = await this.getInstanceVars();
1677
+ const processId = await this.createProcess("accept contribution");
1678
+ const eventsRes = await this.graphql.request(ACCEPT_PROPOSAL, {
1679
+ process: processId,
1680
+ owner: params.ownerId,
1681
+ proposer: params.proposerId,
1682
+ unitOne: vars.unitOne,
1683
+ resourceForked: params.resourceForkedId,
1684
+ resourceOrigin: params.resourceOriginId,
1685
+ creationTime: (/* @__PURE__ */ new Date()).toISOString(),
1686
+ metadata: JSON.stringify(params.newMetadata)
1687
+ });
1688
+ if (eventsRes.errors?.length) throw new Error(`acceptProposal events failed: ${eventsRes.errors[0].message}`);
1689
+ const satRes = await this.graphql.request(SATISFY_INTENTS, {
1690
+ unitOne: vars.unitOne,
1691
+ intentCited: params.citeIntentId,
1692
+ intentAccepted: params.acceptIntentId,
1693
+ intentModify: params.modifyIntentId,
1694
+ eventCite: eventsRes.data.cite.economicEvent.id,
1695
+ eventAccept: eventsRes.data.accept.economicEvent.id,
1696
+ eventModify: eventsRes.data.modify.economicEvent.id
1697
+ });
1698
+ if (satRes.errors?.length) throw new Error(`satisfyIntents failed: ${satRes.errors[0].message}`);
1699
+ }
1700
+ async rejectProposal(intentCite, intentAccept, intentModify) {
1701
+ const res = await this.graphql.request(REJECT_PROPOSAL, {
1702
+ intentCite,
1703
+ intentAccept,
1704
+ intentModify
1705
+ });
1706
+ if (res.errors?.length) throw new Error(`rejectProposal failed: ${res.errors[0].message}`);
1707
+ }
1708
+ };
1709
+
1710
+ // src/social/SocialClient.ts
1711
+ init_sign();
1712
+ var SocialClient = class {
1713
+ constructor(config, store) {
1714
+ this.config = config;
1715
+ this.store = store;
1716
+ }
1717
+ config;
1718
+ store;
1719
+ get personBase() {
1720
+ const base = this.config.social?.personBase;
1721
+ if (!base) throw new Error("social.personBase URL not configured");
1722
+ return base;
1723
+ }
1724
+ get erBase() {
1725
+ const base = this.config.social?.economicResourceBase;
1726
+ if (!base) throw new Error("social.economicResourceBase URL not configured");
1727
+ return base;
1728
+ }
1729
+ get userId() {
1730
+ const id = this.store.getItem("authId");
1731
+ if (!id) throw new Error("Not authenticated");
1732
+ return id;
1733
+ }
1734
+ /** Post an ActivityStreams activity to the user's outbox. */
1735
+ async postActivity(activity) {
1736
+ const body = JSON.stringify(activity);
1737
+ const headers = await signGraphQLRequest(body, this.store);
1738
+ const res = await fetch(`${this.personBase}/${this.userId}/outbox`, {
1739
+ method: "POST",
1740
+ headers: { ...headers, "Content-Type": "application/json" },
1741
+ body
1742
+ });
1743
+ if (!res.ok) throw new Error(`ActivityPub post failed: ${res.statusText}`);
1744
+ }
1745
+ /** Like a resource. */
1746
+ async likeResource(resourceId) {
1747
+ await this.postActivity({
1748
+ "@context": "https://www.w3.org/ns/activitystreams",
1749
+ type: "Like",
1750
+ actor: `${this.personBase}/${this.userId}`,
1751
+ object: `${this.erBase}/${resourceId}`,
1752
+ published: (/* @__PURE__ */ new Date()).toISOString()
1753
+ });
1754
+ }
1755
+ /** Follow (watch) a resource. */
1756
+ async followResource(resourceId) {
1757
+ await this.postActivity({
1758
+ "@context": "https://www.w3.org/ns/activitystreams",
1759
+ type: "Follow",
1760
+ actor: `${this.personBase}/${this.userId}`,
1761
+ object: `${this.erBase}/${resourceId}`,
1762
+ published: (/* @__PURE__ */ new Date()).toISOString()
1763
+ });
1764
+ }
1765
+ /** Get the list of resource IDs the current user has liked. */
1766
+ async getLikes() {
1767
+ const res = await fetch(`${this.personBase}/${this.userId}/liked`);
1768
+ const data = await res.json();
1769
+ const likes = [];
1770
+ for (const item of data.data?.items || []) {
1771
+ const likeRes = await fetch(item);
1772
+ const likeData = await likeRes.json();
1773
+ const object = likeData.data?.object || "";
1774
+ likes.push(object.split("economicresource/")[1] || object);
1775
+ }
1776
+ return likes.filter(Boolean);
1777
+ }
1778
+ /** Check if the current user liked a resource. */
1779
+ async isLiked(resourceId) {
1780
+ const likes = await this.getLikes();
1781
+ return likes.includes(resourceId);
1782
+ }
1783
+ /** Get the list of follower IDs for a resource. */
1784
+ async getFollowers(resourceId) {
1785
+ const res = await fetch(`${this.erBase}/${resourceId}/follower`);
1786
+ const data = await res.json();
1787
+ return (data.data || []).map((f) => f.split("person/")[1] || f).filter(Boolean);
1788
+ }
1789
+ /** Get the list of resources the current user is following. */
1790
+ async getFollowing() {
1791
+ const res = await fetch(`${this.personBase}/${this.userId}/following`);
1792
+ const data = await res.json();
1793
+ return (data.data || []).map((f) => f.split("economicresource/")[1] || f).filter(Boolean);
1794
+ }
1795
+ /** Check if the current user is following a resource. */
1796
+ async isFollowing(resourceId) {
1797
+ const followers = await this.getFollowers(resourceId);
1798
+ return followers.includes(this.userId);
1799
+ }
1800
+ };
1801
+
1802
+ // src/tagging/constants.ts
1803
+ var TAG_PREFIX = {
1804
+ USER: "tag",
1805
+ CATEGORY: "category",
1806
+ MACHINE: "machine",
1807
+ MATERIAL: "material",
1808
+ POWER_COMPAT: "powercompat",
1809
+ POWER_REQ: "powerreq",
1810
+ REPLICABILITY: "replicability",
1811
+ RECYCLABILITY: "recyclability",
1812
+ REPAIRABILITY: "repairability",
1813
+ ENV_ENERGY: "env-energy",
1814
+ ENV_CO2: "env-co2",
1815
+ SERVICE_TYPE: "servicetype",
1816
+ AVAILABILITY: "availability",
1817
+ LICENSE: "license",
1818
+ MANUFACTURABLE: "manufacturable"
1819
+ };
1820
+ var SYSTEM_TAG_PREFIXES = [
1821
+ TAG_PREFIX.CATEGORY,
1822
+ TAG_PREFIX.MACHINE,
1823
+ TAG_PREFIX.MATERIAL,
1824
+ TAG_PREFIX.POWER_COMPAT,
1825
+ TAG_PREFIX.POWER_REQ,
1826
+ TAG_PREFIX.REPLICABILITY,
1827
+ TAG_PREFIX.RECYCLABILITY,
1828
+ TAG_PREFIX.REPAIRABILITY,
1829
+ TAG_PREFIX.ENV_ENERGY,
1830
+ TAG_PREFIX.ENV_CO2,
1831
+ TAG_PREFIX.SERVICE_TYPE,
1832
+ TAG_PREFIX.AVAILABILITY,
1833
+ TAG_PREFIX.LICENSE,
1834
+ TAG_PREFIX.MANUFACTURABLE
1835
+ ];
1836
+ var LEGACY_SYSTEM_TAG_PATTERNS = [
1837
+ "power_compat-",
1838
+ "power_",
1839
+ "env_",
1840
+ "mat:",
1841
+ "c:",
1842
+ "pc:",
1843
+ "env:",
1844
+ "pwr:",
1845
+ "rep:",
1846
+ "m:"
1847
+ ];
1848
+ var PRODUCT_CATEGORY_OPTIONS = [
1849
+ "Electronics",
1850
+ "Tools",
1851
+ "Furniture",
1852
+ "Home renovation",
1853
+ "Energy",
1854
+ "Wearables",
1855
+ "Medical",
1856
+ "Sustainability",
1857
+ "Education"
1858
+ ];
1859
+ var POWER_COMPATIBILITY_OPTIONS = [
1860
+ "120V AC",
1861
+ "220-240V AC",
1862
+ "12V DC",
1863
+ "24V DC",
1864
+ "Battery Powered",
1865
+ "USB-C"
1866
+ ];
1867
+ var REPLICABILITY_OPTIONS = ["High", "Medium", "Low"];
1868
+ var SERVICE_TYPE_OPTIONS = ["Fabrication", "Learning & Education", "Space Access"];
1869
+ var AVAILABILITY_OPTIONS = [
1870
+ "Available Now",
1871
+ "Booking Required",
1872
+ "Weekdays Only",
1873
+ "Weekends Available"
1874
+ ];
1875
+ var RECYCLABILITY_THRESHOLDS_PCT = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
1876
+ var POWER_REQUIREMENT_THRESHOLDS_W = [
1877
+ 0,
1878
+ 10,
1879
+ 25,
1880
+ 50,
1881
+ 75,
1882
+ 100,
1883
+ 150,
1884
+ 200,
1885
+ 250,
1886
+ 300,
1887
+ 500,
1888
+ 750,
1889
+ 1e3,
1890
+ 1500,
1891
+ 2e3
1892
+ ];
1893
+ var ENERGY_THRESHOLDS_KWH = [
1894
+ 0,
1895
+ 10,
1896
+ 20,
1897
+ 30,
1898
+ 50,
1899
+ 100,
1900
+ 200,
1901
+ 300,
1902
+ 500,
1903
+ 750,
1904
+ 1e3,
1905
+ 1500,
1906
+ 2e3
1907
+ ];
1908
+ var CO2_THRESHOLDS_KG = [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 5, 7.5, 10, 15, 20];
1909
+ var REPAIRABILITY_AVAILABLE_TAG = "repairability-available";
1910
+ var MANUFACTURABLE_TRUE_TAG = "manufacturable-true";
1911
+
1912
+ // src/tagging/TaggingClient.ts
1913
+ function slugifyTagValue(value) {
1914
+ return value.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, "");
1915
+ }
1916
+ function prefixedTag(prefix, value) {
1917
+ const slug = slugifyTagValue(value);
1918
+ if (!slug) return void 0;
1919
+ return `${prefix}-${slug}`;
1920
+ }
1921
+ function userTag(raw) {
1922
+ const slug = slugifyTagValue(raw);
1923
+ if (!slug) return void 0;
1924
+ return `${TAG_PREFIX.USER}-${slug}`;
1925
+ }
1926
+ function isUserTag(tag) {
1927
+ return tag.startsWith(`${TAG_PREFIX.USER}-`);
1928
+ }
1929
+ function stripUserTagPrefix(tag) {
1930
+ return isUserTag(tag) ? tag.substring(TAG_PREFIX.USER.length + 1) : tag;
1931
+ }
1932
+ function isSystemTag(tag) {
1933
+ if (isUserTag(tag)) return false;
1934
+ if (SYSTEM_TAG_PREFIXES.some((p) => tag.startsWith(`${p}-`))) return true;
1935
+ if (LEGACY_SYSTEM_TAG_PATTERNS.some((p) => tag.startsWith(p))) return true;
1936
+ return false;
1937
+ }
1938
+ function extractUserTagValues(tags) {
1939
+ if (!tags || tags.length === 0) return [];
1940
+ const out = [];
1941
+ const seen = /* @__PURE__ */ new Set();
1942
+ for (const tag of tags) {
1943
+ if (!tag) continue;
1944
+ let value;
1945
+ if (isUserTag(tag)) {
1946
+ value = decodeURIComponent(stripUserTagPrefix(tag));
1947
+ } else if (!isSystemTag(tag)) {
1948
+ value = decodeURIComponent(tag);
1949
+ }
1950
+ if (!value) continue;
1951
+ if (seen.has(value)) continue;
1952
+ seen.add(value);
1953
+ out.push(value);
1954
+ }
1955
+ return out;
1956
+ }
1957
+ function normalizeUserTagsForSave(tags) {
1958
+ const out = [];
1959
+ const seen = /* @__PURE__ */ new Set();
1960
+ for (const raw of tags) {
1961
+ const trimmed = raw?.trim();
1962
+ if (!trimmed) continue;
1963
+ if (isSystemTag(trimmed)) continue;
1964
+ const canonical = isUserTag(trimmed) ? trimmed : userTag(trimmed);
1965
+ if (!canonical) continue;
1966
+ if (seen.has(canonical)) continue;
1967
+ seen.add(canonical);
1968
+ out.push(canonical);
1969
+ }
1970
+ return out;
1971
+ }
1972
+ function formatNumericTagValue(value) {
1973
+ if (!Number.isFinite(value)) return "";
1974
+ const normalized = Number.isInteger(value) ? String(value) : String(value).replace(/\./g, "p");
1975
+ return normalized.replace(/[^0-9p-]/g, "");
1976
+ }
1977
+ function asSortedNumericThresholds(thresholds) {
1978
+ return Array.from(new Set(thresholds.filter((n) => Number.isFinite(n)))).sort((a, b) => a - b);
1979
+ }
1980
+ function isPrefixedTag(tag, prefixes) {
1981
+ return prefixes.some((prefix) => tag.startsWith(`${prefix}-`));
1982
+ }
1983
+ function monotonicRangeTags(prefix, value, thresholds) {
1984
+ if (!Number.isFinite(value)) return [];
1985
+ const sorted = asSortedNumericThresholds(thresholds);
1986
+ const ge = sorted.filter((t) => t <= value).map((t) => `${prefix}-ge-${formatNumericTagValue(t)}`);
1987
+ const le = sorted.filter((t) => t >= value).map((t) => `${prefix}-le-${formatNumericTagValue(t)}`);
1988
+ return mergeTags(ge, le);
1989
+ }
1990
+ function rangeFilterTags(prefix, minValue, maxValue, thresholds) {
1991
+ const sorted = asSortedNumericThresholds(thresholds);
1992
+ const tags = [];
1993
+ if (typeof minValue === "number" && Number.isFinite(minValue)) {
1994
+ const lower = sorted.reduce((acc, t) => t <= minValue ? t : acc, void 0);
1995
+ if (typeof lower === "number") tags.push(`${prefix}-ge-${formatNumericTagValue(lower)}`);
1996
+ }
1997
+ if (typeof maxValue === "number" && Number.isFinite(maxValue)) {
1998
+ const upper = sorted.find((t) => t >= maxValue);
1999
+ if (typeof upper === "number") tags.push(`${prefix}-le-${formatNumericTagValue(upper)}`);
2000
+ }
2001
+ return mergeTags(tags);
2002
+ }
2003
+ function derivedProductFilterTags(filters) {
2004
+ const categories = (filters.categories || []).map((value) => prefixedTag(TAG_PREFIX.CATEGORY, value)).filter((t) => Boolean(t));
2005
+ const powerCompatibility = (filters.powerCompatibility || []).map((value) => prefixedTag(TAG_PREFIX.POWER_COMPAT, value)).filter((t) => Boolean(t));
2006
+ const replicability = (filters.replicability || []).map((value) => prefixedTag(TAG_PREFIX.REPLICABILITY, value)).filter((t) => Boolean(t));
2007
+ const recyclability = typeof filters.recyclabilityPct === "number" ? monotonicRangeTags(TAG_PREFIX.RECYCLABILITY, filters.recyclabilityPct, RECYCLABILITY_THRESHOLDS_PCT) : [];
2008
+ const repairability = filters.repairability ? [REPAIRABILITY_AVAILABLE_TAG] : [];
2009
+ const powerReq = typeof filters.powerRequirementW === "number" ? monotonicRangeTags(TAG_PREFIX.POWER_REQ, filters.powerRequirementW, POWER_REQUIREMENT_THRESHOLDS_W) : [];
2010
+ const energy = typeof filters.energyKwh === "number" ? monotonicRangeTags(TAG_PREFIX.ENV_ENERGY, filters.energyKwh, ENERGY_THRESHOLDS_KWH) : [];
2011
+ const co2 = typeof filters.co2Kg === "number" ? monotonicRangeTags(TAG_PREFIX.ENV_CO2, filters.co2Kg, CO2_THRESHOLDS_KG) : [];
2012
+ return mergeTags(
2013
+ categories,
2014
+ powerCompatibility,
2015
+ replicability,
2016
+ recyclability,
2017
+ repairability,
2018
+ powerReq,
2019
+ energy,
2020
+ co2
2021
+ );
2022
+ }
2023
+ function derivedServiceFilterTags(filters) {
2024
+ const serviceType = (filters.serviceType || []).map((value) => prefixedTag(TAG_PREFIX.SERVICE_TYPE, value)).filter((t) => Boolean(t));
2025
+ const availability = (filters.availability || []).map((value) => prefixedTag(TAG_PREFIX.AVAILABILITY, value)).filter((t) => Boolean(t));
2026
+ return mergeTags(serviceType, availability);
2027
+ }
2028
+ function removeTagsWithPrefixes(tags, prefixes) {
2029
+ return tags.filter((tag) => !isPrefixedTag(tag, prefixes));
2030
+ }
2031
+ function mergeTags(...tagLists) {
2032
+ const merged = [];
2033
+ const seen = /* @__PURE__ */ new Set();
2034
+ for (const list of tagLists) {
2035
+ if (!list) continue;
2036
+ for (const tag of list) {
2037
+ const trimmed = tag.trim();
2038
+ if (!trimmed) continue;
2039
+ if (seen.has(trimmed)) continue;
2040
+ seen.add(trimmed);
2041
+ merged.push(trimmed);
2042
+ }
2043
+ }
2044
+ return merged;
2045
+ }
2046
+ var TaggingClient = class {
2047
+ // User tag operations
2048
+ normalizeUserTags = normalizeUserTagsForSave;
2049
+ extractUserTagValues = extractUserTagValues;
2050
+ isSystemTag = isSystemTag;
2051
+ isUserTag = isUserTag;
2052
+ userTag = userTag;
2053
+ // Filter tag derivation
2054
+ derivedProductFilterTags = derivedProductFilterTags;
2055
+ derivedServiceFilterTags = derivedServiceFilterTags;
2056
+ // Numeric range helpers
2057
+ monotonicRangeTags = monotonicRangeTags;
2058
+ rangeFilterTags = rangeFilterTags;
2059
+ // Utilities
2060
+ slugifyTagValue = slugifyTagValue;
2061
+ prefixedTag = prefixedTag;
2062
+ mergeTags = mergeTags;
2063
+ removeTagsWithPrefixes = removeTagsWithPrefixes;
2064
+ // Constants
2065
+ TAG_PREFIX = TAG_PREFIX;
2066
+ SYSTEM_TAG_PREFIXES = SYSTEM_TAG_PREFIXES;
2067
+ PRODUCT_CATEGORY_OPTIONS = PRODUCT_CATEGORY_OPTIONS;
2068
+ POWER_COMPATIBILITY_OPTIONS = POWER_COMPATIBILITY_OPTIONS;
2069
+ REPLICABILITY_OPTIONS = REPLICABILITY_OPTIONS;
2070
+ SERVICE_TYPE_OPTIONS = SERVICE_TYPE_OPTIONS;
2071
+ AVAILABILITY_OPTIONS = AVAILABILITY_OPTIONS;
2072
+ RECYCLABILITY_THRESHOLDS_PCT = RECYCLABILITY_THRESHOLDS_PCT;
2073
+ POWER_REQUIREMENT_THRESHOLDS_W = POWER_REQUIREMENT_THRESHOLDS_W;
2074
+ ENERGY_THRESHOLDS_KWH = ENERGY_THRESHOLDS_KWH;
2075
+ CO2_THRESHOLDS_KG = CO2_THRESHOLDS_KG;
2076
+ REPAIRABILITY_AVAILABLE_TAG = REPAIRABILITY_AVAILABLE_TAG;
2077
+ MANUFACTURABLE_TRUE_TAG = MANUFACTURABLE_TRUE_TAG;
2078
+ };
2079
+
2080
+ // src/wallet/WalletClient.ts
2081
+ init_sign();
2082
+ var WalletClient = class {
2083
+ constructor(config, store) {
2084
+ this.config = config;
2085
+ this.store = store;
2086
+ }
2087
+ config;
2088
+ store;
2089
+ /** Get the current balance for a token type. */
2090
+ async getBalance(agentId, token) {
2091
+ const walletUrl = this.config.walletUrl;
2092
+ if (!walletUrl) throw new Error("walletUrl not configured");
2093
+ const res = await fetch(`${walletUrl}/${token}/${agentId}`);
2094
+ const data = await res.json();
2095
+ return data.success === true ? Number(data.amount) / 100 : 0;
2096
+ }
2097
+ /** Get the balance at a specific point in time. */
2098
+ async getBalanceAt(agentId, token, timestamp) {
2099
+ const walletUrl = this.config.walletUrl;
2100
+ if (!walletUrl) throw new Error("walletUrl not configured");
2101
+ const res = await fetch(`${walletUrl}/${token}/${agentId}?until=${timestamp}`);
2102
+ const data = await res.json();
2103
+ return data.success === true ? Number(data.amount) / 100 : 0;
2104
+ }
2105
+ /** Add points to an agent. */
2106
+ async addPoints(agentId, token, amount = 1) {
2107
+ const walletUrl = this.config.walletUrl;
2108
+ if (!walletUrl) throw new Error("walletUrl not configured");
2109
+ const body = JSON.stringify({
2110
+ token,
2111
+ amount: String(amount),
2112
+ owner: agentId
2113
+ });
2114
+ const headers = await signGraphQLRequest(body, this.store);
2115
+ const res = await fetch(walletUrl, {
2116
+ method: "POST",
2117
+ headers: { ...headers, "Content-Type": "application/json" },
2118
+ body
2119
+ });
2120
+ if (!res.ok) throw new Error(`Wallet addPoints failed: ${res.statusText}`);
2121
+ }
2122
+ /** Get point trend over a period (change since period start). */
2123
+ async getTrend(agentId, token, periodStartMs) {
2124
+ const periodStartBalance = await this.getBalanceAt(agentId, token, periodStartMs);
2125
+ const currentBalance = await this.getBalance(agentId, token);
2126
+ if (periodStartBalance === 0) return 0;
2127
+ return (currentBalance - periodStartBalance) / periodStartBalance * 100;
2128
+ }
2129
+ };
2130
+
2131
+ // src/client.ts
2132
+ var InterfacerClient = class {
2133
+ config;
2134
+ store;
2135
+ // Sub-clients (lazily initialized)
2136
+ _graphql;
2137
+ _auth;
2138
+ _resources;
2139
+ _files;
2140
+ _dpp;
2141
+ _inbox;
2142
+ _wallet;
2143
+ _social;
2144
+ _tagging;
2145
+ _import;
2146
+ constructor(config, store) {
2147
+ this.config = config;
2148
+ this.store = store ?? createLocalStorageAdapter() ?? createMemoryStorage();
2149
+ }
2150
+ // ─── Lazy accessors ───────────────────────────────────────────────
2151
+ get graphql() {
2152
+ return this._graphql ??= new GraphQLClient(this.config, this.store);
2153
+ }
2154
+ get auth() {
2155
+ return this._auth ??= new AuthClient(this.config, this.store, this.graphql);
2156
+ }
2157
+ get resources() {
2158
+ return this._resources ??= new ResourceClient(this.config, this.store, this.graphql);
2159
+ }
2160
+ get files() {
2161
+ return this._files ??= new FileClient(this.config, this.store);
2162
+ }
2163
+ get dpp() {
2164
+ return this._dpp ??= new DppClient(this.config, this.store);
2165
+ }
2166
+ get inbox() {
2167
+ return this._inbox ??= new InboxClient(this.config, this.store);
2168
+ }
2169
+ get wallet() {
2170
+ return this._wallet ??= new WalletClient(this.config, this.store);
2171
+ }
2172
+ get social() {
2173
+ return this._social ??= new SocialClient(this.config, this.store);
2174
+ }
2175
+ get tagging() {
2176
+ return this._tagging ??= new TaggingClient();
2177
+ }
2178
+ get import() {
2179
+ return this._import ??= new ImportClient(this.config);
2180
+ }
2181
+ // ─── High-level composite operations ───────────────────────────────
2182
+ /**
2183
+ * Full registration flow:
2184
+ * 1. Request HMAC from server
2185
+ * 2. Derive keys from challenges
2186
+ * 3. Register user on Zenflows
2187
+ * 4. Login (verify)
2188
+ */
2189
+ async register(params) {
2190
+ const hmac = await this.auth.requestHmac(params.email, true);
2191
+ await this.auth.deriveKeys(params.challenges, params.email, hmac);
2192
+ await this.auth.registerUser({
2193
+ name: params.name,
2194
+ user: params.username,
2195
+ email: params.email
2196
+ });
2197
+ await this.auth.login({ email: params.email });
2198
+ }
2199
+ /**
2200
+ * Check if a user is currently authenticated (has keys in storage).
2201
+ */
2202
+ isAuthenticated() {
2203
+ const pk = this.store.getItem("eddsaPrivateKey");
2204
+ const email = this.store.getItem("authEmail");
2205
+ return Boolean(pk) && Boolean(email);
2206
+ }
2207
+ /**
2208
+ * Get the currently stored EdDSA public key.
2209
+ */
2210
+ getPublicKey() {
2211
+ return this.store.getItem("eddsaPublicKey") ?? null;
2212
+ }
2213
+ };
2214
+
2215
+ // src/index.ts
2216
+ init_hashing();
2217
+
2218
+ // src/config/config.ts
2219
+ function createConfig(config) {
2220
+ return config;
2221
+ }
2222
+
2223
+ // src/index.ts
2224
+ init_sign();
2225
+ export {
2226
+ AVAILABILITY_OPTIONS,
2227
+ AuthClient,
2228
+ CO2_THRESHOLDS_KG,
2229
+ DppClient,
2230
+ ENERGY_THRESHOLDS_KWH,
2231
+ FileClient,
2232
+ GraphQLClient,
2233
+ ImportClient,
2234
+ InboxClient,
2235
+ InterfacerClient,
2236
+ MANUFACTURABLE_TRUE_TAG,
2237
+ POWER_COMPATIBILITY_OPTIONS,
2238
+ POWER_REQUIREMENT_THRESHOLDS_W,
2239
+ PRODUCT_CATEGORY_OPTIONS,
2240
+ RECYCLABILITY_THRESHOLDS_PCT,
2241
+ REPAIRABILITY_AVAILABLE_TAG,
2242
+ REPLICABILITY_OPTIONS,
2243
+ ResourceClient,
2244
+ SERVICE_TYPE_OPTIONS,
2245
+ SYSTEM_TAG_PREFIXES,
2246
+ SocialClient,
2247
+ TAG_PREFIX,
2248
+ TaggingClient,
2249
+ WalletClient,
2250
+ clearInstanceVariablesCache,
2251
+ createConfig,
2252
+ createMemoryStorage,
2253
+ derivedProductFilterTags,
2254
+ extractUserTagValues,
2255
+ formatImageSrc,
2256
+ getInstanceVariables,
2257
+ getResourceImage,
2258
+ isSystemTag,
2259
+ isUserTag,
2260
+ mergeTags,
2261
+ monotonicRangeTags,
2262
+ normalizeUserTagsForSave,
2263
+ prefixedTag,
2264
+ prepFileForZenflows,
2265
+ prepFilesForZenflows,
2266
+ rangeFilterTags,
2267
+ removeTagsWithPrefixes,
2268
+ signDidRequest,
2269
+ signFileUpload,
2270
+ signGraphQLRequest,
2271
+ slugifyTagValue,
2272
+ stripUserTagPrefix,
2273
+ userTag
2274
+ };
2275
+ //# sourceMappingURL=index.js.map