@dyne/interfacer-client 0.6.0 → 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.js CHANGED
@@ -310,12 +310,65 @@ function persistKeyring(keyring, store) {
310
310
  store.setItem(K.seed, keyring.seed);
311
311
  }
312
312
 
313
+ // src/graphql/errors.ts
314
+ var GraphQLRequestError = class extends Error {
315
+ graphQLErrors;
316
+ code;
317
+ httpStatus;
318
+ constructor(errors, context) {
319
+ super([context, errors[0]?.message || "GraphQL request failed"].filter(Boolean).join(": "));
320
+ Object.setPrototypeOf(this, new.target.prototype);
321
+ this.name = "GraphQLRequestError";
322
+ this.graphQLErrors = errors;
323
+ this.code = errors[0]?.extensions?.code || "GRAPHQL_ERROR";
324
+ this.httpStatus = errors[0]?.extensions?.httpStatus;
325
+ }
326
+ };
327
+ var GraphQLSigningError = class extends GraphQLRequestError {
328
+ constructor() {
329
+ super([{ message: "Unable to sign the request. Restore your session before trying again.", extensions: { code: "SIGNING_FAILED" } }]);
330
+ this.name = "GraphQLSigningError";
331
+ }
332
+ };
333
+ function throwIfGraphQLErrors(result, context) {
334
+ if (result.errors?.length) throw new GraphQLRequestError(result.errors, context);
335
+ }
336
+
313
337
  // src/graphql/gql.ts
314
338
  function gql(strings, ...values) {
315
339
  return strings.reduce((acc, str, i) => acc + str + (values[i] || ""), "");
316
340
  }
317
341
 
318
342
  // src/graphql/operations.ts
343
+ var PATCH_RESOURCE_METADATA = gql`
344
+ mutation PatchResourceMetadata($id: ID!, $fields: JSONObject!, $expectedMetadataHash: String) {
345
+ patchEconomicResourceMetadata(resourceId: $id, fields: $fields, expectedMetadataHash: $expectedMetadataHash) {
346
+ economicResource { id metadata metadataHash }
347
+ }
348
+ }
349
+ `;
350
+ var PROPOSE_CONTRIBUTION_ATOMIC = gql`
351
+ mutation ProposeContributionAtomic($fork: ID!, $origin: ID!, $name: String, $note: String) {
352
+ proposeContribution(resourceForkedId: $fork, resourceOriginId: $origin, name: $name, note: $note) {
353
+ proposal { id }
354
+ process { id }
355
+ citeIntent { id }
356
+ acceptIntent { id receiver { id } }
357
+ modifyIntent { id }
358
+ created
359
+ }
360
+ }
361
+ `;
362
+ var ACCEPT_CONTRIBUTION = gql`
363
+ mutation AcceptContribution($proposalId: ID!) {
364
+ acceptContribution(proposalId: $proposalId) {
365
+ proposal { id status }
366
+ citeEvent { id }
367
+ acceptEvent { id }
368
+ modifyEvent { id }
369
+ }
370
+ }
371
+ `;
319
372
  var QUERY_VARIABLES = gql`
320
373
  query GetVariables {
321
374
  instanceVariables {
@@ -421,7 +474,7 @@ var FETCH_RESOURCES = gql`
421
474
  $filter: EconomicResourceFilterParams
