optropic 2.3.0 → 3.0.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
@@ -386,6 +386,8 @@ var AssetsResource = class {
386
386
  this.request = request;
387
387
  this.client = client;
388
388
  }
389
+ request;
390
+ client;
389
391
  async create(params) {
390
392
  return this.request({ method: "POST", path: "/v1/assets", body: params });
391
393
  }
@@ -445,6 +447,20 @@ var AssetsResource = class {
445
447
  async batchCreate(params) {
446
448
  return this.request({ method: "POST", path: "/v1/assets/batch", body: params });
447
449
  }
450
+ async batchVerify(assetIds) {
451
+ return this.request({
452
+ method: "POST",
453
+ path: "/v1/assets/batch-verify",
454
+ body: { asset_ids: assetIds }
455
+ });
456
+ }
457
+ async batchRevoke(assetIds, reason) {
458
+ return this.request({
459
+ method: "POST",
460
+ path: "/v1/assets/batch-revoke",
461
+ body: { asset_ids: assetIds, reason }
462
+ });
463
+ }
448
464
  buildQuery(params) {
449
465
  const entries = Object.entries(params).filter(([, v]) => v !== void 0);
450
466
  if (entries.length === 0) return "";
@@ -457,6 +473,7 @@ var AuditResource = class {
457
473
  constructor(request) {
458
474
  this.request = request;
459
475
  }
476
+ request;
460
477
  /**
461
478
  * List audit events with optional filtering and pagination.
462
479
  */
@@ -495,11 +512,101 @@ var AuditResource = class {
495
512
  }
496
513
  };
497
514
 
515
+ // src/resources/batches.ts
516
+ var BatchesResource = class {
517
+ constructor(request) {
518
+ this.request = request;
519
+ }
520
+ request;
521
+ /**
522
+ * Create a new batch job with the given operation and items.
523
+ */
524
+ async create(params) {
525
+ return this.request({ method: "POST", path: "/v1/batches", body: params });
526
+ }
527
+ /**
528
+ * Get the status and details of a specific batch job.
529
+ */
530
+ async get(batchId) {
531
+ return this.request({
532
+ method: "GET",
533
+ path: `/v1/batches/${encodeURIComponent(batchId)}`
534
+ });
535
+ }
536
+ /**
537
+ * List batch jobs with optional limiting.
538
+ */
539
+ async list(params) {
540
+ const query = params ? this.buildQuery(params) : "";
541
+ const result = await this.request({
542
+ method: "GET",
543
+ path: `/v1/batches${query}`
544
+ });
545
+ return result.data;
546
+ }
547
+ /**
548
+ * Wait for a batch job to complete, polling at regular intervals.
549
+ *
550
+ * @param batchId - The ID of the batch to wait for
551
+ * @param opts - Polling configuration (pollInterval in ms, timeout in ms)
552
+ * @returns The final batch result once completed
553
+ * @throws TimeoutError if the operation exceeds the timeout
554
+ */
555
+ async wait(batchId, opts) {
556
+ const pollInterval = opts?.pollInterval ?? 1e3;
557
+ const timeout = opts?.timeout ?? 3e5;
558
+ const startTime = Date.now();
559
+ while (true) {
560
+ const batch = await this.get(batchId);
561
+ if (batch.status === "completed" || batch.status === "failed" || batch.status === "cancelled") {
562
+ return {
563
+ batchId: batch.batchId,
564
+ operation: batch.operation,
565
+ status: batch.status,
566
+ totalItems: batch.totalItems,
567
+ processedItems: batch.processedItems,
568
+ failedItems: batch.failedItems,
569
+ completedAt: batch.completedAt ?? (/* @__PURE__ */ new Date()).toISOString()
570
+ };
571
+ }
572
+ const elapsed = Date.now() - startTime;
573
+ if (elapsed > timeout) {
574
+ throw new Error(`Batch ${batchId} did not complete within ${timeout}ms`);
575
+ }
576
+ await this.sleep(pollInterval);
577
+ }
578
+ }
579
+ /**
580
+ * Cancel a batch job that is still pending or processing.
581
+ */
582
+ async cancel(batchId) {
583
+ return this.request({
584
+ method: "POST",
585
+ path: `/v1/batches/${encodeURIComponent(batchId)}/cancel`
586
+ });
587
+ }
588
+ // ─────────────────────────────────────────────────────────────────────────
589
+ // PRIVATE HELPERS
590
+ // ─────────────────────────────────────────────────────────────────────────
591
+ buildQuery(params) {
592
+ const entries = Object.entries(params).filter(([, v]) => v !== void 0);
593
+ if (entries.length === 0) return "";
594
+ const qs = new URLSearchParams(
595
+ entries.map(([k, v]) => [k, String(v)])
596
+ );
597
+ return `?${qs.toString()}`;
598
+ }
599
+ sleep(ms) {
600
+ return new Promise((resolve) => setTimeout(resolve, ms));
601
+ }
602
+ };
603
+
498
604
  // src/resources/compliance.ts
499
605
  var ComplianceResource = class {
500
606
  constructor(request) {
501
607
  this.request = request;
502
608
  }
609
+ request;
503
610
  /**
504
611
  * Verify the integrity of the full audit chain.
505
612
  */
@@ -568,6 +675,7 @@ var DocumentsResource = class {
568
675
  constructor(request) {
569
676
  this.request = request;
570
677
  }
678
+ request;
571
679
  /**
572
680
  * Enroll a new document (substrate fingerprint) linked to an asset.
573
681
  *
@@ -660,6 +768,7 @@ var KeysResource = class {
660
768
  constructor(request) {
661
769
  this.request = request;
662
770
  }
771
+ request;
663
772
  async create(params) {
664
773
  return this.request({ method: "POST", path: "/v1/keys", body: params });
665
774
  }
@@ -670,6 +779,26 @@ var KeysResource = class {
670
779
  async revoke(keyId) {
671
780
  await this.request({ method: "DELETE", path: `/v1/keys/${encodeURIComponent(keyId)}` });
672
781
  }
782
+ /**
783
+ * Get information about the current API key being used.
784
+ */
785
+ async current() {
786
+ return this.request({ method: "GET", path: "/v1/keys/current" });
787
+ }
788
+ /**
789
+ * Rotate the specified API key to a new one.
790
+ *
791
+ * @param keyId - The ID of the key to rotate
792
+ * @param opts - Optional rotation parameters (gracePeriodHours)
793
+ * @returns New key information and the new key string
794
+ */
795
+ async rotate(keyId, opts) {
796
+ return this.request({
797
+ method: "POST",
798
+ path: `/v1/keys/${encodeURIComponent(keyId)}/rotate`,
799
+ body: opts
800
+ });
801
+ }
673
802
  };
674
803
 
675
804
  // src/resources/keysets.ts
@@ -677,6 +806,7 @@ var KeysetsResource = class {
677
806
  constructor(request) {
678
807
  this.request = request;
679
808
  }
809
+ request;
680
810
  async create(params) {
681
811
  return this.request({ method: "POST", path: "/v1/keysets", body: params });
682
812
  }
@@ -691,11 +821,539 @@ var KeysetsResource = class {
691
821
  }
692
822
  };
693
823
 
824
+ // src/m2m/consensus.ts
825
+ function computeDistance(a, b) {
826
+ if (a.length !== b.length) {
827
+ throw new Error("Vectors must have the same length");
828
+ }
829
+ let sum = 0;
830
+ for (let i = 0; i < a.length; i++) {
831
+ const diff = a[i] - b[i];
832
+ sum += diff * diff;
833
+ }
834
+ return Math.sqrt(sum);
835
+ }
836
+ function computeSimilarity(a, b) {
837
+ const distance = computeDistance(a, b);
838
+ return 1 / (1 + distance);
839
+ }
840
+ function calibrateThreshold(knownMatches) {
841
+ if (knownMatches.length === 0) {
842
+ return 0.85;
843
+ }
844
+ const similarities = knownMatches.map((pair) => ({
845
+ similarity: computeSimilarity(pair.a.dimensions, pair.b.dimensions),
846
+ isMatch: pair.isMatch
847
+ }));
848
+ similarities.sort((a, b) => a.similarity - b.similarity);
849
+ let bestThreshold = 0.85;
850
+ let bestAccuracy = 0;
851
+ for (const item of similarities) {
852
+ const threshold = item.similarity;
853
+ let correct = 0;
854
+ for (const pair of similarities) {
855
+ const predicted = pair.similarity >= threshold;
856
+ if (predicted === pair.isMatch) {
857
+ correct++;
858
+ }
859
+ }
860
+ const accuracy = correct / similarities.length;
861
+ if (accuracy > bestAccuracy) {
862
+ bestAccuracy = accuracy;
863
+ bestThreshold = threshold;
864
+ }
865
+ }
866
+ return bestThreshold;
867
+ }
868
+ function evaluateConsensus(descriptorA, descriptorB, config) {
869
+ const cfg = {
870
+ threshold: config?.threshold ?? 0.85,
871
+ minDimensions: config?.minDimensions ?? 3,
872
+ maxTimeDeltaMs: config?.maxTimeDeltaMs ?? 3e4,
873
+ requireAllDimensions: config?.requireAllDimensions ?? true
874
+ };
875
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
876
+ const matchDetails = [];
877
+ let trustEstablished = false;
878
+ let confidence = 0;
879
+ let distance = 0;
880
+ const dimCountA = descriptorA.dimensions.length;
881
+ const dimCountB = descriptorB.dimensions.length;
882
+ const descriptorDimensions = Math.min(dimCountA, dimCountB);
883
+ if (descriptorDimensions < cfg.minDimensions) {
884
+ return {
885
+ trustEstablished: false,
886
+ confidence: 0,
887
+ distance: Infinity,
888
+ threshold: cfg.threshold,
889
+ descriptorDimensions,
890
+ matchDetails: [],
891
+ auditToken: generateAuditToken({ descriptorA, descriptorB, error: "insufficient_dimensions" }),
892
+ timestamp
893
+ };
894
+ }
895
+ if (cfg.requireAllDimensions && dimCountA !== dimCountB) {
896
+ return {
897
+ trustEstablished: false,
898
+ confidence: 0,
899
+ distance: Infinity,
900
+ threshold: cfg.threshold,
901
+ descriptorDimensions,
902
+ matchDetails: [],
903
+ auditToken: generateAuditToken({ descriptorA, descriptorB, error: "dimension_mismatch" }),
904
+ timestamp
905
+ };
906
+ }
907
+ const timeA = new Date(descriptorA.timestamp).getTime();
908
+ const timeB = new Date(descriptorB.timestamp).getTime();
909
+ const timeDelta = Math.abs(timeA - timeB);
910
+ if (timeDelta > cfg.maxTimeDeltaMs) {
911
+ return {
912
+ trustEstablished: false,
913
+ confidence: 0,
914
+ distance: Infinity,
915
+ threshold: cfg.threshold,
916
+ descriptorDimensions,
917
+ matchDetails: [],
918
+ auditToken: generateAuditToken({ descriptorA, descriptorB, error: "time_delta_exceeded" }),
919
+ timestamp
920
+ };
921
+ }
922
+ for (let i = 0; i < descriptorDimensions; i++) {
923
+ const delta = Math.abs(descriptorA.dimensions[i] - descriptorB.dimensions[i]);
924
+ const withinTolerance = delta < cfg.threshold;
925
+ matchDetails.push({
926
+ dimension: i,
927
+ delta,
928
+ withinTolerance
929
+ });
930
+ }
931
+ const truncatedA = descriptorA.dimensions.slice(0, descriptorDimensions);
932
+ const truncatedB = descriptorB.dimensions.slice(0, descriptorDimensions);
933
+ distance = computeDistance(truncatedA, truncatedB);
934
+ confidence = computeSimilarity(truncatedA, truncatedB);
935
+ trustEstablished = confidence >= cfg.threshold;
936
+ return {
937
+ trustEstablished,
938
+ confidence,
939
+ distance,
940
+ threshold: cfg.threshold,
941
+ descriptorDimensions,
942
+ matchDetails,
943
+ auditToken: generateAuditToken({
944
+ descriptorA,
945
+ descriptorB,
946
+ trustEstablished,
947
+ confidence,
948
+ distance
949
+ }),
950
+ timestamp
951
+ };
952
+ }
953
+ function generateAuditToken(data) {
954
+ const input = JSON.stringify(data);
955
+ let hash = 0;
956
+ for (let i = 0; i < input.length; i++) {
957
+ const char = input.charCodeAt(i);
958
+ hash = (hash << 5) - hash + char;
959
+ hash = hash & hash;
960
+ }
961
+ return Math.abs(hash).toString(16).padStart(8, "0");
962
+ }
963
+
964
+ // src/m2m/p2p-protocol.ts
965
+ function generateNonce() {
966
+ return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
967
+ }
968
+ function createHandshakeInit(deviceId, publicKey, assetId, supportedAlgorithms = ["ed25519"]) {
969
+ const payload = {
970
+ deviceId,
971
+ publicKey,
972
+ supportedAlgorithms,
973
+ assetId
974
+ };
975
+ return {
976
+ type: "handshake_init",
977
+ version: "1.0",
978
+ senderId: deviceId,
979
+ payload,
980
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
981
+ nonce: generateNonce()
982
+ };
983
+ }
984
+ function createHandshakeAccept(initMessage, deviceId, publicKey, selectedAlgorithm = "ed25519") {
985
+ const initPayload = initMessage.payload;
986
+ const payload = {
987
+ deviceId,
988
+ publicKey,
989
+ selectedAlgorithm,
990
+ assetId: initPayload.assetId
991
+ };
992
+ return {
993
+ type: "handshake_accept",
994
+ version: "1.0",
995
+ senderId: deviceId,
996
+ recipientId: initMessage.senderId,
997
+ payload,
998
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
999
+ nonce: generateNonce()
1000
+ };
1001
+ }
1002
+ function createDescriptorExchange(deviceId, descriptor, assetId, captureId, recipientId) {
1003
+ const payload = {
1004
+ descriptor,
1005
+ assetId,
1006
+ captureId: captureId || generateNonce()
1007
+ };
1008
+ return {
1009
+ type: "descriptor_exchange",
1010
+ version: "1.0",
1011
+ senderId: deviceId,
1012
+ recipientId,
1013
+ payload,
1014
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1015
+ nonce: generateNonce()
1016
+ };
1017
+ }
1018
+ function createConsensusResultMessage(deviceId, result, agreedByBoth = true, recipientId) {
1019
+ const payload = {
1020
+ consensusResult: result,
1021
+ agreedByBoth
1022
+ };
1023
+ return {
1024
+ type: "consensus_result",
1025
+ version: "1.0",
1026
+ senderId: deviceId,
1027
+ recipientId,
1028
+ payload,
1029
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1030
+ nonce: generateNonce()
1031
+ };
1032
+ }
1033
+ function validateMessage(message) {
1034
+ const errors = [];
1035
+ if (!message.type) {
1036
+ errors.push({ field: "type", error: "Message type is required" });
1037
+ } else if (!["handshake_init", "handshake_accept", "descriptor_exchange", "consensus_result", "error"].includes(message.type)) {
1038
+ errors.push({ field: "type", error: "Invalid message type" });
1039
+ }
1040
+ if (message.version !== "1.0") {
1041
+ errors.push({ field: "version", error: "Unsupported protocol version" });
1042
+ }
1043
+ if (!message.senderId) {
1044
+ errors.push({ field: "senderId", error: "Sender ID is required" });
1045
+ }
1046
+ if (!message.payload) {
1047
+ errors.push({ field: "payload", error: "Payload is required" });
1048
+ }
1049
+ if (!message.timestamp) {
1050
+ errors.push({ field: "timestamp", error: "Timestamp is required" });
1051
+ } else {
1052
+ const date = new Date(message.timestamp);
1053
+ if (isNaN(date.getTime())) {
1054
+ errors.push({ field: "timestamp", error: "Invalid timestamp format" });
1055
+ }
1056
+ }
1057
+ if (!message.nonce) {
1058
+ errors.push({ field: "nonce", error: "Nonce is required" });
1059
+ }
1060
+ if (message.type === "handshake_init") {
1061
+ const payload = message.payload;
1062
+ if (!payload.deviceId) errors.push({ field: "payload.deviceId", error: "Device ID is required" });
1063
+ if (!payload.publicKey) errors.push({ field: "payload.publicKey", error: "Public key is required" });
1064
+ if (!Array.isArray(payload.supportedAlgorithms)) {
1065
+ errors.push({ field: "payload.supportedAlgorithms", error: "Supported algorithms must be an array" });
1066
+ }
1067
+ if (!payload.assetId) errors.push({ field: "payload.assetId", error: "Asset ID is required" });
1068
+ } else if (message.type === "handshake_accept") {
1069
+ const payload = message.payload;
1070
+ if (!payload.deviceId) errors.push({ field: "payload.deviceId", error: "Device ID is required" });
1071
+ if (!payload.publicKey) errors.push({ field: "payload.publicKey", error: "Public key is required" });
1072
+ if (!payload.selectedAlgorithm) errors.push({ field: "payload.selectedAlgorithm", error: "Selected algorithm is required" });
1073
+ if (!payload.assetId) errors.push({ field: "payload.assetId", error: "Asset ID is required" });
1074
+ } else if (message.type === "descriptor_exchange") {
1075
+ const payload = message.payload;
1076
+ if (!payload.descriptor) errors.push({ field: "payload.descriptor", error: "Descriptor is required" });
1077
+ if (!payload.assetId) errors.push({ field: "payload.assetId", error: "Asset ID is required" });
1078
+ if (!payload.captureId) errors.push({ field: "payload.captureId", error: "Capture ID is required" });
1079
+ } else if (message.type === "consensus_result") {
1080
+ const payload = message.payload;
1081
+ if (!payload.consensusResult) errors.push({ field: "payload.consensusResult", error: "Consensus result is required" });
1082
+ } else if (message.type === "error") {
1083
+ const payload = message.payload;
1084
+ if (!payload.code) errors.push({ field: "payload.code", error: "Error code is required" });
1085
+ if (!payload.message) errors.push({ field: "payload.message", error: "Error message is required" });
1086
+ }
1087
+ return {
1088
+ valid: errors.length === 0,
1089
+ errors
1090
+ };
1091
+ }
1092
+ function serializeMessage(message) {
1093
+ const json = JSON.stringify(message);
1094
+ try {
1095
+ return btoa(json);
1096
+ } catch {
1097
+ if (typeof globalThis.Buffer !== "undefined") {
1098
+ return globalThis.Buffer.from(json).toString("base64");
1099
+ }
1100
+ throw new Error("No base64 encoder available");
1101
+ }
1102
+ }
1103
+ function deserializeMessage(data) {
1104
+ let json;
1105
+ try {
1106
+ try {
1107
+ json = atob(data);
1108
+ } catch {
1109
+ if (typeof globalThis.Buffer !== "undefined") {
1110
+ json = globalThis.Buffer.from(data, "base64").toString("utf-8");
1111
+ } else {
1112
+ throw new Error("Failed to decode base64 message");
1113
+ }
1114
+ }
1115
+ } catch {
1116
+ throw new Error("Failed to decode base64 message");
1117
+ }
1118
+ try {
1119
+ return JSON.parse(json);
1120
+ } catch {
1121
+ throw new Error("Failed to parse message JSON");
1122
+ }
1123
+ }
1124
+
1125
+ // src/m2m/audit-trail.ts
1126
+ function simpleHash(data) {
1127
+ let hash = 0;
1128
+ for (let i = 0; i < data.length; i++) {
1129
+ const char = data.charCodeAt(i);
1130
+ hash = (hash << 5) - hash + char;
1131
+ hash = hash & hash;
1132
+ }
1133
+ return Math.abs(hash).toString(16).padStart(16, "0");
1134
+ }
1135
+ function generateRecordId() {
1136
+ return `rec_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1137
+ }
1138
+ async function computeRecordHash(record) {
1139
+ const data = JSON.stringify({
1140
+ id: record.id,
1141
+ type: record.type,
1142
+ assetId: record.assetId,
1143
+ deviceIds: record.deviceIds,
1144
+ timestamp: record.timestamp,
1145
+ previousHash: record.previousHash,
1146
+ data: record.data
1147
+ });
1148
+ if (typeof globalThis !== "undefined" && globalThis.crypto?.subtle) {
1149
+ try {
1150
+ const encoder = new TextEncoder();
1151
+ const hashBuffer = await globalThis.crypto.subtle.digest("SHA-256", encoder.encode(data));
1152
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
1153
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
1154
+ } catch {
1155
+ return simpleHash(data);
1156
+ }
1157
+ }
1158
+ return simpleHash(data);
1159
+ }
1160
+ function createAuditChain(chainId) {
1161
+ return {
1162
+ records: [],
1163
+ chainId: chainId || `chain_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
1164
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1165
+ lastHash: "0"
1166
+ };
1167
+ }
1168
+ async function appendRecord(chain, type, assetId, deviceIds, data) {
1169
+ const record = {
1170
+ id: generateRecordId(),
1171
+ type,
1172
+ assetId,
1173
+ deviceIds,
1174
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1175
+ previousHash: chain.lastHash,
1176
+ data
1177
+ };
1178
+ const hash = await computeRecordHash(record);
1179
+ const auditRecord = {
1180
+ ...record,
1181
+ hash
1182
+ };
1183
+ chain.records.push(auditRecord);
1184
+ chain.lastHash = hash;
1185
+ return auditRecord;
1186
+ }
1187
+ async function verifyChain(chain) {
1188
+ if (chain.records.length === 0) {
1189
+ return { valid: true };
1190
+ }
1191
+ let previousHash = "0";
1192
+ for (let i = 0; i < chain.records.length; i++) {
1193
+ const record = chain.records[i];
1194
+ if (record.previousHash !== previousHash) {
1195
+ return {
1196
+ valid: false,
1197
+ brokenAt: i,
1198
+ error: `Chain broken at record ${i}: previousHash mismatch`
1199
+ };
1200
+ }
1201
+ const recordData = {
1202
+ id: record.id,
1203
+ type: record.type,
1204
+ assetId: record.assetId,
1205
+ deviceIds: record.deviceIds,
1206
+ timestamp: record.timestamp,
1207
+ previousHash: record.previousHash,
1208
+ data: record.data
1209
+ };
1210
+ const computedHash = await computeRecordHash(recordData);
1211
+ if (record.hash !== computedHash) {
1212
+ return {
1213
+ valid: false,
1214
+ brokenAt: i,
1215
+ error: `Chain broken at record ${i}: hash mismatch`
1216
+ };
1217
+ }
1218
+ previousHash = record.hash;
1219
+ }
1220
+ if (previousHash !== chain.lastHash) {
1221
+ return {
1222
+ valid: false,
1223
+ error: "Final record hash does not match chain lastHash"
1224
+ };
1225
+ }
1226
+ return { valid: true };
1227
+ }
1228
+ function exportChain(chain) {
1229
+ return JSON.stringify(chain, null, 2);
1230
+ }
1231
+ async function importChain(data) {
1232
+ try {
1233
+ const chain = JSON.parse(data);
1234
+ if (!chain.chainId) {
1235
+ throw new Error("Invalid chain: missing chainId");
1236
+ }
1237
+ if (!Array.isArray(chain.records)) {
1238
+ throw new Error("Invalid chain: records is not an array");
1239
+ }
1240
+ if (!chain.createdAt) {
1241
+ throw new Error("Invalid chain: missing createdAt");
1242
+ }
1243
+ if (!chain.lastHash) {
1244
+ throw new Error("Invalid chain: missing lastHash");
1245
+ }
1246
+ const verification = await verifyChain(chain);
1247
+ if (!verification.valid) {
1248
+ throw new Error(`Invalid chain: ${verification.error}`);
1249
+ }
1250
+ return chain;
1251
+ } catch (error) {
1252
+ if (error instanceof SyntaxError) {
1253
+ throw new Error("Failed to parse chain JSON");
1254
+ }
1255
+ throw error;
1256
+ }
1257
+ }
1258
+
1259
+ // src/resources/m2m.ts
1260
+ var M2MResource = class {
1261
+ constructor(request) {
1262
+ this.request = request;
1263
+ }
1264
+ request;
1265
+ /**
1266
+ * Initiate an M2M challenge for an asset.
1267
+ */
1268
+ async initiateChallenge(params) {
1269
+ return this.request({
1270
+ method: "POST",
1271
+ path: "/v1/m2m/challenge",
1272
+ body: {
1273
+ asset_id: params.assetId,
1274
+ algorithm: params.algorithm ?? "ed25519",
1275
+ ttl_seconds: params.ttlSeconds ?? 60
1276
+ }
1277
+ });
1278
+ }
1279
+ /**
1280
+ * Verify an M2M challenge response.
1281
+ */
1282
+ async verify(params) {
1283
+ return this.request({
1284
+ method: "POST",
1285
+ path: "/v1/m2m/verify",
1286
+ body: {
1287
+ challenge_id: params.challengeId,
1288
+ response: params.response,
1289
+ device_id: params.deviceId
1290
+ }
1291
+ });
1292
+ }
1293
+ /**
1294
+ * Register a verifier device.
1295
+ */
1296
+ async registerDevice(params) {
1297
+ return this.request({
1298
+ method: "POST",
1299
+ path: "/v1/m2m/devices",
1300
+ body: params
1301
+ });
1302
+ }
1303
+ /**
1304
+ * Get a verifier device by ID.
1305
+ */
1306
+ async getDevice(deviceId) {
1307
+ return this.request({
1308
+ method: "GET",
1309
+ path: `/v1/m2m/devices/${encodeURIComponent(deviceId)}`
1310
+ });
1311
+ }
1312
+ /**
1313
+ * List all registered verifier devices.
1314
+ */
1315
+ async listDevices() {
1316
+ const response = await this.request({
1317
+ method: "GET",
1318
+ path: "/v1/m2m/devices"
1319
+ });
1320
+ return response.data;
1321
+ }
1322
+ /**
1323
+ * Revoke a verifier device.
1324
+ */
1325
+ async revokeDevice(deviceId) {
1326
+ return this.request({
1327
+ method: "DELETE",
1328
+ path: `/v1/m2m/devices/${encodeURIComponent(deviceId)}`
1329
+ });
1330
+ }
1331
+ /**
1332
+ * Evaluate consensus between two physical descriptors (local operation, no API call)
1333
+ */
1334
+ consensus(descriptorA, descriptorB, config) {
1335
+ return evaluateConsensus(descriptorA, descriptorB, config);
1336
+ }
1337
+ /**
1338
+ * Create a new local audit trail (no API call)
1339
+ */
1340
+ createAuditTrail(chainId) {
1341
+ return createAuditChain(chainId);
1342
+ }
1343
+ /**
1344
+ * Verify audit trail integrity (local operation, no API call)
1345
+ */
1346
+ async verifyAuditTrail(chain) {
1347
+ return verifyChain(chain);
1348
+ }
1349
+ };
1350
+
694
1351
  // src/resources/provenance.ts
695
1352
  var ProvenanceResource = class {
696
1353
  constructor(request) {
697
1354
  this.request = request;
698
1355
  }
1356
+ request;
699
1357
  /**
700
1358
  * Record a new provenance event in the chain.
701
1359
  *
@@ -801,6 +1459,7 @@ var SchemasResource = class {
801
1459
  constructor(request) {
802
1460
  this.request = request;
803
1461
  }
1462
+ request;
804
1463
  /**
805
1464
  * Register or update a vertical config schema.
806
1465
  * If a schema already exists for the verticalId, it will be updated.
@@ -903,10 +1562,59 @@ var SchemasResource = class {
903
1562
  }
904
1563
  };
905
1564
 
1565
+ // src/resources/tenants.ts
1566
+ var TenantsResource = class {
1567
+ constructor(request) {
1568
+ this.request = request;
1569
+ }
1570
+ request;
1571
+ /**
1572
+ * Get information about the current tenant.
1573
+ */
1574
+ async getCurrent() {
1575
+ return this.request({ method: "GET", path: "/v1/tenant" });
1576
+ }
1577
+ /**
1578
+ * Get resource limits for the current tenant based on their plan.
1579
+ */
1580
+ async getLimits() {
1581
+ return this.request({ method: "GET", path: "/v1/tenant/limits" });
1582
+ }
1583
+ /**
1584
+ * Get usage metrics for a specified period.
1585
+ */
1586
+ async getUsage(params) {
1587
+ const query = params ? this.buildQuery(params) : "";
1588
+ return this.request({ method: "GET", path: `/v1/tenant/usage${query}` });
1589
+ }
1590
+ /**
1591
+ * Get usage metrics broken down by endpoint, key, or resource.
1592
+ */
1593
+ async getUsageBreakdown(params) {
1594
+ const query = params ? this.buildQuery(params) : "";
1595
+ const result = await this.request({
1596
+ method: "GET",
1597
+ path: `/v1/tenant/usage/breakdown${query}`
1598
+ });
1599
+ return result.data;
1600
+ }
1601
+ // ─────────────────────────────────────────────────────────────────────────
1602
+ // PRIVATE HELPERS
1603
+ // ─────────────────────────────────────────────────────────────────────────
1604
+ buildQuery(params) {
1605
+ const entries = Object.entries(params).filter(([, v]) => v !== void 0);
1606
+ if (entries.length === 0) return "";
1607
+ const qs = new URLSearchParams(
1608
+ entries.map(([k, v]) => [k, String(v)])
1609
+ );
1610
+ return `?${qs.toString()}`;
1611
+ }
1612
+ };
1613
+
906
1614
  // src/client.ts
907
1615
  var DEFAULT_BASE_URL = "https://api.optropic.com";
908
1616
  var DEFAULT_TIMEOUT = 3e4;
909
- var SDK_VERSION = "2.3.0";
1617
+ var SDK_VERSION = "2.5.0";
910
1618
  var SANDBOX_PREFIXES = ["optr_test_"];
911
1619
  var DEFAULT_RETRY_CONFIG = {
912
1620
  maxRetries: 3,
@@ -920,14 +1628,18 @@ var OptropicClient = class {
920
1628
  retryConfig;
921
1629
  _sandbox;
922
1630
  _debug;
1631
+ _rateLimit = null;
923
1632
  assets;
924
1633
  audit;
1634
+ batches;
925
1635
  compliance;
926
1636
  documents;
927
1637
  keys;
928
1638
  keysets;
1639
+ m2m;
929
1640
  provenance;
930
1641
  schemas;
1642
+ tenants;
931
1643
  constructor(config) {
932
1644
  if (!config.apiKey || !this.isValidApiKey(config.apiKey)) {
933
1645
  throw new AuthenticationError(
@@ -956,12 +1668,15 @@ var OptropicClient = class {
956
1668
  const boundRequest = this.request.bind(this);
957
1669
  this.assets = new AssetsResource(boundRequest, this);
958
1670
  this.audit = new AuditResource(boundRequest);
1671
+ this.batches = new BatchesResource(boundRequest);
959
1672
  this.compliance = new ComplianceResource(boundRequest);
960
1673
  this.documents = new DocumentsResource(boundRequest);
961
1674
  this.keys = new KeysResource(boundRequest);
962
1675
  this.keysets = new KeysetsResource(boundRequest);
1676
+ this.m2m = new M2MResource(boundRequest);
963
1677
  this.provenance = new ProvenanceResource(boundRequest);
964
1678
  this.schemas = new SchemasResource(boundRequest);
1679
+ this.tenants = new TenantsResource(boundRequest);
965
1680
  }
966
1681
  // ─────────────────────────────────────────────────────────────────────────
967
1682
  // ENVIRONMENT DETECTION
@@ -978,6 +1693,22 @@ var OptropicClient = class {
978
1693
  get environment() {
979
1694
  return this._sandbox ? "sandbox" : "live";
980
1695
  }
1696
+ /** Last known rate limit status, updated after every API call. Returns null until the first request. */
1697
+ get rateLimit() {
1698
+ return this._rateLimit;
1699
+ }
1700
+ /**
1701
+ * Get quota information for the current API key.
1702
+ * Based on the last known rate limit from previous API calls.
1703
+ */
1704
+ getQuota() {
1705
+ return {
1706
+ limit: this._rateLimit?.limit ?? 0,
1707
+ remaining: this._rateLimit?.remaining ?? 0,
1708
+ reset: this._rateLimit?.reset,
1709
+ resetAt: this._rateLimit?.reset
1710
+ };
1711
+ }
981
1712
  // ─────────────────────────────────────────────────────────────────────────
982
1713
  // DEBUG LOGGING
983
1714
  // ─────────────────────────────────────────────────────────────────────────
@@ -1090,6 +1821,15 @@ var OptropicClient = class {
1090
1821
  const durationMs = performance.now() - t0;
1091
1822
  const serverRequestId = response.headers.get("x-request-id") ?? "";
1092
1823
  this.logResponse(method, path, response.status, durationMs, requestId, serverRequestId, attempt);
1824
+ const rlLimit = response.headers.get("x-ratelimit-limit");
1825
+ const rlRemaining = response.headers.get("x-ratelimit-remaining");
1826
+ if (rlLimit !== null || rlRemaining !== null) {
1827
+ this._rateLimit = {
1828
+ limit: rlLimit ? parseInt(rlLimit, 10) : 0,
1829
+ remaining: rlRemaining ? parseInt(rlRemaining, 10) : 0,
1830
+ reset: response.headers.get("x-ratelimit-reset") ?? void 0
1831
+ };
1832
+ }
1093
1833
  if (!response.ok) {
1094
1834
  let errorBody;
1095
1835
  try {
@@ -1159,6 +1899,39 @@ function createClient(config) {
1159
1899
  return new OptropicClient(config);
1160
1900
  }
1161
1901
 
1902
+ // src/types.ts
1903
+ var Permission = {
1904
+ ASSETS_READ: "assets:read",
1905
+ ASSETS_WRITE: "assets:write",
1906
+ ASSETS_VERIFY: "assets:verify",
1907
+ AUDIT_READ: "audit:read",
1908
+ COMPLIANCE_READ: "compliance:read",
1909
+ KEYS_MANAGE: "keys:manage",
1910
+ SCHEMAS_MANAGE: "schemas:manage",
1911
+ DOCUMENTS_ENROLL: "documents:enroll",
1912
+ DOCUMENTS_VERIFY: "documents:verify",
1913
+ PROVENANCE_READ: "provenance:read",
1914
+ PROVENANCE_WRITE: "provenance:write",
1915
+ WEBHOOKS_MANAGE: "webhooks:manage",
1916
+ /** All read permissions. */
1917
+ ALL_READ: ["assets:read", "audit:read", "compliance:read", "provenance:read"],
1918
+ /** All write permissions. */
1919
+ ALL_WRITE: [
1920
+ "assets:write",
1921
+ "assets:verify",
1922
+ "documents:enroll",
1923
+ "documents:verify",
1924
+ "provenance:write",
1925
+ "webhooks:manage",
1926
+ "keys:manage",
1927
+ "schemas:manage"
1928
+ ],
1929
+ /** All permissions combined. */
1930
+ all() {
1931
+ return [...this.ALL_READ, ...this.ALL_WRITE];
1932
+ }
1933
+ };
1934
+
1162
1935
  // src/filter-verify.ts
1163
1936
  var HEADER_SIZE = 19;
1164
1937
  var SIGNATURE_SIZE = 64;
@@ -1355,6 +2128,594 @@ function validateDPPMetadata(metadata) {
1355
2128
  }
1356
2129
  return { valid: errors.length === 0, errors };
1357
2130
  }
2131
+ function validateBatteryPassport(data) {
2132
+ const errors = [];
2133
+ const warnings = [];
2134
+ if (!data.manufacturerIdentification) {
2135
+ errors.push("manufacturerIdentification is required (Annex XIII)");
2136
+ }
2137
+ if (!data.manufacturingDate) {
2138
+ errors.push("manufacturingDate is required (Annex XIII)");
2139
+ } else if (!/^\d{4}-\d{2}-\d{2}/.test(data.manufacturingDate)) {
2140
+ errors.push("manufacturingDate must be in ISO 8601 format (YYYY-MM-DD)");
2141
+ }
2142
+ if (!data.manufacturingPlace) {
2143
+ errors.push("manufacturingPlace is required (Annex XIII)");
2144
+ }
2145
+ if (data.batteryWeight === void 0 || data.batteryWeight <= 0) {
2146
+ errors.push("batteryWeight must be a positive number (Annex XIII)");
2147
+ }
2148
+ if (!data.batteryStatus) {
2149
+ errors.push("batteryStatus is required (Annex XIII)");
2150
+ } else if (!["original", "repurposed", "remanufactured", "waste"].includes(data.batteryStatus)) {
2151
+ errors.push(
2152
+ "batteryStatus must be one of: original, repurposed, remanufactured, waste (Annex XIII)"
2153
+ );
2154
+ }
2155
+ if (data.ratedCapacityAh === void 0 || data.ratedCapacityAh <= 0) {
2156
+ errors.push("ratedCapacityAh must be a positive number (Annex XIII)");
2157
+ }
2158
+ if (data.voltageMinV === void 0 || data.voltageMinV < 0) {
2159
+ errors.push("voltageMinV must be a non-negative number (Annex XIII)");
2160
+ }
2161
+ if (data.voltageMaxV === void 0 || data.voltageMaxV < 0) {
2162
+ errors.push("voltageMaxV must be a non-negative number (Annex XIII)");
2163
+ }
2164
+ if (data.voltageNominalV === void 0 || data.voltageNominalV < 0) {
2165
+ errors.push("voltageNominalV must be a non-negative number (Annex XIII)");
2166
+ }
2167
+ if (data.voltageMinV !== void 0 && data.voltageMaxV !== void 0 && data.voltageMinV > data.voltageMaxV) {
2168
+ errors.push("voltageMinV must be less than or equal to voltageMaxV");
2169
+ }
2170
+ if (data.temperatureRangeMinC === void 0) {
2171
+ errors.push("temperatureRangeMinC is required (Annex XIII)");
2172
+ }
2173
+ if (data.temperatureRangeMaxC === void 0) {
2174
+ errors.push("temperatureRangeMaxC is required (Annex XIII)");
2175
+ }
2176
+ if (data.temperatureRangeMinC !== void 0 && data.temperatureRangeMaxC !== void 0 && data.temperatureRangeMinC > data.temperatureRangeMaxC) {
2177
+ errors.push("temperatureRangeMinC must be less than or equal to temperatureRangeMaxC");
2178
+ }
2179
+ if (data.originalPowerCapabilityW === void 0 || data.originalPowerCapabilityW < 0) {
2180
+ errors.push("originalPowerCapabilityW must be a non-negative number (Annex XIII)");
2181
+ }
2182
+ if (data.roundTripEfficiency === void 0 || data.roundTripEfficiency < 0 || data.roundTripEfficiency > 100) {
2183
+ errors.push("roundTripEfficiency must be between 0 and 100 (Annex XIII)");
2184
+ }
2185
+ if (data.internalResistanceOhm === void 0 || data.internalResistanceOhm < 0) {
2186
+ errors.push("internalResistanceOhm must be a non-negative number (Annex XIII)");
2187
+ }
2188
+ if (!data.cellChemistryDetail) {
2189
+ errors.push("cellChemistryDetail is required (Annex XIII)");
2190
+ }
2191
+ if (!data.hazardousSubstances || !Array.isArray(data.hazardousSubstances)) {
2192
+ errors.push("hazardousSubstances must be an array (Annex XIII)");
2193
+ }
2194
+ if (data.carbonFootprintPerKwh === void 0 || data.carbonFootprintPerKwh < 0) {
2195
+ errors.push("carbonFootprintPerKwh must be a non-negative number (Annex XIII)");
2196
+ }
2197
+ if (!data.carbonFootprintStudyUrl) {
2198
+ errors.push("carbonFootprintStudyUrl is required (Annex XIII)");
2199
+ } else if (!isValidUrl(data.carbonFootprintStudyUrl)) {
2200
+ warnings.push("carbonFootprintStudyUrl appears to be invalid");
2201
+ }
2202
+ if (!data.supplyChainDueDiligencePolicy) {
2203
+ errors.push("supplyChainDueDiligencePolicy is required (Annex XIII)");
2204
+ } else if (!isValidUrl(data.supplyChainDueDiligencePolicy)) {
2205
+ warnings.push("supplyChainDueDiligencePolicy appears to be invalid");
2206
+ }
2207
+ if (!data.thirdPartyVerifierId) {
2208
+ errors.push("thirdPartyVerifierId is required (Annex XIII)");
2209
+ }
2210
+ if (!data.dismantlingInstructions) {
2211
+ errors.push("dismantlingInstructions is required (Annex XIII)");
2212
+ } else if (!isValidUrl(data.dismantlingInstructions)) {
2213
+ warnings.push("dismantlingInstructions appears to be invalid");
2214
+ }
2215
+ if (!data.safetyInstructions) {
2216
+ errors.push("safetyInstructions is required (Annex XIII)");
2217
+ } else if (!isValidUrl(data.safetyInstructions)) {
2218
+ warnings.push("safetyInstructions appears to be invalid");
2219
+ }
2220
+ if (!data.extinguishingAgent) {
2221
+ errors.push("extinguishingAgent is required (Annex XIII)");
2222
+ }
2223
+ if (data.chemistry && !data.cellChemistryDetail) {
2224
+ warnings.push("cellChemistryDetail should provide more detail than chemistry type");
2225
+ }
2226
+ if (data.hazardousSubstances && data.hazardousSubstances.length === 0) {
2227
+ warnings.push("hazardousSubstances array is empty; all batteries contain some hazardous materials");
2228
+ }
2229
+ return {
2230
+ valid: errors.length === 0,
2231
+ errors,
2232
+ warnings
2233
+ };
2234
+ }
2235
+ function buildBatteryPassportQR(metadata) {
2236
+ if (!metadata.productId) {
2237
+ throw new Error("productId is required to build battery passport QR");
2238
+ }
2239
+ let serialNumber;
2240
+ if (metadata.sectorData && "type" in metadata.sectorData && metadata.sectorData.type === "battery") {
2241
+ }
2242
+ let uri = `https://id.gs1.org/01/${metadata.productId}`;
2243
+ if (serialNumber) {
2244
+ uri += `/21/${serialNumber}`;
2245
+ }
2246
+ return uri;
2247
+ }
2248
+ function isValidUrl(urlString) {
2249
+ try {
2250
+ new URL(urlString);
2251
+ return true;
2252
+ } catch {
2253
+ return false;
2254
+ }
2255
+ }
2256
+
2257
+ // src/gs1-resolver.ts
2258
+ var DEFAULT_GS1_DOMAIN = "https://id.gs1.org";
2259
+ var AI_LABELS = {
2260
+ "01": "GTIN",
2261
+ "21": "Serial Number",
2262
+ "10": "Batch/Lot Number",
2263
+ "11": "Production Date",
2264
+ "17": "Expiry Date",
2265
+ "3103": "Net Weight (kg)",
2266
+ "3922": "Price",
2267
+ "8200": "URL",
2268
+ "254": "Extension",
2269
+ "414": "Global Location Number"
2270
+ };
2271
+ function validateGTIN(gtin) {
2272
+ const cleaned = gtin.replace(/\D/g, "");
2273
+ if (![8, 12, 13, 14].includes(cleaned.length)) {
2274
+ return {
2275
+ valid: false,
2276
+ checkDigit: -1,
2277
+ message: `Invalid GTIN length: ${cleaned.length}. Must be 8, 12, 13, or 14 digits.`
2278
+ };
2279
+ }
2280
+ const digits = cleaned.split("").map(Number);
2281
+ const checkDigitProvided = digits[digits.length - 1];
2282
+ const contentDigits = digits.slice(0, -1);
2283
+ let sum = 0;
2284
+ let multiplier = 3;
2285
+ for (let i = contentDigits.length - 1; i >= 0; i--) {
2286
+ sum += contentDigits[i] * multiplier;
2287
+ multiplier = multiplier === 3 ? 1 : 3;
2288
+ }
2289
+ const checkDigitCalculated = (10 - sum % 10) % 10;
2290
+ const valid = checkDigitCalculated === checkDigitProvided;
2291
+ return {
2292
+ valid,
2293
+ checkDigit: checkDigitCalculated,
2294
+ message: valid ? `Valid GTIN check digit: ${checkDigitCalculated}` : `Invalid check digit. Expected ${checkDigitCalculated}, got ${checkDigitProvided}`
2295
+ };
2296
+ }
2297
+ function parseGS1DigitalLink(uri) {
2298
+ const url = new URL(uri);
2299
+ const domain = `${url.protocol}//${url.hostname}`;
2300
+ const pathname = url.pathname;
2301
+ const allComponents = [];
2302
+ let gtin;
2303
+ let serialNumber;
2304
+ let batchLot;
2305
+ let productionDate;
2306
+ let expiryDate;
2307
+ let netWeightKg;
2308
+ let price;
2309
+ let urlValue;
2310
+ let gln;
2311
+ let extension;
2312
+ let queryParams;
2313
+ const pathParts = pathname.split("/").filter((p) => p);
2314
+ let i = 0;
2315
+ while (i < pathParts.length - 1) {
2316
+ const ai = pathParts[i];
2317
+ const value = pathParts[i + 1];
2318
+ const label = AI_LABELS[ai] || `AI ${ai}`;
2319
+ allComponents.push({ ai, value, label });
2320
+ switch (ai) {
2321
+ case "01":
2322
+ gtin = value;
2323
+ break;
2324
+ case "21":
2325
+ serialNumber = value;
2326
+ break;
2327
+ case "10":
2328
+ batchLot = value;
2329
+ break;
2330
+ case "11":
2331
+ productionDate = parseGS1Date(value);
2332
+ break;
2333
+ case "17":
2334
+ expiryDate = parseGS1Date(value);
2335
+ break;
2336
+ case "3103":
2337
+ netWeightKg = parseFloat(value);
2338
+ break;
2339
+ case "3922":
2340
+ price = value;
2341
+ break;
2342
+ case "8200":
2343
+ urlValue = value;
2344
+ break;
2345
+ case "414":
2346
+ gln = value;
2347
+ break;
2348
+ case "254":
2349
+ extension = value;
2350
+ break;
2351
+ }
2352
+ i += 2;
2353
+ }
2354
+ const params = {};
2355
+ url.searchParams.forEach((value, key) => {
2356
+ params[key] = value;
2357
+ });
2358
+ if (Object.keys(params).length > 0) {
2359
+ queryParams = params;
2360
+ }
2361
+ const result = {
2362
+ domain,
2363
+ gtin,
2364
+ serialNumber,
2365
+ batchLot,
2366
+ productionDate,
2367
+ expiryDate,
2368
+ netWeightKg,
2369
+ price,
2370
+ url: urlValue,
2371
+ gln,
2372
+ extension,
2373
+ allComponents,
2374
+ queryParams
2375
+ };
2376
+ return result;
2377
+ }
2378
+ function buildGS1DigitalLink(input) {
2379
+ const domain = input.domain || DEFAULT_GS1_DOMAIN;
2380
+ const parts = [];
2381
+ if (!input.gtin) {
2382
+ throw new Error("GTIN is required to build a GS1 Digital Link URI");
2383
+ }
2384
+ const validation = validateGTIN(input.gtin);
2385
+ if (!validation.valid) {
2386
+ throw new Error(`Invalid GTIN: ${validation.message}`);
2387
+ }
2388
+ parts.push("01", input.gtin);
2389
+ if (input.serialNumber) {
2390
+ parts.push("21", input.serialNumber);
2391
+ }
2392
+ if (input.batchLot) {
2393
+ parts.push("10", input.batchLot);
2394
+ }
2395
+ if (input.productionDate) {
2396
+ parts.push("11", formatGS1Date(input.productionDate));
2397
+ }
2398
+ if (input.expiryDate) {
2399
+ parts.push("17", formatGS1Date(input.expiryDate));
2400
+ }
2401
+ if (input.netWeightKg !== void 0) {
2402
+ parts.push("3103", input.netWeightKg.toString());
2403
+ }
2404
+ if (input.price) {
2405
+ parts.push("3922", input.price);
2406
+ }
2407
+ if (input.url) {
2408
+ parts.push("8200", input.url);
2409
+ }
2410
+ if (input.gln) {
2411
+ parts.push("414", input.gln);
2412
+ }
2413
+ if (input.extension) {
2414
+ parts.push("254", input.extension);
2415
+ }
2416
+ let uri = `${domain}/${parts.join("/")}`;
2417
+ if (input.queryParams && Object.keys(input.queryParams).length > 0) {
2418
+ const params = new URLSearchParams(input.queryParams);
2419
+ uri += `?${params.toString()}`;
2420
+ }
2421
+ return uri;
2422
+ }
2423
+ function mapToOptropicAsset(parsed) {
2424
+ if (!parsed.gtin) {
2425
+ throw new Error("GTIN is required for Optropic asset mapping");
2426
+ }
2427
+ let lookupQuery = `gtin:"${parsed.gtin}"`;
2428
+ if (parsed.serialNumber) {
2429
+ lookupQuery += ` AND serial:"${parsed.serialNumber}"`;
2430
+ }
2431
+ if (parsed.batchLot) {
2432
+ lookupQuery += ` AND batch:"${parsed.batchLot}"`;
2433
+ }
2434
+ const lookup = {
2435
+ productId: parsed.gtin,
2436
+ serialNumber: parsed.serialNumber,
2437
+ batchId: parsed.batchLot,
2438
+ lookupQuery
2439
+ };
2440
+ return lookup;
2441
+ }
2442
+ function generateQRCodePayload(input) {
2443
+ const uri = buildGS1DigitalLink(input);
2444
+ return {
2445
+ type: "gs1-digital-link",
2446
+ data: uri,
2447
+ encodingMode: "url"
2448
+ };
2449
+ }
2450
+ function isValidAI(ai) {
2451
+ return Object.prototype.hasOwnProperty.call(AI_LABELS, ai);
2452
+ }
2453
+ function getAILabel(ai) {
2454
+ return AI_LABELS[ai];
2455
+ }
2456
+ function getSupportedAIs() {
2457
+ return Object.keys(AI_LABELS);
2458
+ }
2459
+ function parseGS1Date(gs1Date) {
2460
+ if (gs1Date.length !== 6) {
2461
+ return gs1Date;
2462
+ }
2463
+ const yy = parseInt(gs1Date.substring(0, 2), 10);
2464
+ const mm = gs1Date.substring(2, 4);
2465
+ const dd = gs1Date.substring(4, 6);
2466
+ const yyyy = 2e3 + yy;
2467
+ return `${yyyy}-${mm}-${dd}`;
2468
+ }
2469
+ function formatGS1Date(isoDate) {
2470
+ let cleaned = isoDate.replace(/-/g, "");
2471
+ if (cleaned.length !== 8) {
2472
+ return isoDate;
2473
+ }
2474
+ const yyyy = cleaned.substring(0, 4);
2475
+ const mm = cleaned.substring(4, 6);
2476
+ const dd = cleaned.substring(6, 8);
2477
+ const yy = (parseInt(yyyy, 10) % 100).toString().padStart(2, "0");
2478
+ return `${yy}${mm}${dd}`;
2479
+ }
2480
+
2481
+ // src/dpp-access.ts
2482
+ var DPPAccessLevel = {
2483
+ /** Consumer-facing public data. */
2484
+ PUBLIC: "public",
2485
+ /** Verified supply chain partner. */
2486
+ AUTHENTICATED: "authenticated",
2487
+ /** Market surveillance authority. */
2488
+ REGULATORY: "regulatory",
2489
+ /** Economic operator (data owner). */
2490
+ OWNER: "owner",
2491
+ /**
2492
+ * Check if a level has at least the privilege of another.
2493
+ * Useful for authorization checks.
2494
+ *
2495
+ * @example
2496
+ * ```typescript
2497
+ * DPPAccessLevel.isAtLeast('regulatory', 'authenticated'); // true
2498
+ * DPPAccessLevel.isAtLeast('public', 'regulatory'); // false
2499
+ * ```
2500
+ */
2501
+ isAtLeast(level, required) {
2502
+ return LEVEL_RANK[level] >= LEVEL_RANK[required];
2503
+ }
2504
+ };
2505
+ var LEVEL_RANK = {
2506
+ public: 0,
2507
+ authenticated: 1,
2508
+ regulatory: 2,
2509
+ owner: 3
2510
+ };
2511
+ var DEFAULT_FIELD_VISIBILITY = [
2512
+ // ── Public fields ─────────────────────────────────────────────────────
2513
+ { field: "productId", minLevel: "public" },
2514
+ { field: "productName", minLevel: "public" },
2515
+ { field: "manufacturer", minLevel: "public" },
2516
+ { field: "countryOfOrigin", minLevel: "public" },
2517
+ { field: "category", minLevel: "public" },
2518
+ { field: "carbonFootprint", minLevel: "public" },
2519
+ { field: "recycledContent", minLevel: "public" },
2520
+ { field: "durabilityYears", minLevel: "public" },
2521
+ { field: "repairabilityScore", minLevel: "public" },
2522
+ { field: "dppRegistryId", minLevel: "public" },
2523
+ // ── Authenticated fields ──────────────────────────────────────────────
2524
+ {
2525
+ field: "substancesOfConcern",
2526
+ minLevel: "authenticated",
2527
+ // Battery regulation requires public disclosure of substances
2528
+ categoryOverride: { battery: "public" }
2529
+ },
2530
+ { field: "conformityDeclarations", minLevel: "authenticated" },
2531
+ {
2532
+ field: "sectorData",
2533
+ minLevel: "authenticated",
2534
+ // Battery basic data (chemistry, capacity) is public per Battery Regulation Art. 13
2535
+ categoryOverride: { battery: "public" }
2536
+ },
2537
+ // ── Regulatory fields ─────────────────────────────────────────────────
2538
+ // (These map to DPPMetadata extensions that may be added; included for future-proofing)
2539
+ { field: "internalBatchId", minLevel: "regulatory" },
2540
+ { field: "auditTrailRef", minLevel: "regulatory" },
2541
+ { field: "manufacturingDate", minLevel: "regulatory" },
2542
+ { field: "facilityId", minLevel: "regulatory" },
2543
+ // ── Owner-only fields ─────────────────────────────────────────────────
2544
+ { field: "costData", minLevel: "owner" },
2545
+ { field: "supplierContracts", minLevel: "owner" },
2546
+ { field: "internalNotes", minLevel: "owner" }
2547
+ ];
2548
+ function getDPPAccessPolicy(overrides) {
2549
+ const fields = overrides ?? DEFAULT_FIELD_VISIBILITY;
2550
+ return {
2551
+ defaultLevel: "public",
2552
+ fields,
2553
+ redactionMode: "omit"
2554
+ };
2555
+ }
2556
+ function filterDPPByAccess(metadata, context, policy) {
2557
+ const effectivePolicy = policy ?? getDPPAccessPolicy();
2558
+ const result = {};
2559
+ const showRedacted = context.showRedacted ?? effectivePolicy.redactionMode === "placeholder";
2560
+ for (const [key, value] of Object.entries(metadata)) {
2561
+ const rule = effectivePolicy.fields.find((f) => f.field === key);
2562
+ if (!rule) {
2563
+ if (DPPAccessLevel.isAtLeast(context.level, "owner")) {
2564
+ result[key] = value;
2565
+ } else if (showRedacted) {
2566
+ result[key] = "[REDACTED]";
2567
+ }
2568
+ continue;
2569
+ }
2570
+ let effectiveMinLevel = rule.minLevel;
2571
+ if (context.category && rule.categoryOverride?.[context.category]) {
2572
+ effectiveMinLevel = rule.categoryOverride[context.category];
2573
+ }
2574
+ if (DPPAccessLevel.isAtLeast(context.level, effectiveMinLevel)) {
2575
+ result[key] = value;
2576
+ } else if (showRedacted) {
2577
+ result[key] = "[REDACTED]";
2578
+ }
2579
+ }
2580
+ return result;
2581
+ }
2582
+
2583
+ // src/epcis.ts
2584
+ var MAPPING_TABLE = {
2585
+ manufactured: {
2586
+ eventType: "TransformationEvent",
2587
+ bizStep: "urn:epcglobal:cbv:bizstep:commissioning",
2588
+ disposition: "urn:epcglobal:cbv:disp:active",
2589
+ exact: true,
2590
+ note: "Raw materials transformed into finished product; new EPC commissioned."
2591
+ },
2592
+ labeled: {
2593
+ eventType: "ObjectEvent",
2594
+ bizStep: "urn:epcglobal:cbv:bizstep:encoding",
2595
+ disposition: "urn:epcglobal:cbv:disp:encoded",
2596
+ exact: true,
2597
+ note: "Physical label or tag applied/encoded on the product."
2598
+ },
2599
+ enrolled: {
2600
+ eventType: "ObjectEvent",
2601
+ bizStep: "urn:epcglobal:cbv:bizstep:commissioning",
2602
+ disposition: "urn:epcglobal:cbv:disp:active",
2603
+ exact: false,
2604
+ note: "Optropic-specific: substrate fingerprint captured. Mapped to commissioning as closest EPCIS equivalent."
2605
+ },
2606
+ shipped: {
2607
+ eventType: "ObjectEvent",
2608
+ bizStep: "urn:epcglobal:cbv:bizstep:shipping",
2609
+ disposition: "urn:epcglobal:cbv:disp:in_transit",
2610
+ exact: true,
2611
+ note: "Product shipped from origin; enters transit."
2612
+ },
2613
+ received: {
2614
+ eventType: "ObjectEvent",
2615
+ bizStep: "urn:epcglobal:cbv:bizstep:receiving",
2616
+ disposition: "urn:epcglobal:cbv:disp:active",
2617
+ exact: true,
2618
+ note: "Product received at destination."
2619
+ },
2620
+ transferred: {
2621
+ eventType: "TransactionEvent",
2622
+ bizStep: "urn:epcglobal:cbv:bizstep:holding",
2623
+ disposition: "urn:epcglobal:cbv:disp:active",
2624
+ exact: false,
2625
+ note: "Ownership transfer. TransactionEvent captures business transaction linkage; disposition remains active."
2626
+ },
2627
+ verified: {
2628
+ eventType: "ObjectEvent",
2629
+ bizStep: "urn:epcglobal:cbv:bizstep:inspecting",
2630
+ disposition: "urn:epcglobal:cbv:disp:active",
2631
+ exact: true,
2632
+ note: "Product authenticity or integrity verified."
2633
+ },
2634
+ recalled: {
2635
+ eventType: "ObjectEvent",
2636
+ bizStep: "urn:epcglobal:cbv:bizstep:holding",
2637
+ disposition: "urn:epcglobal:cbv:disp:recalled",
2638
+ exact: true,
2639
+ note: "Product recalled; removed from distribution."
2640
+ },
2641
+ destroyed: {
2642
+ eventType: "ObjectEvent",
2643
+ bizStep: "urn:epcglobal:cbv:bizstep:decommissioning",
2644
+ disposition: "urn:epcglobal:cbv:disp:destroyed",
2645
+ exact: true,
2646
+ note: "Product destroyed; EPC decommissioned."
2647
+ },
2648
+ custom: {
2649
+ eventType: "ObjectEvent",
2650
+ bizStep: "urn:epcglobal:cbv:bizstep:holding",
2651
+ disposition: "urn:epcglobal:cbv:disp:active",
2652
+ exact: false,
2653
+ note: "Custom event with no direct EPCIS equivalent; mapped to generic observation."
2654
+ }
2655
+ };
2656
+ function mapToEPCIS(eventType) {
2657
+ return MAPPING_TABLE[eventType] ?? MAPPING_TABLE.custom;
2658
+ }
2659
+ function getEPCISMappingTable() {
2660
+ return MAPPING_TABLE;
2661
+ }
2662
+ function toEPCISEvent(event, options) {
2663
+ const mapping = mapToEPCIS(event.eventType);
2664
+ const timezoneOffset = options?.timezoneOffset ?? "+00:00";
2665
+ const epcisEvent = {
2666
+ type: mapping.eventType,
2667
+ eventTime: event.timestamp,
2668
+ eventTimeZoneOffset: timezoneOffset,
2669
+ bizStep: mapping.bizStep,
2670
+ disposition: mapping.disposition,
2671
+ epcList: [assetIdToEPC(event.assetId, options?.gs1CompanyPrefix)],
2672
+ ...event.location?.facility && {
2673
+ readPoint: {
2674
+ id: buildLocationUri(event.location, "readPoint", options?.gs1CompanyPrefix)
2675
+ }
2676
+ },
2677
+ ...event.location?.facility && {
2678
+ bizLocation: {
2679
+ id: buildLocationUri(event.location, "bizLocation", options?.gs1CompanyPrefix)
2680
+ }
2681
+ },
2682
+ "optropic:provenanceEventId": event.id,
2683
+ "optropic:chainSequence": event.chainSequence,
2684
+ "optropic:eventHash": event.eventHash
2685
+ };
2686
+ return epcisEvent;
2687
+ }
2688
+ function buildEPCISDocument(events) {
2689
+ return {
2690
+ "@context": [
2691
+ "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld",
2692
+ { optropic: "https://api.optropic.com/ns/epcis/" }
2693
+ ],
2694
+ type: "EPCISDocument",
2695
+ schemaVersion: "2.0",
2696
+ creationDate: (/* @__PURE__ */ new Date()).toISOString(),
2697
+ epcisBody: {
2698
+ eventList: events
2699
+ }
2700
+ };
2701
+ }
2702
+ function provenanceChainToEPCIS(events, options) {
2703
+ const epcisEvents = events.map((e) => toEPCISEvent(e, options));
2704
+ return buildEPCISDocument(epcisEvents);
2705
+ }
2706
+ function assetIdToEPC(assetId, gs1CompanyPrefix) {
2707
+ if (gs1CompanyPrefix && /^\d{8,14}$/.test(assetId)) {
2708
+ return `urn:epc:id:sgtin:${gs1CompanyPrefix}.${assetId}`;
2709
+ }
2710
+ return `urn:optropic:asset:${assetId}`;
2711
+ }
2712
+ function buildLocationUri(location, _type, gs1CompanyPrefix) {
2713
+ if (gs1CompanyPrefix && location.facility) {
2714
+ return `urn:epc:id:sgln:${gs1CompanyPrefix}.${encodeURIComponent(location.facility)}`;
2715
+ }
2716
+ const parts = [location.country, location.region, location.facility].filter(Boolean);
2717
+ return `urn:optropic:location:${parts.join(":")}`;
2718
+ }
1358
2719
 
1359
2720
  // src/webhooks.ts
1360
2721
  async function computeHmacSha256(secret, message) {
@@ -1401,24 +2762,614 @@ async function verifyWebhookSignature(options) {
1401
2762
  return { valid: true };
1402
2763
  }
1403
2764
 
2765
+ // src/stanag/uid.ts
2766
+ function encodeNATOUID(data) {
2767
+ if (!isValidCAGE(data.cage_ncage)) {
2768
+ throw new Error(`Invalid CAGE/NCAGE code: ${data.cage_ncage}`);
2769
+ }
2770
+ const parts = [
2771
+ `25S${data.cage_ncage}`,
2772
+ data.partNumber,
2773
+ data.serialNumber
2774
+ ];
2775
+ if (data.batchLot) {
2776
+ parts.push(`LOT:${data.batchLot}`);
2777
+ }
2778
+ if (data.enterpriseId) {
2779
+ parts.push(`ENT:${data.enterpriseId}`);
2780
+ }
2781
+ if (data.encoding && data.encoding !== "IUID") {
2782
+ parts.push(`ENC:${data.encoding}`);
2783
+ }
2784
+ return parts.join("|");
2785
+ }
2786
+ function decodeNATOUID(encoded) {
2787
+ const parts = encoded.split("|");
2788
+ if (!parts[0]?.startsWith("25S")) {
2789
+ throw new Error('Invalid NATO UID format: must start with DI "25S"');
2790
+ }
2791
+ const firstPart = parts[0].substring(3);
2792
+ const cage_ncage = firstPart.substring(0, 5);
2793
+ if (parts.length < 3) {
2794
+ throw new Error("Invalid NATO UID: insufficient components");
2795
+ }
2796
+ const partNumber = parts[1];
2797
+ const serialNumber = parts[2];
2798
+ let batchLot;
2799
+ let enterpriseId;
2800
+ let encoding = "IUID";
2801
+ for (let i = 3; i < parts.length; i++) {
2802
+ const part = parts[i];
2803
+ if (part?.startsWith("LOT:")) {
2804
+ batchLot = part.substring(4);
2805
+ } else if (part?.startsWith("ENT:")) {
2806
+ enterpriseId = part.substring(4);
2807
+ } else if (part?.startsWith("ENC:")) {
2808
+ encoding = part.substring(4);
2809
+ }
2810
+ }
2811
+ if (!isValidCAGE(cage_ncage)) {
2812
+ throw new Error(`Invalid CAGE/NCAGE in decoded UID: ${cage_ncage}`);
2813
+ }
2814
+ return {
2815
+ cage_ncage,
2816
+ partNumber,
2817
+ serialNumber,
2818
+ batchLot,
2819
+ enterpriseId,
2820
+ encoding
2821
+ };
2822
+ }
2823
+ function validateNATOUID(uid) {
2824
+ const errors = [];
2825
+ if (!uid) {
2826
+ return { valid: false, errors: ["UID cannot be empty"] };
2827
+ }
2828
+ if (!uid.startsWith("25S")) {
2829
+ errors.push('UID must start with DI "25S"');
2830
+ }
2831
+ const parts = uid.split("|");
2832
+ if (parts.length < 3) {
2833
+ errors.push("UID must contain at least CAGE, part number, and serial");
2834
+ }
2835
+ if (parts[0]) {
2836
+ const cage = parts[0].substring(3);
2837
+ if (!isValidCAGE(cage)) {
2838
+ errors.push(`Invalid CAGE/NCAGE code: ${cage}`);
2839
+ }
2840
+ }
2841
+ return {
2842
+ valid: errors.length === 0,
2843
+ errors
2844
+ };
2845
+ }
2846
+ function isValidCAGE(code) {
2847
+ return /^[A-Z0-9]{5}$/.test(code);
2848
+ }
2849
+ function mapNATOUIDToOptropic(uid) {
2850
+ const assetId = encodeNATOUID(uid);
2851
+ return {
2852
+ assetId,
2853
+ metadata: {
2854
+ type: "nato_uid",
2855
+ cage_ncage: uid.cage_ncage,
2856
+ partNumber: uid.partNumber,
2857
+ serialNumber: uid.serialNumber,
2858
+ batchLot: uid.batchLot,
2859
+ enterpriseId: uid.enterpriseId,
2860
+ encoding: uid.encoding,
2861
+ standard: "STANAG_2290"
2862
+ }
2863
+ };
2864
+ }
2865
+ function mapOptropicToNATOUID(_assetId, metadata) {
2866
+ const cage_ncage = metadata.cage_ncage;
2867
+ const partNumber = metadata.partNumber;
2868
+ const serialNumber = metadata.serialNumber;
2869
+ const encoding = metadata.encoding || "IUID";
2870
+ if (!cage_ncage || !partNumber || !serialNumber) {
2871
+ throw new Error("Missing required NATO UID fields in metadata");
2872
+ }
2873
+ return {
2874
+ cage_ncage,
2875
+ partNumber,
2876
+ serialNumber,
2877
+ batchLot: metadata.batchLot,
2878
+ enterpriseId: metadata.enterpriseId,
2879
+ encoding
2880
+ };
2881
+ }
2882
+ function buildDefenceMetadata(classification, caveats, shelfLife) {
2883
+ return {
2884
+ classification,
2885
+ handlingCaveats: caveats || [],
2886
+ releasableTo: getNATOReleasability(classification),
2887
+ shelfLife
2888
+ };
2889
+ }
2890
+ function getNATOReleasability(classification) {
2891
+ switch (classification) {
2892
+ case "UNCLASSIFIED":
2893
+ return ["NATO", "PUBLIC"];
2894
+ case "RESTRICTED":
2895
+ return ["NATO", "EU"];
2896
+ case "CONFIDENTIAL":
2897
+ return ["NATO"];
2898
+ case "SECRET":
2899
+ return ["NATO"];
2900
+ case "NATO_SECRET":
2901
+ return ["NATO"];
2902
+ case "COSMIC_TOP_SECRET":
2903
+ return ["NATO"];
2904
+ default:
2905
+ return [];
2906
+ }
2907
+ }
2908
+ function validateDefenceMetadata(metadata) {
2909
+ const errors = [];
2910
+ if (!metadata.classification) {
2911
+ errors.push("Classification level is required");
2912
+ }
2913
+ if (!Array.isArray(metadata.handlingCaveats)) {
2914
+ errors.push("Handling caveats must be an array");
2915
+ }
2916
+ if (!Array.isArray(metadata.releasableTo)) {
2917
+ errors.push("Releasable to must be an array");
2918
+ }
2919
+ if (metadata.shelfLife) {
2920
+ const mfg = new Date(metadata.shelfLife.manufacturedDate);
2921
+ const exp = new Date(metadata.shelfLife.expiryDate);
2922
+ if (mfg >= exp) {
2923
+ errors.push("Expiry date must be after manufactured date");
2924
+ }
2925
+ if (!["TYPE_I", "TYPE_II", "TYPE_III"].includes(metadata.shelfLife.type)) {
2926
+ errors.push("Invalid shelf life type");
2927
+ }
2928
+ }
2929
+ if (metadata.nsn && !/^\d{13}$/.test(metadata.nsn)) {
2930
+ errors.push("NSN must be 13 digits");
2931
+ }
2932
+ return {
2933
+ valid: errors.length === 0,
2934
+ errors
2935
+ };
2936
+ }
2937
+
2938
+ // src/stanag/logistics.ts
2939
+ function mapMovementToProvenance(movement) {
2940
+ const typeMap = {
2941
+ manufacture: "MANUFACTURE",
2942
+ receipt: "RECEIPT",
2943
+ inspection: "INSPECTION",
2944
+ storage: "STORAGE",
2945
+ issue: "ISSUED",
2946
+ transport: "TRANSPORT",
2947
+ delivery: "DELIVERY",
2948
+ maintenance: "MAINTENANCE",
2949
+ repair: "REPAIR",
2950
+ disposal: "DISPOSAL",
2951
+ destruction: "DESTRUCTION",
2952
+ transfer: "TRANSFER",
2953
+ inventory: "INVENTORY"
2954
+ };
2955
+ return {
2956
+ eventType: typeMap[movement.movementType] ?? "UNKNOWN",
2957
+ timestamp: movement.timestamp,
2958
+ actor: movement.custodian,
2959
+ location: {
2960
+ facility: movement.location.facility,
2961
+ coordinates: movement.location.coordinates ? {
2962
+ lat: movement.location.coordinates.lat,
2963
+ lng: movement.location.coordinates.lon
2964
+ } : void 0
2965
+ },
2966
+ metadata: {
2967
+ movementId: movement.movementId,
2968
+ itemUID: movement.itemUID,
2969
+ supplyClass: movement.supplyClass,
2970
+ priority: movement.priority,
2971
+ condition: movement.condition,
2972
+ authorizedBy: movement.authorizedBy,
2973
+ transportMethod: movement.transportMethod,
2974
+ receivingParty: movement.receivingParty,
2975
+ remarks: movement.remarks
2976
+ }
2977
+ };
2978
+ }
2979
+ function calculateReadiness(movements, thresholds = {}) {
2980
+ if (movements.length === 0) {
2981
+ return {
2982
+ overall: 0,
2983
+ serviceablePercent: 0,
2984
+ maintenanceCompliance: 0,
2985
+ daysSinceInspection: 0,
2986
+ transportEfficiency: 0,
2987
+ recommendations: ["No movement data available for readiness assessment"],
2988
+ assessmentAt: (/* @__PURE__ */ new Date()).toISOString()
2989
+ };
2990
+ }
2991
+ const maxInventoryAge = thresholds.maxInventoryAgeDays ?? 365;
2992
+ void thresholds.maxUnserviceablePercent;
2993
+ const requiredMaintenance = thresholds.requiredMaintenancePercent ?? 95;
2994
+ const conditions = movements.map((m) => m.condition);
2995
+ const serviceableCount = conditions.filter((c) => c === "serviceable").length;
2996
+ const serviceablePercent = serviceableCount / conditions.length * 100;
2997
+ const maintenances = movements.filter((m) => m.movementType === "maintenance" || m.movementType === "repair");
2998
+ const maintenancePercent = maintenances.length / Math.max(movements.length, 1) * 100;
2999
+ const inspections = movements.filter((m) => m.movementType === "inspection");
3000
+ const now = /* @__PURE__ */ new Date();
3001
+ let daysSinceInspection = 0;
3002
+ if (inspections.length > 0) {
3003
+ const lastInspection = new Date(inspections[inspections.length - 1].timestamp);
3004
+ daysSinceInspection = Math.floor((now.getTime() - lastInspection.getTime()) / (1e3 * 60 * 60 * 24));
3005
+ } else {
3006
+ daysSinceInspection = maxInventoryAge;
3007
+ }
3008
+ const transports = movements.filter((m) => m.movementType === "transport");
3009
+ let transportEfficiency = 100;
3010
+ if (transports.length > 0) {
3011
+ const avgDelay = transports.reduce((sum, m) => {
3012
+ const timestamp = new Date(m.timestamp);
3013
+ const delay = Math.floor((now.getTime() - timestamp.getTime()) / (1e3 * 60 * 60));
3014
+ return sum + delay;
3015
+ }, 0) / transports.length;
3016
+ transportEfficiency = Math.max(0, 100 - avgDelay / (thresholds.maxTransportHours ?? 48) * 100);
3017
+ }
3018
+ const weightedScore = serviceablePercent * 0.4 + Math.min(maintenancePercent, requiredMaintenance) * 0.3 + (100 - Math.min(daysSinceInspection, maxInventoryAge) / maxInventoryAge * 100) * 0.2 + transportEfficiency * 0.1;
3019
+ const overall = Math.round(Math.max(0, Math.min(100, weightedScore)));
3020
+ const recommendations = [];
3021
+ if (serviceablePercent < 85) {
3022
+ recommendations.push(`Low serviceable percentage (${Math.round(serviceablePercent)}%). Increase maintenance activities.`);
3023
+ }
3024
+ if (maintenancePercent < requiredMaintenance) {
3025
+ recommendations.push(`Maintenance compliance below threshold (${Math.round(maintenancePercent)}% vs ${requiredMaintenance}% required).`);
3026
+ }
3027
+ if (daysSinceInspection > maxInventoryAge * 0.8) {
3028
+ recommendations.push(`Items overdue for inspection. Last inspection ${daysSinceInspection} days ago.`);
3029
+ }
3030
+ if (transportEfficiency < 70) {
3031
+ recommendations.push("Transport efficiency is degraded. Review logistics network.");
3032
+ }
3033
+ if (recommendations.length === 0) {
3034
+ recommendations.push("Readiness levels are optimal. Continue routine maintenance.");
3035
+ }
3036
+ return {
3037
+ overall,
3038
+ serviceablePercent: Math.round(serviceablePercent * 10) / 10,
3039
+ maintenanceCompliance: Math.round(maintenancePercent * 10) / 10,
3040
+ daysSinceInspection,
3041
+ transportEfficiency: Math.round(transportEfficiency * 10) / 10,
3042
+ recommendations,
3043
+ assessmentAt: (/* @__PURE__ */ new Date()).toISOString()
3044
+ };
3045
+ }
3046
+ function validateLogisticsMovement(movement) {
3047
+ const errors = [];
3048
+ if (!movement.movementId) {
3049
+ errors.push("Movement ID is required");
3050
+ }
3051
+ if (!movement.itemUID) {
3052
+ errors.push("Item UID is required");
3053
+ }
3054
+ if (!["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"].includes(movement.supplyClass)) {
3055
+ errors.push("Invalid supply class");
3056
+ }
3057
+ if (!movement.timestamp) {
3058
+ errors.push("Timestamp is required");
3059
+ } else {
3060
+ const d = new Date(movement.timestamp);
3061
+ if (isNaN(d.getTime())) {
3062
+ errors.push("Invalid timestamp format");
3063
+ }
3064
+ }
3065
+ if (!movement.custodian) {
3066
+ errors.push("Custodian is required");
3067
+ }
3068
+ return {
3069
+ valid: errors.length === 0,
3070
+ errors
3071
+ };
3072
+ }
3073
+
3074
+ // src/multi-tenant/platform.ts
3075
+ async function createOrganization(params) {
3076
+ if (!params.name || !params.slug) {
3077
+ throw new Error("Name and slug are required");
3078
+ }
3079
+ if (!/^[a-z0-9-]+$/.test(params.slug)) {
3080
+ throw new Error("Slug must contain only lowercase letters, numbers, and hyphens");
3081
+ }
3082
+ return {
3083
+ id: `org_${generateId()}`,
3084
+ name: params.name,
3085
+ slug: params.slug,
3086
+ plan: params.plan,
3087
+ status: "active",
3088
+ settings: params.settings,
3089
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3090
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3091
+ };
3092
+ }
3093
+ async function getOrganization(orgId) {
3094
+ if (!orgId) {
3095
+ throw new Error("Organization ID is required");
3096
+ }
3097
+ throw new Error("getOrganization requires API integration");
3098
+ }
3099
+ async function updateOrganization(orgId, updates) {
3100
+ if (!orgId) {
3101
+ throw new Error("Organization ID is required");
3102
+ }
3103
+ if (updates.plan && !["starter", "professional", "enterprise", "sovereign"].includes(updates.plan)) {
3104
+ throw new Error("Invalid plan tier");
3105
+ }
3106
+ if (updates.status && !["active", "suspended", "pending"].includes(updates.status)) {
3107
+ throw new Error("Invalid organization status");
3108
+ }
3109
+ throw new Error("updateOrganization requires API integration");
3110
+ }
3111
+ async function listMembers(orgId) {
3112
+ if (!orgId) {
3113
+ throw new Error("Organization ID is required");
3114
+ }
3115
+ throw new Error("listMembers requires API integration");
3116
+ }
3117
+ async function inviteMember(orgId, email, role) {
3118
+ if (!orgId || !email || !role) {
3119
+ throw new Error("Organization ID, email, and role are required");
3120
+ }
3121
+ if (!isValidEmail(email)) {
3122
+ throw new Error("Invalid email address");
3123
+ }
3124
+ if (!["owner", "admin", "member", "viewer", "auditor"].includes(role)) {
3125
+ throw new Error("Invalid role");
3126
+ }
3127
+ return {
3128
+ id: `invite_${generateId()}`,
3129
+ email,
3130
+ role,
3131
+ invitedBy: "current_user",
3132
+ expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1e3).toISOString(),
3133
+ // 30 days
3134
+ status: "pending"
3135
+ };
3136
+ }
3137
+ async function removeMember(orgId, userId) {
3138
+ if (!orgId || !userId) {
3139
+ throw new Error("Organization ID and user ID are required");
3140
+ }
3141
+ throw new Error("removeMember requires API integration");
3142
+ }
3143
+ async function updateMemberRole(orgId, userId, newRole) {
3144
+ if (!orgId || !userId || !newRole) {
3145
+ throw new Error("Organization ID, user ID, and new role are required");
3146
+ }
3147
+ if (!["owner", "admin", "member", "viewer", "auditor"].includes(newRole)) {
3148
+ throw new Error("Invalid role");
3149
+ }
3150
+ throw new Error("updateMemberRole requires API integration");
3151
+ }
3152
+ async function createRLSPolicy(params) {
3153
+ if (!params.tenantId || !params.resourceType || !params.action || !params.condition) {
3154
+ throw new Error("All policy parameters are required");
3155
+ }
3156
+ validateRLSCondition(params.condition);
3157
+ return {
3158
+ id: `policy_${generateId()}`,
3159
+ tenantId: params.tenantId,
3160
+ resourceType: params.resourceType,
3161
+ action: params.action,
3162
+ condition: params.condition,
3163
+ priority: params.priority ?? 100,
3164
+ enabled: true
3165
+ };
3166
+ }
3167
+ async function listRLSPolicies(tenantId) {
3168
+ if (!tenantId) {
3169
+ throw new Error("Tenant ID is required");
3170
+ }
3171
+ throw new Error("listRLSPolicies requires API integration");
3172
+ }
3173
+ async function deleteRLSPolicy(policyId) {
3174
+ if (!policyId) {
3175
+ throw new Error("Policy ID is required");
3176
+ }
3177
+ throw new Error("deleteRLSPolicy requires API integration");
3178
+ }
3179
+ function validateRLSCondition(condition) {
3180
+ if (!condition.field || !condition.operator || condition.value === void 0) {
3181
+ throw new Error("RLS condition must have field, operator, and value");
3182
+ }
3183
+ const validOperators = ["eq", "neq", "in", "not_in", "contains", "starts_with", "gt", "lt"];
3184
+ if (!validOperators.includes(condition.operator)) {
3185
+ throw new Error(`Invalid RLS operator: ${condition.operator}`);
3186
+ }
3187
+ if (["in", "not_in"].includes(condition.operator) && !Array.isArray(condition.value)) {
3188
+ throw new Error(`Operator ${condition.operator} requires an array value`);
3189
+ }
3190
+ }
3191
+ async function getUsageQuota(tenantId) {
3192
+ if (!tenantId) {
3193
+ throw new Error("Tenant ID is required");
3194
+ }
3195
+ throw new Error("getUsageQuota requires API integration");
3196
+ }
3197
+ async function updateUsageQuota(tenantId, limits) {
3198
+ if (!tenantId) {
3199
+ throw new Error("Tenant ID is required");
3200
+ }
3201
+ if (limits.assets !== void 0 && limits.assets < 0) {
3202
+ throw new Error("Asset limit cannot be negative");
3203
+ }
3204
+ if (limits.storage_mb !== void 0 && limits.storage_mb < 0) {
3205
+ throw new Error("Storage limit cannot be negative");
3206
+ }
3207
+ throw new Error("updateUsageQuota requires API integration");
3208
+ }
3209
+ function generateId() {
3210
+ return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
3211
+ }
3212
+ function isValidEmail(email) {
3213
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
3214
+ }
3215
+ function getRolePermissions(role) {
3216
+ const permissionMap = {
3217
+ owner: [
3218
+ "assets:read",
3219
+ "assets:write",
3220
+ "assets:delete",
3221
+ "assets:admin",
3222
+ "members:manage",
3223
+ "policies:manage",
3224
+ "quotas:manage",
3225
+ "audit:read",
3226
+ "org:manage"
3227
+ ],
3228
+ admin: [
3229
+ "assets:read",
3230
+ "assets:write",
3231
+ "assets:delete",
3232
+ "members:manage",
3233
+ "policies:manage",
3234
+ "audit:read"
3235
+ ],
3236
+ member: [
3237
+ "assets:read",
3238
+ "assets:write",
3239
+ "audit:read"
3240
+ ],
3241
+ viewer: [
3242
+ "assets:read"
3243
+ ],
3244
+ auditor: [
3245
+ "assets:read",
3246
+ "audit:read"
3247
+ ]
3248
+ };
3249
+ return permissionMap[role] || [];
3250
+ }
3251
+
3252
+ // src/marketplace/partner.ts
3253
+ async function registerPartner(registration, requestFn) {
3254
+ const result = await requestFn("POST", "/marketplace/partners", registration);
3255
+ return result;
3256
+ }
3257
+ async function getPartner(partnerId, requestFn) {
3258
+ const result = await requestFn("GET", `/marketplace/partners/${partnerId}`);
3259
+ return result;
3260
+ }
3261
+ async function updatePartner(partnerId, params, requestFn) {
3262
+ const result = await requestFn("PATCH", `/marketplace/partners/${partnerId}`, params);
3263
+ return result;
3264
+ }
3265
+ async function getPartnerAnalytics(partnerId, period, requestFn) {
3266
+ const result = await requestFn(
3267
+ "GET",
3268
+ `/marketplace/partners/${partnerId}/analytics?period=${encodeURIComponent(period)}`
3269
+ );
3270
+ return result;
3271
+ }
3272
+ async function listPartners(params, requestFn) {
3273
+ const queryParams = new URLSearchParams();
3274
+ if (params?.tier) queryParams.append("tier", params.tier);
3275
+ if (params?.status) queryParams.append("status", params.status);
3276
+ if (params?.type) queryParams.append("type", params.type);
3277
+ if (params?.limit) queryParams.append("limit", params.limit.toString());
3278
+ if (params?.offset) queryParams.append("offset", params.offset.toString());
3279
+ const query = queryParams.toString();
3280
+ const path = query ? `/marketplace/partners?${query}` : "/marketplace/partners";
3281
+ const result = await requestFn("GET", path);
3282
+ return result;
3283
+ }
3284
+ async function generatePartnerApiKey(partnerId, scopes, expiresAt, requestFn) {
3285
+ const body = { scopes, expiresAt };
3286
+ const result = await requestFn("POST", `/marketplace/partners/${partnerId}/keys`, body);
3287
+ return result;
3288
+ }
3289
+
3290
+ // src/marketplace/templates.ts
3291
+ async function createTemplate(partnerId, params, requestFn) {
3292
+ const body = { ...params, partnerId };
3293
+ const result = await requestFn("POST", "/marketplace/templates", body);
3294
+ return result;
3295
+ }
3296
+ async function getTemplate(templateId, requestFn) {
3297
+ const result = await requestFn("GET", `/marketplace/templates/${templateId}`);
3298
+ return result;
3299
+ }
3300
+ async function updateTemplate(templateId, params, requestFn) {
3301
+ const result = await requestFn("PATCH", `/marketplace/templates/${templateId}`, params);
3302
+ return result;
3303
+ }
3304
+ async function publishTemplate(templateId, params, requestFn) {
3305
+ const result = await requestFn("POST", `/marketplace/templates/${templateId}/publish`, params);
3306
+ return result;
3307
+ }
3308
+ async function deprecateTemplate(templateId, params, requestFn) {
3309
+ const result = await requestFn("POST", `/marketplace/templates/${templateId}/deprecate`, params);
3310
+ return result;
3311
+ }
3312
+ async function listTemplates(params, requestFn) {
3313
+ const queryParams = new URLSearchParams();
3314
+ if (params?.category) queryParams.append("category", params.category);
3315
+ if (params?.status) queryParams.append("status", params.status);
3316
+ if (params?.author) queryParams.append("author", params.author);
3317
+ if (params?.limit) queryParams.append("limit", params.limit.toString());
3318
+ if (params?.offset) queryParams.append("offset", params.offset.toString());
3319
+ const query = queryParams.toString();
3320
+ const path = query ? `/marketplace/templates?${query}` : "/marketplace/templates";
3321
+ const result = await requestFn("GET", path);
3322
+ return result;
3323
+ }
3324
+ async function searchTemplates(query, params, requestFn) {
3325
+ const queryParams = new URLSearchParams({ q: query });
3326
+ if (params?.category) queryParams.append("category", params.category);
3327
+ if (params?.limit) queryParams.append("limit", params.limit.toString());
3328
+ const result = await requestFn(
3329
+ "GET",
3330
+ `/marketplace/templates/search?${queryParams.toString()}`
3331
+ );
3332
+ return result;
3333
+ }
3334
+ async function installTemplate(templateId, requestFn) {
3335
+ const result = await requestFn("POST", `/marketplace/templates/${templateId}/install`);
3336
+ return result;
3337
+ }
3338
+ async function uninstallTemplate(templateId, requestFn) {
3339
+ const result = await requestFn("POST", `/marketplace/templates/${templateId}/uninstall`);
3340
+ return result;
3341
+ }
3342
+ async function rateTemplate(templateId, params, requestFn) {
3343
+ const result = await requestFn("POST", `/marketplace/templates/${templateId}/rate`, params);
3344
+ return result;
3345
+ }
3346
+ async function validateAgainstTemplate(templateId, data, requestFn) {
3347
+ const result = await requestFn("POST", `/marketplace/templates/${templateId}/validate`, { data });
3348
+ return result;
3349
+ }
3350
+
1404
3351
  // src/index.ts
1405
- var SDK_VERSION2 = "2.3.0";
3352
+ var SDK_VERSION2 = "3.0.0";
1406
3353
  export {
1407
3354
  AssetsResource,
1408
3355
  AuditResource,
1409
3356
  AuthenticationError,
1410
3357
  BatchNotFoundError,
3358
+ BatchesResource,
1411
3359
  CodeNotFoundError,
1412
3360
  ComplianceResource,
3361
+ DPPAccessLevel,
1413
3362
  DocumentsResource,
1414
3363
  InvalidCodeError,
1415
3364
  InvalidGTINError,
1416
3365
  InvalidSerialError,
1417
3366
  KeysResource,
1418
3367
  KeysetsResource,
3368
+ M2MResource,
1419
3369
  NetworkError,
1420
3370
  OptropicClient,
1421
3371
  OptropicError,
3372
+ Permission,
1422
3373
  ProvenanceResource,
1423
3374
  QuotaExceededError,
1424
3375
  RateLimitedError,
@@ -1427,13 +3378,87 @@ export {
1427
3378
  SchemasResource,
1428
3379
  ServiceUnavailableError,
1429
3380
  StaleFilterError,
3381
+ TenantsResource,
1430
3382
  TimeoutError,
3383
+ appendRecord,
3384
+ buildBatteryPassportQR,
1431
3385
  buildDPPConfig,
3386
+ buildDefenceMetadata,
3387
+ buildEPCISDocument,
3388
+ buildGS1DigitalLink,
3389
+ calculateReadiness,
3390
+ calibrateThreshold,
3391
+ computeDistance,
3392
+ computeSimilarity,
3393
+ createAuditChain,
1432
3394
  createClient,
3395
+ createConsensusResultMessage,
3396
+ createDescriptorExchange,
1433
3397
  createErrorFromResponse,
3398
+ createHandshakeAccept,
3399
+ createHandshakeInit,
3400
+ createOrganization,
3401
+ createRLSPolicy,
3402
+ createTemplate,
3403
+ decodeNATOUID,
3404
+ deleteRLSPolicy,
3405
+ deprecateTemplate,
3406
+ deserializeMessage,
3407
+ encodeNATOUID,
3408
+ evaluateConsensus,
3409
+ exportChain,
3410
+ filterDPPByAccess,
3411
+ generatePartnerApiKey,
3412
+ generateQRCodePayload,
3413
+ getAILabel,
3414
+ getDPPAccessPolicy,
3415
+ getEPCISMappingTable,
3416
+ getOrganization,
3417
+ getPartner,
3418
+ getPartnerAnalytics,
3419
+ getRolePermissions,
3420
+ getSupportedAIs,
3421
+ getTemplate,
3422
+ getUsageQuota,
3423
+ importChain,
3424
+ installTemplate,
3425
+ inviteMember,
3426
+ isValidAI,
3427
+ listMembers,
3428
+ listPartners,
3429
+ listRLSPolicies,
3430
+ listTemplates,
3431
+ mapMovementToProvenance,
3432
+ mapNATOUIDToOptropic,
3433
+ mapOptropicToNATOUID,
3434
+ mapToEPCIS,
3435
+ mapToOptropicAsset,
1434
3436
  parseFilterHeader,
3437
+ parseGS1DigitalLink,
1435
3438
  parseSaltsHeader,
3439
+ provenanceChainToEPCIS,
3440
+ publishTemplate,
3441
+ rateTemplate,
3442
+ registerPartner,
3443
+ removeMember,
3444
+ searchTemplates,
3445
+ serializeMessage,
3446
+ toEPCISEvent,
3447
+ uninstallTemplate,
3448
+ updateMemberRole,
3449
+ updateOrganization,
3450
+ updatePartner,
3451
+ updateTemplate,
3452
+ updateUsageQuota,
3453
+ validateAgainstTemplate,
3454
+ validateBatteryPassport,
1436
3455
  validateDPPMetadata,
3456
+ validateDefenceMetadata,
3457
+ validateGTIN,
3458
+ validateLogisticsMovement,
3459
+ validateMessage,
3460
+ validateNATOUID,
3461
+ verifyChain,
1437
3462
  verifyOffline,
1438
3463
  verifyWebhookSignature
1439
3464
  };