@partylayer/sdk 0.15.0 → 0.17.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.mjs CHANGED
@@ -364,6 +364,46 @@ var GenericDiscoveryAdapter = class {
364
364
  };
365
365
  return { partyId, session, capabilities: this.getCapabilities() };
366
366
  }
367
+ /**
368
+ * Restore a persisted session by delegating to the official adapter's own `restore`.
369
+ *
370
+ * The official `ProviderAdapter` shape carries an optional `restore()` that reinstates a
371
+ * session (for example from the wallet's own storage) and returns a LIVE provider.
372
+ * Without this method the SDK revived the persisted record as-is and then built a fresh,
373
+ * SESSION-LESS provider from `provider()`, so a wallet that restores in `restore` looked
374
+ * connected after a reload but its first real request threw. This forwards to the
375
+ * official `restore` and, when it yields a provider, adopts it as the cached provider so
376
+ * the very next request uses the restored session.
377
+ *
378
+ * Popup-safe: this runs on the SDK's init/restore path, never inside a user gesture, so a
379
+ * popup could not open here even if an adapter tried (the browser would block it). Per
380
+ * the official contract `restore` is storage-based and gesture-free. If the official
381
+ * adapter has no `restore`, it returns null, or host resolution is not ready, this falls
382
+ * through to the previous behavior: the persisted session is returned and the provider is
383
+ * built lazily on first use, exactly as before.
384
+ */
385
+ async restore(ctx, persisted) {
386
+ const asIs = { ...persisted, walletId: this.walletId };
387
+ try {
388
+ this.resolveOfficial(ctx.network);
389
+ } catch {
390
+ return asIs;
391
+ }
392
+ const restore = this.official?.restore;
393
+ if (this.official && restore) {
394
+ let restored = null;
395
+ try {
396
+ restored = await restore.call(this.official);
397
+ } catch {
398
+ restored = null;
399
+ }
400
+ if (restored) {
401
+ this.providerInstance = restored;
402
+ return asIs;
403
+ }
404
+ }
405
+ return asIs;
406
+ }
367
407
  async disconnect() {
368
408
  try {
369
409
  await this.provider.request({ method: "disconnect" });
@@ -389,25 +429,13 @@ var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
389
429
 
390
430
  // src/adapters.ts
391
431
  var DefaultLogger = class {
392
- debug(message, ...args) {
393
- if (typeof console !== "undefined" && console.debug) {
394
- console.debug(`[PartyLayer] ${message}`, ...args);
395
- }
432
+ debug(_message, ..._args) {
396
433
  }
397
- info(message, ...args) {
398
- if (typeof console !== "undefined" && console.info) {
399
- console.info(`[PartyLayer] ${message}`, ...args);
400
- }
434
+ info(_message, ..._args) {
401
435
  }
402
- warn(message, ...args) {
403
- if (typeof console !== "undefined" && console.warn) {
404
- console.warn(`[PartyLayer] ${message}`, ...args);
405
- }
436
+ warn(_message, ..._args) {
406
437
  }
407
- error(message, error, ...args) {
408
- if (typeof console !== "undefined" && console.error) {
409
- console.error(`[PartyLayer] ${message}`, error, ...args);
410
- }
438
+ error(_message, _error, ..._args) {
411
439
  }
412
440
  };
413
441
  var DefaultCrypto = class {
@@ -735,6 +763,85 @@ function createTelemetryAdapter(config) {
735
763
  }
736
764
  return config;
737
765
  }
766
+
767
+ // src/event-telemetry.ts
768
+ function errorProperties(error) {
769
+ const code = error.code;
770
+ return code ? { code } : {};
771
+ }
772
+ function eventTelemetryProperties(event) {
773
+ switch (event.type) {
774
+ case "registry:updated":
775
+ return { channel: event.channel, version: event.version };
776
+ case "registry:status":
777
+ return {
778
+ source: event.status.source,
779
+ channel: event.status.channel,
780
+ verified: event.status.verified,
781
+ stale: event.status.stale,
782
+ sequence: event.status.sequence
783
+ };
784
+ case "session:connected":
785
+ return { walletId: event.session.walletId, network: event.session.network };
786
+ case "session:disconnected":
787
+ return {};
788
+ case "session:expired":
789
+ return {};
790
+ case "session:networkMismatch":
791
+ return { expected: event.expected, actual: event.actual, enforced: event.enforced };
792
+ case "tx:status":
793
+ return { status: event.status };
794
+ case "error":
795
+ return errorProperties(event.error);
796
+ case "wallets:changed":
797
+ return { reason: event.reason };
798
+ default:
799
+ return {};
800
+ }
801
+ }
802
+
803
+ // src/logging.ts
804
+ var LEVEL_PRIORITY = {
805
+ debug: 10,
806
+ info: 20,
807
+ warn: 30,
808
+ error: 40,
809
+ silent: 100
810
+ };
811
+ function shouldLog(level, threshold) {
812
+ if (threshold === "silent") return false;
813
+ return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[threshold];
814
+ }
815
+ function newCorrelationId() {
816
+ const scope = typeof globalThis !== "undefined" ? globalThis : {};
817
+ if (scope.crypto && typeof scope.crypto.getRandomValues === "function") {
818
+ const bytes = new Uint8Array(6);
819
+ scope.crypto.getRandomValues(bytes);
820
+ let hex = "";
821
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
822
+ return hex;
823
+ }
824
+ return Math.random().toString(16).slice(2, 14).padStart(12, "0");
825
+ }
826
+ function eventLogLevel(type) {
827
+ switch (type) {
828
+ case "error":
829
+ return "error";
830
+ case "session:networkMismatch":
831
+ return "warn";
832
+ case "session:connected":
833
+ case "session:disconnected":
834
+ return "info";
835
+ case "registry:status":
836
+ case "registry:updated":
837
+ case "session:expired":
838
+ case "tx:status":
839
+ case "wallets:changed":
840
+ return "debug";
841
+ default:
842
+ return "info";
843
+ }
844
+ }
738
845
  var SESSION_STORAGE_KEY = "active_session";
739
846
  var WALLETS_CHANGED_DEBOUNCE_MS = 50;
740
847
  function deriveAnnounceConfig(entry) {
@@ -778,6 +885,8 @@ var PartyLayerClient = class {
778
885
  registryClient;
779
886
  // Expose for React hooks
780
887
  logger;
888
+ /** Configured log verbosity; filtering happens centrally in {@link log}. */
889
+ logLevel;
781
890
  crypto;
782
891
  storage;
783
892
  telemetry;
@@ -802,6 +911,7 @@ var PartyLayerClient = class {
802
911
  this.origin = "unknown";
803
912
  }
804
913
  this.logger = config.logger || new DefaultLogger();
914
+ this.logLevel = config.logLevel ?? "info";
805
915
  this.crypto = config.crypto || new DefaultCrypto();
806
916
  this.storage = config.storage || new DefaultStorage();
807
917
  const telemetryAdapter = createTelemetryAdapter(config.telemetry);
@@ -819,7 +929,7 @@ var PartyLayerClient = class {
819
929
  adapter = adapterOrClass;
820
930
  }
821
931
  this.adapters.set(adapter.walletId, adapter);
822
- this.logger.debug("Registered wallet adapter", {
932
+ this.log("debug", "adapter:registered", "Registered wallet adapter", {
823
933
  walletId: adapter.walletId,
824
934
  name: adapter.name,
825
935
  capabilities: adapter.getCapabilities()
@@ -885,7 +995,7 @@ var PartyLayerClient = class {
885
995
  this.updateRegistryStatus();
886
996
  } catch (err) {
887
997
  this.updateRegistryStatus();
888
- this.logger.warn("Registry fetch failed, using registered adapters only", {
998
+ this.log("warn", "registry:fetch_failed", "Registry fetch failed, using registered adapters only", {
889
999
  error: err instanceof Error ? err.message : String(err)
890
1000
  });
891
1001
  registryWallets = [];
@@ -1073,7 +1183,9 @@ var PartyLayerClient = class {
1073
1183
  this.emit("session:expired", { type: "session:expired", sessionId: active.sessionId });
1074
1184
  }
1075
1185
  } catch (err) {
1076
- this.logger.warn("Restore re-probe failed; leaving session as-is", err);
1186
+ this.log("warn", "session:reprobe_failed", "Restore re-probe failed; leaving session as-is", {
1187
+ error: err instanceof Error ? err.message : String(err)
1188
+ });
1077
1189
  }
1078
1190
  }
1079
1191
  }
@@ -1140,11 +1252,13 @@ var PartyLayerClient = class {
1140
1252
  */
1141
1253
  async connect(options) {
1142
1254
  this.telemetry?.increment?.(METRICS.WALLET_CONNECT_ATTEMPTS);
1255
+ const correlationId = newCorrelationId();
1256
+ this.log("debug", "connect:start", "connect", {}, correlationId);
1143
1257
  try {
1144
- const fast = this.tryFastConnect(options);
1258
+ const fast = this.tryFastConnect(options, correlationId);
1145
1259
  if (fast) return await fast;
1146
1260
  const plan = await this.resolveConnectPlan(options);
1147
- return await this.completeConnect(plan, options);
1261
+ return await this.completeConnect(plan, options, correlationId);
1148
1262
  } catch (err) {
1149
1263
  const timeoutMs = options?.timeoutMs || 3e4;
1150
1264
  const error = mapUnknownErrorToPartyLayerError(err, {
@@ -1152,7 +1266,7 @@ var PartyLayerClient = class {
1152
1266
  walletId: options?.walletId ? String(options.walletId) : void 0,
1153
1267
  timeoutMs
1154
1268
  });
1155
- this.emit("error", { type: "error", error });
1269
+ this.emit("error", { type: "error", error }, correlationId);
1156
1270
  throw error;
1157
1271
  }
1158
1272
  }
@@ -1256,7 +1370,7 @@ var PartyLayerClient = class {
1256
1370
  * build / persist / emit the session. Separated from plan resolution so the
1257
1371
  * popup-safe fast-path can call it gesture-synchronously.
1258
1372
  */
1259
- async completeConnect(plan, options) {
1373
+ async completeConnect(plan, options, correlationId = newCorrelationId()) {
1260
1374
  const { selectedWallet, adapter, ctx } = plan;
1261
1375
  const timeoutMs = options?.timeoutMs || 12e4;
1262
1376
  const connectPromise = adapter.connect(ctx, {
@@ -1299,7 +1413,7 @@ var PartyLayerClient = class {
1299
1413
  expected: mismatch.expected,
1300
1414
  actual: mismatch.actual,
1301
1415
  enforced: this.enforcement !== "off"
1302
- });
1416
+ }, correlationId);
1303
1417
  if (this.enforcement === "strict") {
1304
1418
  throw new NetworkMismatchError(mismatch.expected, mismatch.actual);
1305
1419
  }
@@ -1313,7 +1427,7 @@ var PartyLayerClient = class {
1313
1427
  this.emit("session:connected", {
1314
1428
  type: "session:connected",
1315
1429
  session
1316
- });
1430
+ }, correlationId);
1317
1431
  return session;
1318
1432
  }
1319
1433
  /**
@@ -1353,14 +1467,14 @@ var PartyLayerClient = class {
1353
1467
  * Returns the in-flight Session promise, or null to fall back to the normal
1354
1468
  * path (e.g. cold cache, or a non-discovery wallet).
1355
1469
  */
1356
- tryFastConnect(options) {
1470
+ tryFastConnect(options, correlationId) {
1357
1471
  const walletId = options?.walletId;
1358
1472
  if (!walletId) return null;
1359
1473
  if (options?.requiredCapabilities || options?.allowWallets) return null;
1360
1474
  const plan = this.warmPlans.get(walletId);
1361
1475
  if (!plan) return null;
1362
1476
  this.warmPlans.delete(walletId);
1363
- return this.completeConnect(plan, options);
1477
+ return this.completeConnect(plan, options, correlationId);
1364
1478
  }
1365
1479
  /**
1366
1480
  * Disconnect from wallet
@@ -1452,6 +1566,8 @@ var PartyLayerClient = class {
1452
1566
  "signTransaction"
1453
1567
  );
1454
1568
  }
1569
+ const correlationId = newCorrelationId();
1570
+ this.log("debug", "signTransaction:start", "signTransaction", {}, correlationId);
1455
1571
  try {
1456
1572
  this.assertNetworkOk(session);
1457
1573
  const ctx = this.createAdapterContext();
@@ -1462,14 +1578,14 @@ var PartyLayerClient = class {
1462
1578
  txId: result.transactionHash,
1463
1579
  status: "pending",
1464
1580
  raw: result.signedTx
1465
- });
1581
+ }, correlationId);
1466
1582
  return result;
1467
1583
  } catch (err) {
1468
1584
  const error = mapUnknownErrorToPartyLayerError(err, {
1469
1585
  phase: "signTransaction",
1470
1586
  walletId: String(session.walletId)
1471
1587
  });
1472
- this.emit("error", { type: "error", error });
1588
+ this.emit("error", { type: "error", error }, correlationId);
1473
1589
  throw error;
1474
1590
  }
1475
1591
  }
@@ -1488,6 +1604,8 @@ var PartyLayerClient = class {
1488
1604
  "submitTransaction"
1489
1605
  );
1490
1606
  }
1607
+ const correlationId = newCorrelationId();
1608
+ this.log("debug", "submitTransaction:start", "submitTransaction", {}, correlationId);
1491
1609
  try {
1492
1610
  this.assertNetworkOk(session);
1493
1611
  const ctx = this.createAdapterContext();
@@ -1498,14 +1616,14 @@ var PartyLayerClient = class {
1498
1616
  txId: result.transactionHash,
1499
1617
  status: "submitted",
1500
1618
  raw: result
1501
- });
1619
+ }, correlationId);
1502
1620
  return result;
1503
1621
  } catch (err) {
1504
1622
  const error = mapUnknownErrorToPartyLayerError(err, {
1505
1623
  phase: "submitTransaction",
1506
1624
  walletId: String(session.walletId)
1507
1625
  });
1508
- this.emit("error", { type: "error", error });
1626
+ this.emit("error", { type: "error", error }, correlationId);
1509
1627
  throw error;
1510
1628
  }
1511
1629
  }
@@ -1630,7 +1748,9 @@ var PartyLayerClient = class {
1630
1748
  const encrypted = await this.crypto.encrypt(data, this.origin);
1631
1749
  await this.storage.set(SESSION_STORAGE_KEY, encrypted);
1632
1750
  } catch (err) {
1633
- this.logger.warn("Failed to persist session", err);
1751
+ this.log("warn", "session:persist_failed", "Failed to persist session", {
1752
+ error: err instanceof Error ? err.message : String(err)
1753
+ });
1634
1754
  }
1635
1755
  }
1636
1756
  /**
@@ -1643,7 +1763,9 @@ var PartyLayerClient = class {
1643
1763
  try {
1644
1764
  await this.storage.remove(SESSION_STORAGE_KEY);
1645
1765
  } catch (err) {
1646
- this.logger.warn("Failed to remove session", err);
1766
+ this.log("warn", "session:remove_failed", "Failed to remove session", {
1767
+ error: err instanceof Error ? err.message : String(err)
1768
+ });
1647
1769
  }
1648
1770
  }
1649
1771
  /**
@@ -1651,6 +1773,8 @@ var PartyLayerClient = class {
1651
1773
  */
1652
1774
  async restoreSession() {
1653
1775
  this.telemetry?.increment?.(METRICS.RESTORE_ATTEMPTS);
1776
+ const correlationId = newCorrelationId();
1777
+ this.log("debug", "session:restore_start", "restoreSession", {}, correlationId);
1654
1778
  try {
1655
1779
  const encrypted = await this.storage.get(SESSION_STORAGE_KEY);
1656
1780
  if (!encrypted) {
@@ -1673,17 +1797,17 @@ var PartyLayerClient = class {
1673
1797
  expected: mismatch.expected,
1674
1798
  actual: mismatch.actual,
1675
1799
  enforced: this.enforcement !== "off"
1676
- });
1800
+ }, correlationId);
1677
1801
  if (this.enforcement !== "off") {
1678
- this.logger.warn("Refused session restore \u2014 network mismatch", {
1802
+ this.log("warn", "session:restore_network_mismatch", "Refused session restore: network mismatch", {
1679
1803
  expected: mismatch.expected,
1680
1804
  actual: mismatch.actual
1681
- });
1805
+ }, correlationId);
1682
1806
  await this.removeSession(session.sessionId);
1683
1807
  this.emit("session:expired", {
1684
1808
  type: "session:expired",
1685
1809
  sessionId: session.sessionId
1686
- });
1810
+ }, correlationId);
1687
1811
  return null;
1688
1812
  }
1689
1813
  session.networkMismatch = mismatch;
@@ -1704,14 +1828,14 @@ var PartyLayerClient = class {
1704
1828
  this.emit("session:connected", {
1705
1829
  type: "session:connected",
1706
1830
  session: restored
1707
- });
1831
+ }, correlationId);
1708
1832
  return restored;
1709
1833
  } else {
1710
1834
  await this.removeSession(session.sessionId);
1711
1835
  this.emit("session:expired", {
1712
1836
  type: "session:expired",
1713
1837
  sessionId: session.sessionId
1714
- });
1838
+ }, correlationId);
1715
1839
  return null;
1716
1840
  }
1717
1841
  }
@@ -1719,7 +1843,9 @@ var PartyLayerClient = class {
1719
1843
  this.activeSessionNeedsProbe = true;
1720
1844
  return session;
1721
1845
  } catch (err) {
1722
- this.logger.warn("Failed to restore session", err);
1846
+ this.log("warn", "session:restore_failed", "Failed to restore session", {
1847
+ error: err instanceof Error ? err.message : String(err)
1848
+ }, correlationId);
1723
1849
  return null;
1724
1850
  }
1725
1851
  }
@@ -1761,20 +1887,56 @@ var PartyLayerClient = class {
1761
1887
  /**
1762
1888
  * Emit event to handlers
1763
1889
  */
1764
- emit(event, payload) {
1890
+ /**
1891
+ * Central structured log. Filters by the configured level here, before the adapter
1892
+ * is called, so adapters never filter themselves; skips entirely when no real
1893
+ * logger was configured (the no-op default), so a silent client pays only a check.
1894
+ * Every line carries a machine readable payload `{ event, correlationId?, ...fields }`.
1895
+ * Privacy: callers pass only non identifying fields, the same rule as telemetry.
1896
+ */
1897
+ log(level, event, message, fields, correlationId) {
1898
+ if (this.logger instanceof DefaultLogger) return;
1899
+ if (!shouldLog(level, this.logLevel)) return;
1900
+ const payload = {
1901
+ event,
1902
+ ...correlationId ? { correlationId } : {},
1903
+ ...fields ?? {}
1904
+ };
1905
+ switch (level) {
1906
+ case "debug":
1907
+ this.logger.debug(message, payload);
1908
+ break;
1909
+ case "info":
1910
+ this.logger.info(message, payload);
1911
+ break;
1912
+ case "warn":
1913
+ this.logger.warn(message, payload);
1914
+ break;
1915
+ case "error":
1916
+ this.logger.error(message, payload);
1917
+ break;
1918
+ }
1919
+ }
1920
+ emit(event, payload, correlationId) {
1765
1921
  if (event === "error" && "error" in payload) {
1766
1922
  const error = payload.error;
1767
1923
  if (error.code) {
1768
1924
  this.telemetry?.increment?.(errorMetricName(error.code));
1769
1925
  }
1770
1926
  }
1927
+ if (this.telemetry && !(this.telemetry instanceof DefaultTelemetry)) {
1928
+ this.telemetry.track(event, eventTelemetryProperties(payload));
1929
+ }
1930
+ this.log(eventLogLevel(event), event, event, eventTelemetryProperties(payload), correlationId);
1771
1931
  const handlers = this.eventHandlers.get(event);
1772
1932
  if (handlers) {
1773
1933
  for (const handler of handlers) {
1774
1934
  try {
1775
1935
  handler(payload);
1776
1936
  } catch (err) {
1777
- this.logger.error("Error in event handler", err);
1937
+ this.log("error", "event:handler_error", "Error in event handler", {
1938
+ error: err instanceof Error ? err.message : String(err)
1939
+ });
1778
1940
  }
1779
1941
  }
1780
1942
  }