422
475
  ) {
423
476
  economicResources(first: $first after: $after before: $before last: $last filter: $filter) {
424
- pageInfo { startCursor endCursor hasPreviousPage hasNextPage totalCount pageLimit }
477
+ pageInfo { startCursor endCursor hasPreviousPage hasNextPage totalCount pageLimit distinctPrimaryAccountableCount }
425
478
  edges {
426
479
  cursor
427
480
  node {
@@ -1010,7 +1063,7 @@ var AuthClient = class {
1010
1063
  { firstRegistration, userData }
1011
1064
  );
1012
1065
  if (res.errors?.length) {
1013
- throw new Error(`HMAC request failed: ${res.errors[0].message}`);
1066
+ throw new GraphQLRequestError(res.errors, "HMAC request failed");
1014
1067
  }
1015
1068
  const hmac = res.data?.keypairoomServer;
1016
1069
  if (!hmac) throw new Error("HMAC not returned from server. Email may not exist.");
@@ -1052,7 +1105,7 @@ var AuthClient = class {
1052
1105
  this.config.zenflowsAdmin ? { "zenflows-admin": this.config.zenflowsAdmin } : void 0
1053
1106
  );
1054
1107
  if (res.errors?.length) {
1055
- throw new Error(`Registration failed: ${res.errors[0].message}`);
1108
+ throw new GraphQLRequestError(res.errors, "Registration failed");
1056
1109
  }
1057
1110
  const agent = res.data?.createPerson.agent;
1058
1111
  if (!agent) throw new Error("Registration failed: no agent returned.");
@@ -1068,6 +1121,7 @@ var AuthClient = class {
1068
1121
  */
1069
1122
  async verifyUser(email, eddsaPublicKey) {
1070
1123
  const res = await this.graphql.request(FETCH_SELF, { email, pubkey: eddsaPublicKey });
1124
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "User verification failed");
1071
1125
  const person = res.data?.personCheck;
1072
1126
  if (!person) return null;
1073
1127
  return {
@@ -1114,7 +1168,7 @@ var AuthClient = class {
1114
1168
  const template = this.detectTemplate();
1115
1169
  const res = await this.graphql.request(SEND_EMAIL_VERIFICATION, { template });
1116
1170
  if (res.errors?.length) {
1117
- throw new Error(`Email verification failed: ${res.errors[0].message}`);
1171
+ throw new GraphQLRequestError(res.errors, "Email verification failed");
1118
1172
  }
1119
1173
  }
1120
1174
  /**
@@ -1123,7 +1177,7 @@ var AuthClient = class {
1123
1177
  async claimDid(personId) {
1124
1178
  const res = await this.graphql.request(CLAIM_DID, { id: personId });
1125
1179
  if (res.errors?.length) {
1126
- throw new Error(`DID claim failed: ${res.errors[0].message}`);
1180
+ throw new GraphQLRequestError(res.errors, "DID claim failed");
1127
1181
  }
1128
1182
  return res.data?.claimPerson || "";
1129
1183
  }
@@ -1198,24 +1252,48 @@ var DppClient = class {
1198
1252
  if (json) headers["Content-Type"] = "application/json";
1199
1253
  return headers;
1200
1254
  }
1255
+ /**
1256
+ * Sign a body-less request (DELETE) by signing the object id string. The
1257
+ * DPP service reconstructs the signed bytes from the path id, so the
1258
+ * signature is bound to exactly this object (cross-service authz contract
1259
+ * §2). Returns DID headers plus x-user-id as a logged hint the server does
1260
+ * not trust for the principal.
1261
+ */
1262
+ async signedIdRequest(id) {
1263
+ const headers = { ...await signDidRequest(id, this.store) };
1264
+ const userId = this.store.getItem("authId");
1265
+ if (userId) headers["x-user-id"] = userId;
1266
+ return headers;
1267
+ }
1268
+ /** Throw a uniform error for a non-ok DPP response. */
1269
+ async ensureOk(res, method, path) {
1270
+ if (res.ok) return;
1271
+ let errMsg = res.statusText;
1272
+ try {
1273
+ const err = await res.json();
1274
+ errMsg = err.error || errMsg;
1275
+ } catch {
1276
+ }
1277
+ throw new Error(`DPP ${method} ${path} failed: ${errMsg}`);
1278
+ }
1201
1279
  /** Generic request helper. */
1202
1280
  async request(method, path, body) {
1203
1281
  const url = `${this.dppUrl}${path}`;
1204
1282
  const headers = await this.signedRequest(body);
1205
1283
  const jsonBody = body != null ? JSON.stringify(body) : void 0;
1206
1284
  const res = await fetch(url, { method, headers, body: jsonBody });
1207
- if (!res.ok) {
1208
- let errMsg = res.statusText;
1209
- try {
1210
- const err = await res.json();
1211
- errMsg = err.error || errMsg;
1212
- } catch {
1213
- }
1214
- throw new Error(`DPP ${method} ${path} failed: ${errMsg}`);
1215
- }
1285
+ await this.ensureOk(res, method, path);
1216
1286
  if (res.status === 204) return void 0;
1217
1287
  return res.json();
1218
1288
  }
1289
+ /** DELETE a body-less resource, signing the given object id. */
1290
+ async deleteSigned(path, signId) {
1291
+ const res = await fetch(`${this.dppUrl}${path}`, {
1292
+ method: "DELETE",
1293
+ headers: await this.signedIdRequest(signId)
1294
+ });
1295
+ await this.ensureOk(res, "DELETE", path);
1296
+ }
1219
1297
  // ─── CRUD ──────────────────────────────────────────────────────────
1220
1298
  async createDpp(data) {
1221
1299
  return this.request("POST", "/dpp", data);
@@ -1227,7 +1305,7 @@ var DppClient = class {
1227
1305
  return this.request("PUT", `/dpp/${encodeURIComponent(id)}`, data);
1228
1306
  }
1229
1307
  async deleteDpp(id) {
1230
- return this.request("DELETE", `/dpp/${encodeURIComponent(id)}`);
1308
+ return this.deleteSigned(`/dpp/${encodeURIComponent(id)}`, id);
1231
1309
  }
1232
1310
  // ─── List / Query ──────────────────────────────────────────────────
1233
1311
  async listDpps(filters) {
@@ -1280,9 +1358,9 @@ var DppClient = class {
1280
1358
  return res.json();
1281
1359
  }
1282
1360
  async deleteAttachment(dppId, attachmentId) {
1283
- return this.request(
1284
- "DELETE",
1285
- `/dpp/${encodeURIComponent(dppId)}/attachments/${encodeURIComponent(attachmentId)}`
1361
+ return this.deleteSigned(
1362
+ `/dpp/${encodeURIComponent(dppId)}/attachments/${encodeURIComponent(attachmentId)}`,
1363
+ dppId
1286
1364
  );
1287
1365
  }
1288
1366
  /** Get the file download URL for an attachment. */
@@ -1505,25 +1583,57 @@ var GraphQLClient = class {
1505
1583
  try {
1506
1584
  const signed = await signGraphQLRequest(body, this.store);
1507
1585
  Object.assign(headers, signed);
1508
- } catch (err) {
1509
- console.warn("[interfacer-client] GraphQL signing failed:", err);
1586
+ } catch {
1587
+ throw new GraphQLSigningError();
1510
1588
  }
1511
1589
  }
1512
1590
  const url = this.config.zenflowsUrl;
1513
1591
  if (!url) throw new Error("zenflowsUrl not configured. Provide zenflowsUrl or proxyUrl in config.");
1514
- const res = await fetch(url, {
1515
- method: "POST",
1516
- headers,
1517
- body
1518
- });
1592
+ let res;
1593
+ try {
1594
+ res = await fetch(url, { method: "POST", headers, body });
1595
+ } catch {
1596
+ throw new GraphQLRequestError([{
1597
+ message: "Unable to reach the service. Check the operation's status before retrying.",
1598
+ extensions: { code: "NETWORK_ERROR" }
1599
+ }]);
1600
+ }
1519
1601
  if (!res.ok) {
1520
- return {
1521
- errors: [{ message: `HTTP ${res.status}: ${res.statusText}` }]
1602
+ const codes = {
1603
+ 401: "UNAUTHENTICATED",
1604
+ 403: "FORBIDDEN",
1605
+ 409: "CONFLICT",
1606
+ 429: "RATE_LIMITED",
1607
+ 503: "SERVICE_UNAVAILABLE"
1522
1608
  };
1609
+ return { errors: [{
1610
+ message: `HTTP ${res.status}`,
1611
+ extensions: { code: codes[res.status] || "HTTP_ERROR", httpStatus: res.status }
1612
+ }] };
1523
1613
  }
1524
- return res.json();
1614
+ let result;
1615
+ try {
1616
+ result = await res.json();
1617
+ } catch {
1618
+ throw invalidResponse();
1619
+ }
1620
+ if (!isGraphQLResult(result)) throw invalidResponse();
1621
+ return result;
1525
1622
  }
1526
1623
  };
1624
+ function invalidResponse() {
1625
+ return new GraphQLRequestError([{
1626
+ message: "The service returned an invalid response. Check the operation's status before retrying.",
1627
+ extensions: { code: "INVALID_RESPONSE" }
1628
+ }]);
1629
+ }
1630
+ function isGraphQLResult(value) {
1631
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1632
+ const result = value;
1633
+ if (result.data != null && (typeof result.data !== "object" || Array.isArray(result.data))) return false;
1634
+ if (result.errors !== void 0 && (!Array.isArray(result.errors) || result.errors.some((error) => !error || typeof error !== "object" || typeof error.message !== "string"))) return false;
1635
+ return Object.hasOwn(result, "data") || Array.isArray(result.errors) && result.errors.length > 0;
1636
+ }
1527
1637
  function extractOperationName(operation) {
1528
1638
  const match = operation.match(/(?:query|mutation)\s+(\w+)/);
1529
1639
  return match ? match[1] : null;
@@ -1726,7 +1836,7 @@ async function getInstanceVariables(client) {
1726
1836
  if (cachedVars) return cachedVars;
1727
1837
  const res = await client.request(QUERY_INSTANCE_VARIABLES);
1728
1838
  if (res.errors?.length) {
1729
- throw new Error(`Failed to fetch instance variables: ${res.errors[0].message}`);
1839
+ throw new GraphQLRequestError(res.errors, "Failed to fetch instance variables");
1730
1840
  }
1731
1841
  const d = res.data?.instanceVariables;
1732
1842
  if (!d) throw new Error("No instance variables returned.");
@@ -2028,6 +2138,19 @@ var TaggingClient = class {
2028
2138
  };
2029
2139
 
2030
2140
  // src/resources/ResourceClient.ts
2141
+ function isMetadataMap(value) {
2142
+ return value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
2143
+ }
2144
+ function metadataError(code) {
2145
+ return new GraphQLRequestError([{ message: code === "BAD_USER_INPUT" ? "Invalid metadata fields or precondition." : "Invalid metadata patch response.", extensions: { code } }]);
2146
+ }
2147
+ function contributionError(code) {
2148
+ return new GraphQLRequestError([{ message: code === "BAD_USER_INPUT" ? "Invalid proposal id." : "Invalid acceptContribution response.", extensions: { code } }]);
2149
+ }
2150
+ function eventId(value) {
2151
+ const id = isMetadataMap(value) ? value.id : void 0;
2152
+ return typeof id === "string" && id ? id : void 0;
2153
+ }
2031
2154
  var ResourceClient = class {
2032
2155
  constructor(config, store, graphql) {
2033
2156
  this.config = config;
@@ -2066,7 +2189,7 @@ var ResourceClient = class {
2066
2189
  CREATE_PROCESS,
2067
2190
  { name }
2068
2191
  );
2069
- if (res.errors?.length) throw new Error(`createProcess failed: ${res.errors[0].message}`);
2192
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createProcess failed");
2070
2193
  return res.data.createProcess.process.id;
2071
2194
  }
2072
2195
  // ─── Location ──────────────────────────────────────────────────────
@@ -2077,7 +2200,7 @@ var ResourceClient = class {
2077
2200
  lat: params.lat || 0,
2078
2201
  lng: params.lng || 0
2079
2202
  });
2080
- if (res.errors?.length) throw new Error(`createLocation failed: ${res.errors[0].message}`);
2203
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createLocation failed");
2081
2204
  return res.data.createSpatialThing.spatialThing;
2082
2205
  }
2083
2206
  // ─── Create Project (Design, Product, Service) ─────────────────────
@@ -2109,7 +2232,7 @@ var ResourceClient = class {
2109
2232
  variables.tags = params.tags;
2110
2233
  }
2111
2234
  const res = await this.graphql.request(CREATE_PROJECT, variables);
2112
- if (res.errors?.length) throw new Error(`createProject failed: ${res.errors[0].message}`);
2235
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createProject failed");
2113
2236
  return res.data.createEconomicEvent.economicEvent.resourceInventoriedAs;
2114
2237
  }
2115
2238
  // ─── Create Machine ────────────────────────────────────────────────
@@ -2141,7 +2264,7 @@ var ResourceClient = class {
2141
2264
  };
2142
2265
  if (tags.length > 0) variables.tags = tags;
2143
2266
  const res = await this.graphql.request(CREATE_MACHINE_RESOURCE, variables);
2144
- if (res.errors?.length) throw new Error(`createMachine failed: ${res.errors[0].message}`);
2267
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createMachine failed");
2145
2268
  return res.data.createEconomicEvent.economicEvent.resourceInventoriedAs;
2146
2269
  }
2147
2270
  // ─── Create DPP Resource ───────────────────────────────────────────
@@ -2160,7 +2283,7 @@ var ResourceClient = class {
2160
2283
  name: params.name,
2161
2284
  note: params.note || ""
2162
2285
  });
2163
- if (res.errors?.length) throw new Error(`createDppResource failed: ${res.errors[0].message}`);
2286
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "createDppResource failed");
2164
2287
  return res.data.createEconomicEvent.economicEvent.resourceInventoriedAs;
2165
2288
  }
2166
2289
  // ─── Queries ───────────────────────────────────────────────────────
@@ -2169,6 +2292,7 @@ var ResourceClient = class {
2169
2292
  QUERY_RESOURCE,
2170
2293
  { id }
2171
2294
  );
2295
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "getResource failed");
2172
2296
  return res.data?.economicResource ?? null;
2173
2297
  }
2174
2298
  async listResources(filter, pagination) {
@@ -2176,6 +2300,7 @@ var ResourceClient = class {
2176
2300
  ...pagination,
2177
2301
  filter: filter || {}
2178
2302
  });
2303
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "listResources failed");
2179
2304
  return res.data || {};
2180
2305
  }
