@dyne/interfacer-client 0.6.1 → 0.7.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.cjs CHANGED
@@ -254,6 +254,7 @@ var init_hashing = __esm({
254
254
  // src/index.ts
255
255
  var index_exports = {};
256
256
  __export(index_exports, {
257
+ ACCEPT_CONTRIBUTION: () => ACCEPT_CONTRIBUTION,
257
258
  ACCEPT_PROPOSAL: () => ACCEPT_PROPOSAL,
258
259
  ASK_RESOURCE_PRIMARY_ACCOUNTABLE: () => ASK_RESOURCE_PRIMARY_ACCOUNTABLE,
259
260
  AVAILABILITY_OPTIONS: () => AVAILABILITY_OPTIONS,
@@ -289,17 +290,21 @@ __export(index_exports, {
289
290
  GET_USER_IMAGES: () => GET_USER_IMAGES,
290
291
  GET_USER_LAYOUT: () => GET_USER_LAYOUT,
291
292
  GraphQLClient: () => GraphQLClient,
293
+ GraphQLRequestError: () => GraphQLRequestError,
294
+ GraphQLSigningError: () => GraphQLSigningError,
292
295
  ImportClient: () => ImportClient,
293
296
  InboxClient: () => InboxClient,
294
297
  InterfacerClient: () => InterfacerClient,
295
298
  LINK_CONTRIBUTION_PROPOSAL_INTENT: () => LINK_CONTRIBUTION_PROPOSAL_INTENT,
296
299
  LINK_PROPOSAL_AND_INTENT: () => LINK_PROPOSAL_AND_INTENT,
297
300
  MANUFACTURABLE_TRUE_TAG: () => MANUFACTURABLE_TRUE_TAG,
301
+ PATCH_RESOURCE_METADATA: () => PATCH_RESOURCE_METADATA,
298
302
  PERSON_EXISTS: () => PERSON_EXISTS,
299
303
  POWER_COMPATIBILITY_OPTIONS: () => POWER_COMPATIBILITY_OPTIONS,
300
304
  POWER_REQUIREMENT_THRESHOLDS_W: () => POWER_REQUIREMENT_THRESHOLDS_W,
301
305
  PRODUCT_CATEGORY_OPTIONS: () => PRODUCT_CATEGORY_OPTIONS,
302
306
  PROPOSE_CONTRIBUTION: () => PROPOSE_CONTRIBUTION,
307
+ PROPOSE_CONTRIBUTION_ATOMIC: () => PROPOSE_CONTRIBUTION_ATOMIC,
303
308
  QUERY_AGENTS: () => QUERY_AGENTS,
304
309
  QUERY_CITED_RESOURCES: () => QUERY_CITED_RESOURCES,
305
310
  QUERY_MACHINES: () => QUERY_MACHINES,
@@ -364,6 +369,7 @@ __export(index_exports, {
364
369
  signGraphQLRequest: () => signGraphQLRequest,
365
370
  slugifyTagValue: () => slugifyTagValue,
366
371
  stripUserTagPrefix: () => stripUserTagPrefix,
372
+ throwIfGraphQLErrors: () => throwIfGraphQLErrors,
367
373
  userTag: () => userTag
368
374
  });
369
375
  module.exports = __toCommonJS(index_exports);
@@ -449,12 +455,65 @@ function persistKeyring(keyring, store) {
449
455
  store.setItem(K.seed, keyring.seed);
450
456
  }
451
457
 
458
+ // src/graphql/errors.ts
459
+ var GraphQLRequestError = class extends Error {
460
+ graphQLErrors;
461
+ code;
462
+ httpStatus;
463
+ constructor(errors, context) {
464
+ super([context, errors[0]?.message || "GraphQL request failed"].filter(Boolean).join(": "));
465
+ Object.setPrototypeOf(this, new.target.prototype);
466
+ this.name = "GraphQLRequestError";
467
+ this.graphQLErrors = errors;
468
+ this.code = errors[0]?.extensions?.code || "GRAPHQL_ERROR";
469
+ this.httpStatus = errors[0]?.extensions?.httpStatus;
470
+ }
471
+ };
472
+ var GraphQLSigningError = class extends GraphQLRequestError {
473
+ constructor() {
474
+ super([{ message: "Unable to sign the request. Restore your session before trying again.", extensions: { code: "SIGNING_FAILED" } }]);
475
+ this.name = "GraphQLSigningError";
476
+ }
477
+ };
478
+ function throwIfGraphQLErrors(result, context) {
479
+ if (result.errors?.length) throw new GraphQLRequestError(result.errors, context);
480
+ }
481
+
452
482
  // src/graphql/gql.ts
453
483
  function gql(strings, ...values) {
454
484
  return strings.reduce((acc, str, i) => acc + str + (values[i] || ""), "");
455
485
  }
456
486
 
457
487
  // src/graphql/operations.ts
488
+ var PATCH_RESOURCE_METADATA = gql`
489
+ mutation PatchResourceMetadata($id: ID!, $fields: JSONObject!, $expectedMetadataHash: String) {
490
+ patchEconomicResourceMetadata(resourceId: $id, fields: $fields, expectedMetadataHash: $expectedMetadataHash) {
491
+ economicResource { id metadata metadataHash }
492
+ }
493
+ }
494
+ `;
495
+ var PROPOSE_CONTRIBUTION_ATOMIC = gql`
496
+ mutation ProposeContributionAtomic($fork: ID!, $origin: ID!, $name: String, $note: String) {
497
+ proposeContribution(resourceForkedId: $fork, resourceOriginId: $origin, name: $name, note: $note) {
498
+ proposal { id }
499
+ process { id }
500
+ citeIntent { id }
501
+ acceptIntent { id receiver { id } }
502
+ modifyIntent { id }
503
+ created
504
+ }
505
+ }
506
+ `;
507
+ var ACCEPT_CONTRIBUTION = gql`
508
+ mutation AcceptContribution($proposalId: ID!) {
509
+ acceptContribution(proposalId: $proposalId) {
510
+ proposal { id status }
511
+ citeEvent { id }
512
+ acceptEvent { id }
513
+ modifyEvent { id }
514
+ }
515
+ }
516
+ `;
458
517
  var QUERY_VARIABLES = gql`
459
518
  query GetVariables {
460
519
  instanceVariables {
@@ -1149,7 +1208,7 @@ var AuthClient = class {
1149
1208
  { firstRegistration, userData }
1150
1209
  );
1151
1210
  if (res.errors?.length) {
1152
- throw new Error(`HMAC request failed: ${res.errors[0].message}`);
1211
+ throw new GraphQLRequestError(res.errors, "HMAC request failed");
1153
1212
  }
1154
1213
  const hmac = res.data?.keypairoomServer;
1155
1214
  if (!hmac) throw new Error("HMAC not returned from server. Email may not exist.");
@@ -1191,7 +1250,7 @@ var AuthClient = class {
1191
1250
  this.config.zenflowsAdmin ? { "zenflows-admin": this.config.zenflowsAdmin } : void 0
1192
1251
  );
1193
1252
  if (res.errors?.length) {
1194
- throw new Error(`Registration failed: ${res.errors[0].message}`);
1253
+ throw new GraphQLRequestError(res.errors, "Registration failed");
1195
1254
  }
1196
1255
  const agent = res.data?.createPerson.agent;
1197
1256
  if (!agent) throw new Error("Registration failed: no agent returned.");
@@ -1207,6 +1266,7 @@ var AuthClient = class {
1207
1266
  */
1208
1267
  async verifyUser(email, eddsaPublicKey) {
1209
1268
  const res = await this.graphql.request(FETCH_SELF, { email, pubkey: eddsaPublicKey });
1269
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "User verification failed");
1210
1270
  const person = res.data?.personCheck;
1211
1271
  if (!person) return null;
1212
1272
  return {
@@ -1253,7 +1313,7 @@ var AuthClient = class {
1253
1313
  const template = this.detectTemplate();
1254
1314
  const res = await this.graphql.request(SEND_EMAIL_VERIFICATION, { template });
1255
1315
  if (res.errors?.length) {
1256
- throw new Error(`Email verification failed: ${res.errors[0].message}`);
1316
+ throw new GraphQLRequestError(res.errors, "Email verification failed");
1257
1317
  }
1258
1318
  }
1259
1319
  /**
@@ -1262,7 +1322,7 @@ var AuthClient = class {
1262
1322
  async claimDid(personId) {
1263
1323
  const res = await this.graphql.request(CLAIM_DID, { id: personId });
1264
1324
  if (res.errors?.length) {
1265
- throw new Error(`DID claim failed: ${res.errors[0].message}`);
1325
+ throw new GraphQLRequestError(res.errors, "DID claim failed");
1266
1326
  }
1267
1327
  return res.data?.claimPerson || "";
1268
1328
  }
@@ -1337,24 +1397,48 @@ var DppClient = class {
1337
1397
  if (json) headers["Content-Type"] = "application/json";
1338
1398
  return headers;
1339
1399
  }
1400
+ /**
1401
+ * Sign a body-less request (DELETE) by signing the object id string. The
1402
+ * DPP service reconstructs the signed bytes from the path id, so the
1403
+ * signature is bound to exactly this object (cross-service authz contract
1404
+ * §2). Returns DID headers plus x-user-id as a logged hint the server does
1405
+ * not trust for the principal.
1406
+ */
1407
+ async signedIdRequest(id) {
1408
+ const headers = { ...await signDidRequest(id, this.store) };
1409
+ const userId = this.store.getItem("authId");
1410
+ if (userId) headers["x-user-id"] = userId;
1411
+ return headers;
1412
+ }
1413
+ /** Throw a uniform error for a non-ok DPP response. */
1414
+ async ensureOk(res, method, path) {
1415
+ if (res.ok) return;
1416
+ let errMsg = res.statusText;
1417
+ try {
1418
+ const err = await res.json();
1419
+ errMsg = err.error || errMsg;
1420
+ } catch {
1421
+ }
1422
+ throw new Error(`DPP ${method} ${path} failed: ${errMsg}`);
1423
+ }
1340
1424
  /** Generic request helper. */
1341
1425
  async request(method, path, body) {
1342
1426
  const url = `${this.dppUrl}${path}`;
1343
1427
  const headers = await this.signedRequest(body);
1344
1428
  const jsonBody = body != null ? JSON.stringify(body) : void 0;
1345
1429
  const res = await fetch(url, { method, headers, body: jsonBody });
1346
- if (!res.ok) {
1347
- let errMsg = res.statusText;
1348
- try {
1349
- const err = await res.json();
1350
- errMsg = err.error || errMsg;
1351
- } catch {
1352
- }
1353
- throw new Error(`DPP ${method} ${path} failed: ${errMsg}`);
1354
- }
1430
+ await this.ensureOk(res, method, path);
1355
1431
  if (res.status === 204) return void 0;
1356
1432
  return res.json();
1357
1433
  }
1434
+ /** DELETE a body-less resource, signing the given object id. */
1435
+ async deleteSigned(path, signId) {
1436
+ const res = await fetch(`${this.dppUrl}${path}`, {
1437
+ method: "DELETE",
1438
+ headers: await this.signedIdRequest(signId)
1439
+ });
1440
+ await this.ensureOk(res, "DELETE", path);
1441
+ }
1358
1442
  // ─── CRUD ──────────────────────────────────────────────────────────
1359
1443
  async createDpp(data) {
1360
1444
  return this.request("POST", "/dpp", data);
@@ -1366,7 +1450,7 @@ var DppClient = class {
1366
1450
  return this.request("PUT", `/dpp/${encodeURIComponent(id)}`, data);
1367
1451
  }
1368
1452
  async deleteDpp(id) {
1369
- return this.request("DELETE", `/dpp/${encodeURIComponent(id)}`);
1453
+ return this.deleteSigned(`/dpp/${encodeURIComponent(id)}`, id);
1370
1454
  }
1371
1455
  // ─── List / Query ──────────────────────────────────────────────────
1372
1456
  async listDpps(filters) {
@@ -1419,9 +1503,9 @@ var DppClient = class {
1419
1503
  return res.json();
1420
1504
  }
1421
1505
  async deleteAttachment(dppId, attachmentId) {
1422
- return this.request(
1423
- "DELETE",
1424
- `/dpp/${encodeURIComponent(dppId)}/attachments/${encodeURIComponent(attachmentId)}`
1506
+ return this.deleteSigned(
1507
+ `/dpp/${encodeURIComponent(dppId)}/attachments/${encodeURIComponent(attachmentId)}`,
1508
+ dppId
1425
1509
  );
1426
1510
  }
1427
1511
  /** Get the file download URL for an attachment. */
@@ -1644,25 +1728,57 @@ var GraphQLClient = class {
1644
1728
  try {
1645
1729
  const signed = await signGraphQLRequest(body, this.store);
1646
1730
  Object.assign(headers, signed);
1647
- } catch (err) {
1648
- console.warn("[interfacer-client] GraphQL signing failed:", err);
1731
+ } catch {
1732
+ throw new GraphQLSigningError();
1649
1733
  }
1650
1734
  }
1651
1735
  const url = this.config.zenflowsUrl;
1652
1736
  if (!url) throw new Error("zenflowsUrl not configured. Provide zenflowsUrl or proxyUrl in config.");
1653
- const res = await fetch(url, {
1654
- method: "POST",
1655
- headers,
1656
- body
1657
- });
1737
+ let res;
1738
+ try {
1739
+ res = await fetch(url, { method: "POST", headers, body });
1740
+ } catch {
1741
+ throw new GraphQLRequestError([{
1742
+ message: "Unable to reach the service. Check the operation's status before retrying.",
1743
+ extensions: { code: "NETWORK_ERROR" }
1744
+ }]);
1745
+ }
1658
1746
  if (!res.ok) {
1659
- return {
1660
- errors: [{ message: `HTTP ${res.status}: ${res.statusText}` }]
1747
+ const codes = {
1748
+ 401: "UNAUTHENTICATED",
1749
+ 403: "FORBIDDEN",
1750
+ 409: "CONFLICT",
1751
+ 429: "RATE_LIMITED",
1752
+ 503: "SERVICE_UNAVAILABLE"
1661
1753
  };
1754
+ return { errors: [{
1755
+ message: `HTTP ${res.status}`,
1756
+ extensions: { code: codes[res.status] || "HTTP_ERROR", httpStatus: res.status }
1757
+ }] };
1662
1758
  }
1663
- return res.json();
1759
+ let result;
1760
+ try {
1761
+ result = await res.json();
1762
+ } catch {
1763
+ throw invalidResponse();
1764
+ }
1765
+ if (!isGraphQLResult(result)) throw invalidResponse();
1766
+ return result;
1664
1767
  }
1665
1768
  };
1769
+ function invalidResponse() {
1770
+ return new GraphQLRequestError([{
1771
+ message: "The service returned an invalid response. Check the operation's status before retrying.",
1772
+ extensions: { code: "INVALID_RESPONSE" }
1773
+ }]);
1774
+ }
1775
+ function isGraphQLResult(value) {
1776
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1777
+ const result = value;
1778
+ if (result.data != null && (typeof result.data !== "object" || Array.isArray(result.data))) return false;
1779
+ if (result.errors !== void 0 && (!Array.isArray(result.errors) || result.errors.some((error) => !error || typeof error !== "object" || typeof error.message !== "string"))) return false;
1780
+ return Object.hasOwn(result, "data") || Array.isArray(result.errors) && result.errors.length > 0;
1781
+ }
1666
1782
  function extractOperationName(operation) {
1667
1783
  const match = operation.match(/(?:query|mutation)\s+(\w+)/);
1668
1784
  return match ? match[1] : null;
@@ -1865,7 +1981,7 @@ async function getInstanceVariables(client) {
1865
1981
  if (cachedVars) return cachedVars;
1866
1982
  const res = await client.request(QUERY_INSTANCE_VARIABLES);
1867
1983
  if (res.errors?.length) {
1868
- throw new Error(`Failed to fetch instance variables: ${res.errors[0].message}`);
1984
+ throw new GraphQLRequestError(res.errors, "Failed to fetch instance variables");
1869
1985
  }
1870
1986
  const d = res.data?.instanceVariables;
1871
1987
  if (!d) throw new Error("No instance variables returned.");
@@ -2167,6 +2283,19 @@ var TaggingClient = class {
2167
2283
  };
2168
2284
 
2169
2285
  // src/resources/ResourceClient.ts
2286
+ function isMetadataMap(value) {
2287
+ return value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
2288
+ }
2289
+ function metadataError(code) {
2290
+ return new GraphQLRequestError([{ message: code === "BAD_USER_INPUT" ? "Invalid metadata fields or precondition." : "Invalid metadata patch response.", extensions: { code } }]);
2291
+ }
2292
+ function contributionError(code) {
2293
+ return new GraphQLRequestError([{ message: code === "BAD_USER_INPUT" ? "Invalid proposal id." : "Invalid acceptContribution response.", extensions: { code } }]);
2294
+ }
2295
+ function eventId(value) {
2296
+ const id = isMetadataMap(value) ? value.id : void 0;
2297
+ return typeof id === "string" && id ? id : void 0;
2298
+ }
2170
2299
  var ResourceClient = class {
2171
2300
  constructor(config, store, graphql) {
2172
2301
  this.config = config;
@@ -2205,7 +2334,7 @@ var ResourceClient = class {
2205
2334
  CREATE_PROCESS,
2206
2335
  { name }
2207
2336
  );
2208
- if (res.errors?.length) throw new Error(`createProcess failed: ${res.errors[0].message}`);
2337
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createProcess failed");
2209
2338
  return res.data.createProcess.process.id;
2210
2339
  }
2211
2340
  // ─── Location ──────────────────────────────────────────────────────
@@ -2216,7 +2345,7 @@ var ResourceClient = class {
2216
2345
  lat: params.lat || 0,
2217
2346
  lng: params.lng || 0
2218
2347
  });
2219
- if (res.errors?.length) throw new Error(`createLocation failed: ${res.errors[0].message}`);
2348
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createLocation failed");
2220
2349
  return res.data.createSpatialThing.spatialThing;
2221
2350
  }
2222
2351
  // ─── Create Project (Design, Product, Service) ─────────────────────
@@ -2248,7 +2377,7 @@ var ResourceClient = class {
2248
2377
  variables.tags = params.tags;
2249
2378
  }
2250
2379
  const res = await this.graphql.request(CREATE_PROJECT, variables);
2251
- if (res.errors?.length) throw new Error(`createProject failed: ${res.errors[0].message}`);
2380
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createProject failed");
2252
2381
  return res.data.createEconomicEvent.economicEvent.resourceInventoriedAs;
2253
2382
  }
2254
2383
  // ─── Create Machine ────────────────────────────────────────────────
@@ -2280,7 +2409,7 @@ var ResourceClient = class {
2280
2409
  };
2281
2410
  if (tags.length > 0) variables.tags = tags;
2282
2411
  const res = await this.graphql.request(CREATE_MACHINE_RESOURCE, variables);
2283
- if (res.errors?.length) throw new Error(`createMachine failed: ${res.errors[0].message}`);
2412
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createMachine failed");
2284
2413
  return res.data.createEconomicEvent.economicEvent.resourceInventoriedAs;
2285
2414
  }
2286
2415
  // ─── Create DPP Resource ───────────────────────────────────────────
@@ -2299,7 +2428,7 @@ var ResourceClient = class {
2299
2428
  name: params.name,
2300
2429
  note: params.note || ""
2301
2430
  });
2302
- if (res.errors?.length) throw new Error(`createDppResource failed: ${res.errors[0].message}`);
2431
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createDppResource failed");
2303
2432
  return res.data.createEconomicEvent.economicEvent.resourceInventoriedAs;
2304
2433
  }
2305
2434
  // ─── Queries ───────────────────────────────────────────────────────
@@ -2308,6 +2437,7 @@ var ResourceClient = class {
2308
2437
  QUERY_RESOURCE,
2309
2438
  { id }
2310
2439
  );
2440
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "getResource failed");
2311
2441
  return res.data?.economicResource ?? null;
2312
2442
  }
2313
2443
  async listResources(filter, pagination) {
@@ -2315,6 +2445,7 @@ var ResourceClient = class {
2315
2445
  ...pagination,
2316
2446
  filter: filter || {}
2317
2447
  });
2448
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "listResources failed");
2318
2449
  return res.data || {};
2319
2450
  }
2320
2451
  async getProjects(filter, pagination) {
@@ -2322,6 +2453,7 @@ var ResourceClient = class {
2322
2453
  ...pagination,
2323
2454
  filter: filter || {}
2324
2455
  });
2456
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "getProjects failed");
2325
2457
  return res.data || {};
2326
2458
  }
2327
2459
  async getMachines() {
@@ -2331,6 +2463,7 @@ var ResourceClient = class {
2331
2463
  const res = await this.graphql.request(QUERY_MACHINES, {
2332
2464
  resourceSpecId: machineSpecId
2333
2465
  });
2466
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "getMachines failed");
2334
2467
  return res.data || {};
2335
2468
  }
2336
2469
  // ─── Relations ─────────────────────────────────────────────────────
@@ -2343,7 +2476,7 @@ var ResourceClient = class {
2343
2476
  process: processId,
2344
2477
  unitOne: vars.unitOne
2345
2478
  });
2346
- if (res.errors?.length) throw new Error(`citeResource failed: ${res.errors[0].message}`);
2479
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "citeResource failed");
2347
2480
  }
2348
2481
  async consumeResource(resourceId, processId) {
2349
2482
  const vars = await this.getInstanceVars();
@@ -2354,7 +2487,7 @@ var ResourceClient = class {
2354
2487
  process: processId,
2355
2488
  unitOne: vars.unitOne
2356
2489
  });
2357
- if (res.errors?.length) throw new Error(`consumeResource failed: ${res.errors[0].message}`);
2490
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "consumeResource failed");
2358
2491
  }
2359
2492
  async contributeToResource(processId, contributionTypeSpecId) {
2360
2493
  const vars = await this.getInstanceVars();
@@ -2365,9 +2498,41 @@ var ResourceClient = class {
2365
2498
  unitOne: vars.unitOne,
2366
2499
  conformsTo: contributionTypeSpecId
2367
2500
  });
2368
- if (res.errors?.length) throw new Error(`contribute failed: ${res.errors[0].message}`);
2501
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "contribute failed");
2369
2502
  }
2370
2503
  // ─── Metadata ──────────────────────────────────────────────────────
2504
+ /**
2505
+ * One signed metadata-only mutation: shallow field replacement under the
2506
+ * backend row lock, with optional content CAS. No processes/economic events,
2507
+ * quantity changes, preflight or retry. Arrays/nested objects replace a field;
2508
+ * null is a value, not deletion. Without CAS, overlapping fields are last-write-wins.
2509
+ * The token detects differing current content, not ABA or every historical revision.
2510
+ */
2511
+ async patchMetadata(resourceId, fields, options = {}) {
2512
+ if (typeof resourceId !== "string" || !resourceId.trim() || !isMetadataMap(fields) || !isMetadataMap(options)) throw metadataError("BAD_USER_INPUT");
2513
+ const hasExpected = Object.prototype.hasOwnProperty.call(options, "expectedMetadataHash");
2514
+ if (hasExpected && (typeof options.expectedMetadataHash !== "string" || !/^[0-9a-f]{64}$/.test(options.expectedMetadataHash))) throw metadataError("BAD_USER_INPUT");
2515
+ let serialized;
2516
+ try {
2517
+ serialized = JSON.stringify(fields, (_key, value) => {
2518
+ if (value === void 0 || ["function", "symbol", "bigint"].includes(typeof value) || typeof value === "number" && !Number.isFinite(value)) throw metadataError("BAD_USER_INPUT");
2519
+ return value;
2520
+ });
2521
+ if (!isMetadataMap(JSON.parse(serialized))) throw metadataError("BAD_USER_INPUT");
2522
+ } catch {
2523
+ throw metadataError("BAD_USER_INPUT");
2524
+ }
2525
+ const result = await this.graphql.request(PATCH_RESOURCE_METADATA, {
2526
+ id: resourceId,
2527
+ fields: serialized,
2528
+ ...hasExpected ? { expectedMetadataHash: options.expectedMetadataHash } : {}
2529
+ });
2530
+ if (result.errors?.length) throw new GraphQLRequestError(result.errors, "patchMetadata failed");
2531
+ const resource = result.data?.patchEconomicResourceMetadata?.economicResource;
2532
+ if (!resource || resource.id !== resourceId || resource.metadata !== null && !isMetadataMap(resource.metadata) || typeof resource.metadataHash !== "string" || !/^[0-9a-f]{64}$/.test(resource.metadataHash)) throw metadataError("INVALID_RESPONSE");
2533
+ return resource;
2534
+ }
2535
+ /** Legacy full replacement through economic events; not an atomic field patch. */
2371
2536
  async updateMetadata(resourceId, metadata, quantity) {
2372
2537
  const res = await this.graphql.request(UPDATE_METADATA, {
2373
2538
  process: await this.createProcess(`metadata update`),
@@ -2377,14 +2542,14 @@ var ResourceClient = class {
2377
2542
  now: (/* @__PURE__ */ new Date()).toISOString(),
2378
2543
  metadata: JSON.stringify(metadata)
2379
2544
  });
2380
- if (res.errors?.length) throw new Error(`updateMetadata failed: ${res.errors[0].message}`);
2545
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "updateMetadata failed");
2381
2546
  }
2382
2547
  async updateClassifiedAs(resourceId, tags) {
2383
2548
  const res = await this.graphql.request(UPDATE_RESOURCE_CLASSIFIED_AS, {
2384
2549
  id: resourceId,
2385
2550
  classifiedAs: tags
2386
2551
  });
2387
- if (res.errors?.length) throw new Error(`updateClassifiedAs failed: ${res.errors[0].message}`);
2552
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "updateClassifiedAs failed");
2388
2553
  }
2389
2554
  async relocateResource(resourceId, locationId) {
2390
2555
  const vars = await this.getInstanceVars();
@@ -2396,9 +2561,41 @@ var ResourceClient = class {
2396
2561
  now: (/* @__PURE__ */ new Date()).toISOString(),
2397
2562
  location: locationId
2398
2563
  });
2399
- if (res.errors?.length) throw new Error(`relocate failed: ${res.errors[0].message}`);
2564
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "relocate failed");
2400
2565
  }
2401
2566
  // ─── Proposals ─────────────────────────────────────────────────────
2567
+ /**
2568
+ * Create a contribution proposal with one signed mutation; the server writes
2569
+ * the process, intents, proposal and links in one transaction, names the
2570
+ * origin's controller as owner and returns an existing pending proposal for
2571
+ * the same fork and origin (created: false). Never retried by the SDK.
2572
+ * Requires zenflows#77.
2573
+ */
2574
+ async createContributionProposal(params) {
2575
+ const ok = (v) => typeof v === "string" && v.trim().length > 0;
2576
+ const optional = (v) => v === void 0 || typeof v === "string";
2577
+ if (!isMetadataMap(params) || !ok(params.resourceForkedId) || !ok(params.resourceOriginId) || params.resourceForkedId === params.resourceOriginId || !optional(params.name) || !optional(params.note)) {
2578
+ throw new GraphQLRequestError([{ message: "Invalid contribution proposal.", extensions: { code: "BAD_USER_INPUT" } }]);
2579
+ }
2580
+ const variables = { fork: params.resourceForkedId, origin: params.resourceOriginId };
2581
+ if (params.name !== void 0) variables.name = params.name;
2582
+ if (params.note !== void 0) variables.note = params.note;
2583
+ const result = await this.graphql.request(PROPOSE_CONTRIBUTION_ATOMIC, variables);
2584
+ if (result.errors?.length) throw new GraphQLRequestError(result.errors, "createContributionProposal failed");
2585
+ const p = result.data?.proposeContribution;
2586
+ const id = (key) => isMetadataMap(p) ? eventId(p[key]) : void 0;
2587
+ const [proposalId, processId, citeIntentId, acceptIntentId, modifyIntentId] = ["proposal", "process", "citeIntent", "acceptIntent", "modifyIntent"].map(id);
2588
+ const ownerId = isMetadataMap(p) && isMetadataMap(p.acceptIntent) ? eventId(p.acceptIntent.receiver) : void 0;
2589
+ if (!isMetadataMap(p) || typeof p.created !== "boolean" || !proposalId || !processId || !citeIntentId || !acceptIntentId || !modifyIntentId || !ownerId) {
2590
+ throw new GraphQLRequestError([{ message: "Invalid proposeContribution response.", extensions: { code: "INVALID_RESPONSE" } }]);
2591
+ }
2592
+ return { proposalId, processId, citeIntentId, acceptIntentId, modifyIntentId, ownerId, created: p.created };
2593
+ }
2594
+ /**
2595
+ * @deprecated Four non-transactional requests that name a caller-supplied
2596
+ * owner: a failure leaves orphans and a retry duplicates. Use
2597
+ * createContributionProposal.
2598
+ */
2402
2599
  async proposeContribution(params) {
2403
2600
  const vars = await this.getInstanceVars();
2404
2601
  const processId = await this.createProcess("contribution proposal");
@@ -2412,12 +2609,12 @@ var ResourceClient = class {
2412
2609
  unitOne: vars.unitOne,
2413
2610
  resourceOrigin: params.resourceOriginId
2414
2611
  });
2415
- if (intentsRes.errors?.length) throw new Error(`proposeContribution intents failed: ${intentsRes.errors[0].message}`);
2612
+ if (intentsRes.errors?.length) throw new GraphQLRequestError(intentsRes.errors, "proposeContribution intents failed");
2416
2613
  const proposalRes = await this.graphql.request(CREATE_PROPOSAL, {
2417
2614
  name: `Contribution to resource`,
2418
2615
  note: params.note
2419
2616
  });
2420
- if (proposalRes.errors?.length) throw new Error(`createProposal failed: ${proposalRes.errors[0].message}`);
2617
+ if (proposalRes.errors?.length) throw new GraphQLRequestError(proposalRes.errors, "createProposal failed");
2421
2618
  const proposalId = proposalRes.data.createProposal.proposal.id;
2422
2619
  const citeIntentId = intentsRes.data.citeResourceForked.intent.id;
2423
2620
  const acceptIntentId = intentsRes.data.acceptResourceOrigin.intent.id;
@@ -2428,9 +2625,34 @@ var ResourceClient = class {
2428
2625
  acceptIntent: acceptIntentId,
2429
2626
  modifyIntent: modifyIntentId
2430
2627
  });
2431
- if (linkRes.errors?.length) throw new Error(`linkIntents failed: ${linkRes.errors[0].message}`);
2628
+ if (linkRes.errors?.length) throw new GraphQLRequestError(linkRes.errors, "linkIntents failed");
2432
2629
  return { proposalId, citeIntentId, acceptIntentId, modifyIntentId };
2433
2630
  }
2631
+ /**
2632
+ * Accept a contribution proposal with one signed mutation: the backend writes
2633
+ * the events, satisfactions and the origin's new relation in one transaction.
2634
+ * Accepting an accepted proposal returns the same events, so a caller may
2635
+ * retry after an uncertain outcome; the SDK itself never retries. A rejected
2636
+ * or half-accepted proposal fails with CONFLICT. Requires zenflows#76.
2637
+ */
2638
+ async acceptContribution(proposalId) {
2639
+ if (typeof proposalId !== "string" || !proposalId.trim()) throw contributionError("BAD_USER_INPUT");
2640
+ const result = await this.graphql.request(ACCEPT_CONTRIBUTION, { proposalId });
2641
+ if (result.errors?.length) throw new GraphQLRequestError(result.errors, "acceptContribution failed");
2642
+ const payload = result.data?.acceptContribution;
2643
+ const proposal = isMetadataMap(payload) && isMetadataMap(payload.proposal) ? payload.proposal : void 0;
2644
+ const citeEventId = isMetadataMap(payload) ? eventId(payload.citeEvent) : void 0;
2645
+ const acceptEventId = isMetadataMap(payload) ? eventId(payload.acceptEvent) : void 0;
2646
+ const modifyEventId = isMetadataMap(payload) ? eventId(payload.modifyEvent) : void 0;
2647
+ if (!proposal || proposal.id !== proposalId || proposal.status !== "ACCEPTED" || !citeEventId || !acceptEventId || !modifyEventId) {
2648
+ throw contributionError("INVALID_RESPONSE");
2649
+ }
2650
+ return { proposalId, status: "ACCEPTED", citeEventId, acceptEventId, modifyEventId };
2651
+ }
2652
+ /**
2653
+ * @deprecated Two non-transactional requests: a failure between them leaves
2654
+ * committed events and a retry duplicates them. Use acceptContribution.
2655
+ */
2434
2656
  async acceptProposal(params) {
2435
2657
  const vars = await this.getInstanceVars();
2436
2658
  const processId = await this.createProcess("accept contribution");
@@ -2444,7 +2666,7 @@ var ResourceClient = class {
2444
2666
  creationTime: (/* @__PURE__ */ new Date()).toISOString(),
2445
2667
  metadata: JSON.stringify(params.newMetadata)
2446
2668
  });
2447
- if (eventsRes.errors?.length) throw new Error(`acceptProposal events failed: ${eventsRes.errors[0].message}`);
2669
+ if (eventsRes.errors?.length) throw new GraphQLRequestError(eventsRes.errors, "acceptProposal events failed");
2448
2670
  const satRes = await this.graphql.request(SATISFY_INTENTS, {
2449
2671
  unitOne: vars.unitOne,
2450
2672
  intentCited: params.citeIntentId,
@@ -2454,11 +2676,11 @@ var ResourceClient = class {
2454
2676
  eventAccept: eventsRes.data.accept.economicEvent.id,
2455
2677
  eventModify: eventsRes.data.modify.economicEvent.id
2456
2678
  });
2457
- if (satRes.errors?.length) throw new Error(`satisfyIntents failed: ${satRes.errors[0].message}`);
2679
+ if (satRes.errors?.length) throw new GraphQLRequestError(satRes.errors, "satisfyIntents failed");
2458
2680
  }
2459
2681
  async getTraceDpp(id) {
2460
2682
  const res = await this.graphql.request(QUERY_RESOURCE_TRACE_DPP, { id });
2461
- if (res.errors?.length) throw new Error(`getTraceDpp failed: ${res.errors[0].message}`);
2683
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "getTraceDpp failed");
2462
2684
  const traceDpp = res.data?.economicResource?.traceDpp;
2463
2685
  return Array.isArray(traceDpp) ? traceDpp : [];
2464
2686
  }
@@ -2468,7 +2690,7 @@ var ResourceClient = class {
2468
2690
  intentAccept,
2469
2691
  intentModify
2470
2692
  });
2471
- if (res.errors?.length) throw new Error(`rejectProposal failed: ${res.errors[0].message}`);
2693
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "rejectProposal failed");
2472
2694
  }
2473
2695
  };
2474
2696
 
@@ -2606,6 +2828,28 @@ var WalletClient = class {
2606
2828
  });
2607
2829
  if (!res.ok) throw new Error(`Wallet addPoints failed: ${res.statusText}`);
2608
2830
  }
2831
+ /**
2832
+ * Issue points for a ValueFlows/social event. Unlike addPoints, the caller
2833
+ * does NOT choose the recipient or amount: it names the event that justifies
2834
+ * the issuance, and the server (Zenflows PDP) attests it and derives the
2835
+ * recipients and server-authoritative amounts. Phase 1 supports `accept`.
2836
+ */
2837
+ async issueForEvent(event) {
2838
+ const walletUrl = this.config.walletUrl;
2839
+ if (!walletUrl) throw new Error("walletUrl not configured");
2840
+ const body = JSON.stringify({ event });
2841
+ const headers = await signDidRequest(body, this.store);
2842
+ const res = await fetch(walletUrl, {
2843
+ method: "POST",
2844
+ headers: { ...headers, "Content-Type": "application/json" },
2845
+ body
2846
+ });
2847
+ if (!res.ok) throw new Error(`Wallet issueForEvent failed: ${res.statusText}`);
2848
+ const data = await res.json();
2849
+ if (data?.success !== true) {
2850
+ throw new Error(`Wallet issue denied: ${data?.reason ?? "unknown"}`);
2851
+ }
2852
+ }
2609
2853
  /** Get point trend over a period (change since period start). */
2610
2854
  async getTrend(agentId, token, periodStartMs) {
2611
2855
  const periodStartBalance = await this.getBalanceAt(agentId, token, periodStartMs);
@@ -2746,6 +2990,7 @@ function createConfig(config) {
2746
2990
  init_sign();
2747
2991
  // Annotate the CommonJS export names for ESM import in node:
2748
2992
  0 && (module.exports = {
2993
+ ACCEPT_CONTRIBUTION,
2749
2994
  ACCEPT_PROPOSAL,
2750
2995
  ASK_RESOURCE_PRIMARY_ACCOUNTABLE,
2751
2996
  AVAILABILITY_OPTIONS,
@@ -2781,17 +3026,21 @@ init_sign();
2781
3026
  GET_USER_IMAGES,
2782
3027
  GET_USER_LAYOUT,
2783
3028
  GraphQLClient,
3029
+ GraphQLRequestError,
3030
+ GraphQLSigningError,
2784
3031
  ImportClient,
2785
3032
  InboxClient,
2786
3033
  InterfacerClient,
2787
3034
  LINK_CONTRIBUTION_PROPOSAL_INTENT,
2788
3035
  LINK_PROPOSAL_AND_INTENT,
2789
3036
  MANUFACTURABLE_TRUE_TAG,
3037
+ PATCH_RESOURCE_METADATA,
2790
3038
  PERSON_EXISTS,
2791
3039
  POWER_COMPATIBILITY_OPTIONS,
2792
3040
  POWER_REQUIREMENT_THRESHOLDS_W,
2793
3041
  PRODUCT_CATEGORY_OPTIONS,
2794
3042
  PROPOSE_CONTRIBUTION,
3043
+ PROPOSE_CONTRIBUTION_ATOMIC,
2795
3044
  QUERY_AGENTS,
2796
3045
  QUERY_CITED_RESOURCES,
2797
3046
  QUERY_MACHINES,
@@ -2856,6 +3105,7 @@ init_sign();
2856
3105
  signGraphQLRequest,
2857
3106
  slugifyTagValue,
2858
3107
  stripUserTagPrefix,
3108
+ throwIfGraphQLErrors,
2859
3109
  userTag
2860
3110
  });
2861
3111
  //# sourceMappingURL=index.cjs.map