2181
2306
  async getProjects(filter, pagination) {
@@ -2183,6 +2308,7 @@ var ResourceClient = class {
2183
2308
  ...pagination,
2184
2309
  filter: filter || {}
2185
2310
  });
2311
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "getProjects failed");
2186
2312
  return res.data || {};
2187
2313
  }
2188
2314
  async getMachines() {
@@ -2192,6 +2318,7 @@ var ResourceClient = class {
2192
2318
  const res = await this.graphql.request(QUERY_MACHINES, {
2193
2319
  resourceSpecId: machineSpecId
2194
2320
  });
2321
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "getMachines failed");
2195
2322
  return res.data || {};
2196
2323
  }
2197
2324
  // ─── Relations ─────────────────────────────────────────────────────
@@ -2204,7 +2331,7 @@ var ResourceClient = class {
2204
2331
  process: processId,
2205
2332
  unitOne: vars.unitOne
2206
2333
  });
2207
- if (res.errors?.length) throw new Error(`citeResource failed: ${res.errors[0].message}`);
2334
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "citeResource failed");
2208
2335
  }
2209
2336
  async consumeResource(resourceId, processId) {
2210
2337
  const vars = await this.getInstanceVars();
@@ -2215,7 +2342,7 @@ var ResourceClient = class {
2215
2342
  process: processId,
2216
2343
  unitOne: vars.unitOne
2217
2344
  });
2218
- if (res.errors?.length) throw new Error(`consumeResource failed: ${res.errors[0].message}`);
2345
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "consumeResource failed");
2219
2346
  }
2220
2347
  async contributeToResource(processId, contributionTypeSpecId) {
2221
2348
  const vars = await this.getInstanceVars();
@@ -2226,9 +2353,41 @@ var ResourceClient = class {
2226
2353
  unitOne: vars.unitOne,
2227
2354
  conformsTo: contributionTypeSpecId
2228
2355
  });
2229
- if (res.errors?.length) throw new Error(`contribute failed: ${res.errors[0].message}`);
2356
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "contribute failed");
2230
2357
  }
2231
2358
  // ─── Metadata ──────────────────────────────────────────────────────
2359
+ /**
2360
+ * One signed metadata-only mutation: shallow field replacement under the
2361
+ * backend row lock, with optional content CAS. No processes/economic events,
2362
+ * quantity changes, preflight or retry. Arrays/nested objects replace a field;
2363
+ * null is a value, not deletion. Without CAS, overlapping fields are last-write-wins.
2364
+ * The token detects differing current content, not ABA or every historical revision.
2365
+ */
2366
+ async patchMetadata(resourceId, fields, options = {}) {
2367
+ if (typeof resourceId !== "string" || !resourceId.trim() || !isMetadataMap(fields) || !isMetadataMap(options)) throw metadataError("BAD_USER_INPUT");
2368
+ const hasExpected = Object.prototype.hasOwnProperty.call(options, "expectedMetadataHash");
2369
+ if (hasExpected && (typeof options.expectedMetadataHash !== "string" || !/^[0-9a-f]{64}$/.test(options.expectedMetadataHash))) throw metadataError("BAD_USER_INPUT");
2370
+ let serialized;
2371
+ try {
2372
+ serialized = JSON.stringify(fields, (_key, value) => {
2373
+ if (value === void 0 || ["function", "symbol", "bigint"].includes(typeof value) || typeof value === "number" && !Number.isFinite(value)) throw metadataError("BAD_USER_INPUT");
2374
+ return value;
2375
+ });
2376
+ if (!isMetadataMap(JSON.parse(serialized))) throw metadataError("BAD_USER_INPUT");
2377
+ } catch {
2378
+ throw metadataError("BAD_USER_INPUT");
2379
+ }
2380
+ const result = await this.graphql.request(PATCH_RESOURCE_METADATA, {
2381
+ id: resourceId,
2382
+ fields: serialized,
2383
+ ...hasExpected ? { expectedMetadataHash: options.expectedMetadataHash } : {}
2384
+ });
2385
+ if (result.errors?.length) throw new GraphQLRequestError(result.errors, "patchMetadata failed");
2386
+ const resource = result.data?.patchEconomicResourceMetadata?.economicResource;
2387
+ 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");
2388
+ return resource;
2389
+ }
2390
+ /** Legacy full replacement through economic events; not an atomic field patch. */
2232
2391
  async updateMetadata(resourceId, metadata, quantity) {
2233
2392
  const res = await this.graphql.request(UPDATE_METADATA, {
2234
2393
  process: await this.createProcess(`metadata update`),
@@ -2238,14 +2397,14 @@ var ResourceClient = class {
2238
2397
  now: (/* @__PURE__ */ new Date()).toISOString(),
2239
2398
  metadata: JSON.stringify(metadata)
2240
2399
  });
2241
- if (res.errors?.length) throw new Error(`updateMetadata failed: ${res.errors[0].message}`);
2400
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "updateMetadata failed");
2242
2401
  }
2243
2402
  async updateClassifiedAs(resourceId, tags) {
2244
2403
  const res = await this.graphql.request(UPDATE_RESOURCE_CLASSIFIED_AS, {
2245
2404
  id: resourceId,
2246
2405
  classifiedAs: tags
2247
2406
  });
2248
- if (res.errors?.length) throw new Error(`updateClassifiedAs failed: ${res.errors[0].message}`);
2407
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "updateClassifiedAs failed");
2249
2408
  }
2250
2409
  async relocateResource(resourceId, locationId) {
2251
2410
  const vars = await this.getInstanceVars();
@@ -2257,9 +2416,41 @@ var ResourceClient = class {
2257
2416
  now: (/* @__PURE__ */ new Date()).toISOString(),
2258
2417
  location: locationId
2259
2418
  });
2260
- if (res.errors?.length) throw new Error(`relocate failed: ${res.errors[0].message}`);
2419
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "relocate failed");
2261
2420
  }
2262
2421
  // ─── Proposals ─────────────────────────────────────────────────────
2422
+ /**
2423
+ * Create a contribution proposal with one signed mutation; the server writes
2424
+ * the process, intents, proposal and links in one transaction, names the
2425
+ * origin's controller as owner and returns an existing pending proposal for
2426
+ * the same fork and origin (created: false). Never retried by the SDK.
2427
+ * Requires zenflows#77.
2428
+ */
2429
+ async createContributionProposal(params) {
2430
+ const ok = (v) => typeof v === "string" && v.trim().length > 0;
2431
+ const optional = (v) => v === void 0 || typeof v === "string";
2432
+ if (!isMetadataMap(params) || !ok(params.resourceForkedId) || !ok(params.resourceOriginId) || params.resourceForkedId === params.resourceOriginId || !optional(params.name) || !optional(params.note)) {
2433
+ throw new GraphQLRequestError([{ message: "Invalid contribution proposal.", extensions: { code: "BAD_USER_INPUT" } }]);
2434
+ }
2435
+ const variables = { fork: params.resourceForkedId, origin: params.resourceOriginId };
2436
+ if (params.name !== void 0) variables.name = params.name;
2437
+ if (params.note !== void 0) variables.note = params.note;
2438
+ const result = await this.graphql.request(PROPOSE_CONTRIBUTION_ATOMIC, variables);
2439
+ if (result.errors?.length) throw new GraphQLRequestError(result.errors, "createContributionProposal failed");
2440
+ const p = result.data?.proposeContribution;
2441
+ const id = (key) => isMetadataMap(p) ? eventId(p[key]) : void 0;
2442
+ const [proposalId, processId, citeIntentId, acceptIntentId, modifyIntentId] = ["proposal", "process", "citeIntent", "acceptIntent", "modifyIntent"].map(id);
2443
+ const ownerId = isMetadataMap(p) && isMetadataMap(p.acceptIntent) ? eventId(p.acceptIntent.receiver) : void 0;
2444
+ if (!isMetadataMap(p) || typeof p.created !== "boolean" || !proposalId || !processId || !citeIntentId || !acceptIntentId || !modifyIntentId || !ownerId) {
2445
+ throw new GraphQLRequestError([{ message: "Invalid proposeContribution response.", extensions: { code: "INVALID_RESPONSE" } }]);
2446
+ }
2447
+ return { proposalId, processId, citeIntentId, acceptIntentId, modifyIntentId, ownerId, created: p.created };
2448
+ }
2449
+ /**
2450
+ * @deprecated Four non-transactional requests that name a caller-supplied
2451
+ * owner: a failure leaves orphans and a retry duplicates. Use
2452
+ * createContributionProposal.
2453
+ */
2263
2454
  async proposeContribution(params) {
2264
2455
  const vars = await this.getInstanceVars();
2265
2456
  const processId = await this.createProcess("contribution proposal");
@@ -2273,12 +2464,12 @@ var ResourceClient = class {
2273
2464
  unitOne: vars.unitOne,
2274
2465
  resourceOrigin: params.resourceOriginId
2275
2466
  });
2276
- if (intentsRes.errors?.length) throw new Error(`proposeContribution intents failed: ${intentsRes.errors[0].message}`);
2467
+ if (intentsRes.errors?.length) throw new GraphQLRequestError(intentsRes.errors, "proposeContribution intents failed");
2277
2468
  const proposalRes = await this.graphql.request(CREATE_PROPOSAL, {
2278
2469
  name: `Contribution to resource`,
2279
2470
  note: params.note
2280
2471
  });
2281
- if (proposalRes.errors?.length) throw new Error(`createProposal failed: ${proposalRes.errors[0].message}`);
2472
+ if (proposalRes.errors?.length) throw new GraphQLRequestError(proposalRes.errors, "createProposal failed");
2282
2473
  const proposalId = proposalRes.data.createProposal.proposal.id;
2283
2474
  const citeIntentId = intentsRes.data.citeResourceForked.intent.id;
2284
2475
  const acceptIntentId = intentsRes.data.acceptResourceOrigin.intent.id;
@@ -2289,9 +2480,34 @@ var ResourceClient = class {
2289
2480
  acceptIntent: acceptIntentId,
2290
2481
  modifyIntent: modifyIntentId
2291
2482
  });
2292
- if (linkRes.errors?.length) throw new Error(`linkIntents failed: ${linkRes.errors[0].message}`);
2483
+ if (linkRes.errors?.length) throw new GraphQLRequestError(linkRes.errors, "linkIntents failed");
2293
2484
  return { proposalId, citeIntentId, acceptIntentId, modifyIntentId };
2294
2485
  }
2486
+ /**
2487
+ * Accept a contribution proposal with one signed mutation: the backend writes
2488
+ * the events, satisfactions and the origin's new relation in one transaction.
2489
+ * Accepting an accepted proposal returns the same events, so a caller may
2490
+ * retry after an uncertain outcome; the SDK itself never retries. A rejected
2491
+ * or half-accepted proposal fails with CONFLICT. Requires zenflows#76.
2492
+ */
2493
+ async acceptContribution(proposalId) {
2494
+ if (typeof proposalId !== "string" || !proposalId.trim()) throw contributionError("BAD_USER_INPUT");
2495
+ const result = await this.graphql.request(ACCEPT_CONTRIBUTION, { proposalId });
2496
+ if (result.errors?.length) throw new GraphQLRequestError(result.errors, "acceptContribution failed");
2497
+ const payload = result.data?.acceptContribution;
2498
+ const proposal = isMetadataMap(payload) && isMetadataMap(payload.proposal) ? payload.proposal : void 0;
2499
+ const citeEventId = isMetadataMap(payload) ? eventId(payload.citeEvent) : void 0;
2500
+ const acceptEventId = isMetadataMap(payload) ? eventId(payload.acceptEvent) : void 0;
2501
+ const modifyEventId = isMetadataMap(payload) ? eventId(payload.modifyEvent) : void 0;
2502
+ if (!proposal || proposal.id !== proposalId || proposal.status !== "ACCEPTED" || !citeEventId || !acceptEventId || !modifyEventId) {
2503
+ throw contributionError("INVALID_RESPONSE");
2504
+ }
2505
+ return { proposalId, status: "ACCEPTED", citeEventId, acceptEventId, modifyEventId };
2506
+ }
2507
+ /**
2508
+ * @deprecated Two non-transactional requests: a failure between them leaves
2509
+ * committed events and a retry duplicates them. Use acceptContribution.
2510
+ */
2295
2511
  async acceptProposal(params) {
2296
2512
  const vars = await this.getInstanceVars();
2297
2513
  const processId = await this.createProcess("accept contribution");
@@ -2305,7 +2521,7 @@ var ResourceClient = class {
2305
2521
  creationTime: (/* @__PURE__ */ new Date()).toISOString(),
2306
2522
  metadata: JSON.stringify(params.newMetadata)
2307
2523
  });
2308
- if (eventsRes.errors?.length) throw new Error(`acceptProposal events failed: ${eventsRes.errors[0].message}`);
2524
+ if (eventsRes.errors?.length) throw new GraphQLRequestError(eventsRes.errors, "acceptProposal events failed");
2309
2525
  const satRes = await this.graphql.request(SATISFY_INTENTS, {
2310
2526
  unitOne: vars.unitOne,
2311
2527
  intentCited: params.citeIntentId,
@@ -2315,11 +2531,11 @@ var ResourceClient = class {
2315
2531
  eventAccept: eventsRes.data.accept.economicEvent.id,
2316
2532
  eventModify: eventsRes.data.modify.economicEvent.id
2317
2533
  });
2318
- if (satRes.errors?.length) throw new Error(`satisfyIntents failed: ${satRes.errors[0].message}`);
2534
+ if (satRes.errors?.length) throw new GraphQLRequestError(satRes.errors, "satisfyIntents failed");
2319
2535
  }
2320
2536
  async getTraceDpp(id) {
2321
2537
  const res = await this.graphql.request(QUERY_RESOURCE_TRACE_DPP, { id });
2322
- if (res.errors?.length) throw new Error(`getTraceDpp failed: ${res.errors[0].message}`);
2538
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "getTraceDpp failed");
2323
2539
  const traceDpp = res.data?.economicResource?.traceDpp;
2324
2540
  return Array.isArray(traceDpp) ? traceDpp : [];
2325
2541
  }
@@ -2329,7 +2545,7 @@ var ResourceClient = class {
2329
2545
  intentAccept,
2330
2546
  intentModify
2331
2547
  });
2332
- if (res.errors?.length) throw new Error(`rejectProposal failed: ${res.errors[0].message}`);
2548
+ if (res.errors?.length) throw new GraphQLRequestError(res.errors, "rejectProposal failed");
2333
2549
  }
2334
2550
  };
2335
2551
 
@@ -2467,6 +2683,28 @@ var WalletClient = class {
2467
2683
  });
2468
2684
  if (!res.ok) throw new Error(`Wallet addPoints failed: ${res.statusText}`);
2469
2685
  }
2686
+ /**
2687
+ * Issue points for a ValueFlows/social event. Unlike addPoints, the caller
2688
+ * does NOT choose the recipient or amount: it names the event that justifies
2689
+ * the issuance, and the server (Zenflows PDP) attests it and derives the
2690
+ * recipients and server-authoritative amounts. Phase 1 supports `accept`.
2691
+ */
2692
+ async issueForEvent(event) {
2693
+ const walletUrl = this.config.walletUrl;
2694
+ if (!walletUrl) throw new Error("walletUrl not configured");
2695
+ const body = JSON.stringify({ event });
2696
+ const headers = await signDidRequest(body, this.store);
2697
+ const res = await fetch(walletUrl, {
2698
+ method: "POST",
2699
+ headers: { ...headers, "Content-Type": "application/json" },
2700
+ body
2701
+ });
2702
+ if (!res.ok) throw new Error(`Wallet issueForEvent failed: ${res.statusText}`);
2703
+ const data = await res.json();
2704
+ if (data?.success !== true) {
2705
+ throw new Error(`Wallet issue denied: ${data?.reason ?? "unknown"}`);
2706
+ }
2707
+ }
2470
2708
  /** Get point trend over a period (change since period start). */
2471
2709
  async getTrend(agentId, token, periodStartMs) {
2472
2710
  const periodStartBalance = await this.getBalanceAt(agentId, token, periodStartMs);
@@ -2606,6 +2844,7 @@ function createConfig(config) {
2606
2844
  // src/index.ts
2607
2845
  init_sign();
2608
2846
  export {
2847
+ ACCEPT_CONTRIBUTION,
2609
2848
  ACCEPT_PROPOSAL,
2610
2849
  ASK_RESOURCE_PRIMARY_ACCOUNTABLE,
2611
2850
  AVAILABILITY_OPTIONS,
@@ -2641,17 +2880,21 @@ export {
2641
2880
  GET_USER_IMAGES,
2642
2881
  GET_USER_LAYOUT,
2643
2882
  GraphQLClient,
2883
+ GraphQLRequestError,
2884
+ GraphQLSigningError,
2644
2885
  ImportClient,
2645
2886
  InboxClient,
2646
2887
  InterfacerClient,
2647
2888
  LINK_CONTRIBUTION_PROPOSAL_INTENT,
2648
2889
  LINK_PROPOSAL_AND_INTENT,
2649
2890
  MANUFACTURABLE_TRUE_TAG,
2891
+ PATCH_RESOURCE_METADATA,
2650
2892
  PERSON_EXISTS,
2651
2893
  POWER_COMPATIBILITY_OPTIONS,
2652
2894
  POWER_REQUIREMENT_THRESHOLDS_W,
2653
2895
  PRODUCT_CATEGORY_OPTIONS,
2654
2896
  PROPOSE_CONTRIBUTION,
2897
+ PROPOSE_CONTRIBUTION_ATOMIC,
2655
2898
  QUERY_AGENTS,
2656
2899
  QUERY_CITED_RESOURCES,
2657
2900
  QUERY_MACHINES,
@@ -2716,6 +2959,7 @@ export {
2716
2959
  signGraphQLRequest,
2717
2960
  slugifyTagValue,
2718
2961
  stripUserTagPrefix,
2962
+ throwIfGraphQLErrors,
2719
2963
  userTag
2720
2964
  };
2721
2965
  //# sourceMappingURL=index.js.map