@startinblox/core 2.0.6-beta.1 → 2.0.6-beta.10

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.
@@ -1,15 +1,15 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- import { l as isUrlOrRelativePath, m as jsonldContextParserExports, o as getRawContext, n as normalizeContext, q as mergeContexts, c as doesResourceContainList, r as requireJsonldContextParser, v as requireErrorCoded, w as requireLink } from "./helpers-vZrb1UDN.js";
5
- let StoreService, formatAttributesToServerSearchOptions, base_context, StoreType, StoreFactory, hasQueryIndex, formatAttributesToServerPaginationOptions, getDefaultExportFromCjs, hasSetLocalData, sibStore, mergeServerSearchOptions, semantizer;
4
+ import { l as isUrlOrRelativePath, m as jsonldContextParserExports, o as getRawContext, n as normalizeContext, q as mergeContexts, c as doesResourceContainList, r as requireJsonldContextParser, v as requireErrorCoded, w as requireLink } from "./helpers-DtCY-jxq.js";
5
+ let AuthFetchResolver, DEFAULT_AUTH_SELECTORS, StoreService, formatAttributesToServerSearchOptions, base_context, StoreType, StoreFactory, hasQueryIndex, formatAttributesToServerPaginationOptions, getDefaultExportFromCjs, hasSetLocalData, sibStore, mergeServerSearchOptions, semantizer;
6
6
  let __tla = (async () => {
7
7
  var _a;
8
8
  getDefaultExportFromCjs = function(x) {
9
9
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
10
10
  };
11
11
  function getAugmentedNamespace(n) {
12
- if (n.__esModule) return n;
12
+ if (Object.prototype.hasOwnProperty.call(n, "__esModule")) return n;
13
13
  var f = n.default;
14
14
  if (typeof f == "function") {
15
15
  var a = function a2() {
@@ -162,7 +162,21 @@ let __tla = (async () => {
162
162
  return false;
163
163
  }
164
164
  }
165
- class DataspaceConnectorStore {
165
+ class AssetValidationError extends Error {
166
+ constructor(message, assetId, validationType, reason, details) {
167
+ super(message);
168
+ __publicField(this, "assetId");
169
+ __publicField(this, "validationType");
170
+ __publicField(this, "reason");
171
+ __publicField(this, "details");
172
+ this.name = "AssetValidationError";
173
+ this.assetId = assetId;
174
+ this.validationType = validationType;
175
+ this.reason = reason;
176
+ this.details = details;
177
+ }
178
+ }
179
+ const _DataspaceConnectorStore = class _DataspaceConnectorStore {
166
180
  constructor(config) {
167
181
  __publicField(this, "cache");
168
182
  __publicField(this, "session");
@@ -184,6 +198,12 @@ let __tla = (async () => {
184
198
  Accept: "application/json"
185
199
  };
186
200
  }
201
+ _makeAssetAgreementKey(assetId, providerParticipantId) {
202
+ if (providerParticipantId) {
203
+ return `${assetId}:${providerParticipantId}`;
204
+ }
205
+ return assetId;
206
+ }
187
207
  validateConfig(config) {
188
208
  const required = [
189
209
  "catalogEndpoint",
@@ -254,6 +274,21 @@ let __tla = (async () => {
254
274
  }
255
275
  async negotiateContract(counterPartyAddress, _offerId, policy, counterPartyId) {
256
276
  await this.ensureAuthenticated();
277
+ console.log("[DataspaceConnectorStore] Received policy for negotiation:", policy);
278
+ console.log("[DataspaceConnectorStore] Policy keys:", Object.keys(policy));
279
+ const cleanPolicy = {};
280
+ for (const key in policy) {
281
+ if (!/^\d+$/.test(key)) {
282
+ cleanPolicy[key] = policy[key];
283
+ } else {
284
+ console.warn(`[DataspaceConnectorStore] Removing numeric key "${key}" from policy`);
285
+ }
286
+ }
287
+ console.log("[DataspaceConnectorStore] Cleaned policy keys:", Object.keys(cleanPolicy));
288
+ const targetAssetId = _offerId || cleanPolicy.target || cleanPolicy["odrl:target"] || policy.target || policy["odrl:target"];
289
+ if (!targetAssetId) {
290
+ console.warn("[DataspaceConnectorStore] No target asset ID found for negotiation");
291
+ }
257
292
  const negotiationRequest = {
258
293
  "@context": {
259
294
  "@vocab": "https://w3id.org/edc/v0.0.1/ns/"
@@ -264,12 +299,15 @@ let __tla = (async () => {
264
299
  protocol: "dataspace-protocol-http",
265
300
  policy: {
266
301
  "@context": "http://www.w3.org/ns/odrl.jsonld",
267
- "@id": policy["@id"],
268
- "@type": "Offer",
269
- assigner: counterPartyId || "provider",
270
- target: policy.target
302
+ ...cleanPolicy,
303
+ "@type": "odrl:Offer",
304
+ assigner: cleanPolicy.assigner || policy.assigner || counterPartyId || "provider",
305
+ target: targetAssetId,
306
+ "odrl:target": targetAssetId
271
307
  }
272
308
  };
309
+ console.log("[DataspaceConnectorStore] Contract negotiation request:", JSON.stringify(negotiationRequest, null, 2));
310
+ console.log("[DataspaceConnectorStore] \u{1F50D} POSTing negotiation to consumer connector:", this.config.contractNegotiationEndpoint);
273
311
  const response = await this.fetchAuthn(this.config.contractNegotiationEndpoint, {
274
312
  method: "POST",
275
313
  headers: this.headers,
@@ -291,7 +329,7 @@ let __tla = (async () => {
291
329
  getNegotiationStatus(negotiationId) {
292
330
  return this._getNegotiationStatus(negotiationId);
293
331
  }
294
- async getContractAgreement(negotiationId) {
332
+ async getContractAgreement(negotiationId, providerParticipantId) {
295
333
  await this.ensureAuthenticated();
296
334
  try {
297
335
  const response = await this.fetchAuthn(`${this.config.contractNegotiationEndpoint}/${negotiationId}/agreement`, {
@@ -306,9 +344,11 @@ let __tla = (async () => {
306
344
  this.contractAgreements.set(agreement["@id"], agreement);
307
345
  const assetId = agreement.assetId;
308
346
  if (assetId) {
309
- const existing = this.assetAgreements.get(assetId);
347
+ const key = this._makeAssetAgreementKey(assetId, providerParticipantId);
348
+ const existing = this.assetAgreements.get(key);
310
349
  const mapping = {
311
350
  assetId,
351
+ providerParticipantId,
312
352
  catalogId: existing == null ? void 0 : existing.catalogId,
313
353
  agreementId: agreement["@id"],
314
354
  agreement,
@@ -318,7 +358,7 @@ let __tla = (async () => {
318
358
  createdAt: (existing == null ? void 0 : existing.createdAt) || Date.now(),
319
359
  lastUpdated: Date.now()
320
360
  };
321
- this.assetAgreements.set(assetId, mapping);
361
+ this.assetAgreements.set(key, mapping);
322
362
  }
323
363
  return agreement;
324
364
  } catch (error2) {
@@ -326,8 +366,9 @@ let __tla = (async () => {
326
366
  return null;
327
367
  }
328
368
  }
329
- getStoredContractAgreement(assetId) {
330
- const mapping = this.assetAgreements.get(assetId);
369
+ getStoredContractAgreement(assetId, providerParticipantId) {
370
+ const key = this._makeAssetAgreementKey(assetId, providerParticipantId);
371
+ const mapping = this.assetAgreements.get(key);
331
372
  return (mapping == null ? void 0 : mapping.agreement) || null;
332
373
  }
333
374
  async getAllContractNegotiations() {
@@ -388,11 +429,12 @@ let __tla = (async () => {
388
429
  getAllAssetAgreements() {
389
430
  return Array.from(this.assetAgreements.values());
390
431
  }
391
- getAssetAgreement(assetId) {
392
- return this.assetAgreements.get(assetId) || null;
432
+ getAssetAgreement(assetId, providerParticipantId) {
433
+ const key = this._makeAssetAgreementKey(assetId, providerParticipantId);
434
+ return this.assetAgreements.get(key) || null;
393
435
  }
394
- hasValidAgreement(assetId) {
395
- const agreement = this.getAssetAgreement(assetId);
436
+ hasValidAgreement(assetId, providerParticipantId) {
437
+ const agreement = this.getAssetAgreement(assetId, providerParticipantId);
396
438
  return agreement !== null;
397
439
  }
398
440
  async initiateTransfer(counterPartyAddress, contractId, dataDestination) {
@@ -420,7 +462,7 @@ let __tla = (async () => {
420
462
  this.transferProcesses.set(transferId, transfer);
421
463
  return transferId;
422
464
  }
423
- async initiateEDRTransfer(assetId, counterPartyAddress, contractId) {
465
+ async initiateEDRTransfer(assetId, counterPartyAddress, contractId, providerParticipantId) {
424
466
  await this.ensureAuthenticated();
425
467
  const edrRequest = {
426
468
  "@context": {
@@ -447,11 +489,12 @@ let __tla = (async () => {
447
489
  }
448
490
  const edrResponse = await response.json();
449
491
  const transferId = edrResponse["@id"];
450
- const mapping = this.assetAgreements.get(assetId);
492
+ const key = this._makeAssetAgreementKey(assetId, providerParticipantId);
493
+ const mapping = this.assetAgreements.get(key);
451
494
  if (mapping) {
452
495
  mapping.transferId = transferId;
453
496
  mapping.lastUpdated = Date.now();
454
- this.assetAgreements.set(assetId, mapping);
497
+ this.assetAgreements.set(key, mapping);
455
498
  }
456
499
  return transferId;
457
500
  }
@@ -529,7 +572,8 @@ let __tla = (async () => {
529
572
  }
530
573
  async accessAssetData(assetId, counterPartyAddress, policy, counterPartyId, additionalPath) {
531
574
  try {
532
- const existingMapping = this.assetAgreements.get(assetId);
575
+ const key = this._makeAssetAgreementKey(assetId, counterPartyId);
576
+ const existingMapping = this.assetAgreements.get(key);
533
577
  if ((existingMapping == null ? void 0 : existingMapping.edrToken) && existingMapping.transferId) {
534
578
  const edrDataAddress = this.edrTokens.get(existingMapping.transferId);
535
579
  if (edrDataAddress) {
@@ -546,13 +590,13 @@ let __tla = (async () => {
546
590
  throw error2;
547
591
  }
548
592
  }
549
- async continueAssetAccess(negotiationId, assetId, counterPartyAddress, additionalPath) {
593
+ async continueAssetAccess(negotiationId, assetId, counterPartyAddress, additionalPath, providerParticipantId) {
550
594
  try {
551
- const agreement = await this.getContractAgreement(negotiationId);
595
+ const agreement = await this.getContractAgreement(negotiationId, providerParticipantId);
552
596
  if (!agreement) {
553
597
  throw new Error("Failed to retrieve contract agreement");
554
598
  }
555
- const transferId = await this.initiateEDRTransfer(assetId, counterPartyAddress, agreement["@id"]);
599
+ const transferId = await this.initiateEDRTransfer(assetId, counterPartyAddress, agreement["@id"], providerParticipantId);
556
600
  const edrDataAddress = await this.getEDRToken(transferId);
557
601
  if (!edrDataAddress) {
558
602
  throw new Error("Failed to retrieve EDR token");
@@ -564,8 +608,9 @@ let __tla = (async () => {
564
608
  throw error2;
565
609
  }
566
610
  }
567
- async accessStoredAssetData(assetId, additionalPath) {
568
- const mapping = this.assetAgreements.get(assetId);
611
+ async accessStoredAssetData(assetId, additionalPath, providerParticipantId) {
612
+ const key = this._makeAssetAgreementKey(assetId, providerParticipantId);
613
+ const mapping = this.assetAgreements.get(key);
569
614
  if (!(mapping == null ? void 0 : mapping.transferId)) {
570
615
  throw new Error(`No stored transfer information for asset: ${assetId}`);
571
616
  }
@@ -575,6 +620,107 @@ let __tla = (async () => {
575
620
  }
576
621
  return await this.fetchWithEDRToken(edrDataAddress, additionalPath);
577
622
  }
623
+ async fetchProtectedResource(resourceUrl, consumerParticipantId, consumerConnectorUrl, providerConnectorUrl, existingAgreementId, maxNegotiationRetries = 30, negotiationRetryDelay = 2e3) {
624
+ console.log(`\u{1F510} Requesting protected resource: ${resourceUrl}`);
625
+ if (existingAgreementId) {
626
+ console.log(`\u{1F4DC} Using existing agreement: ${existingAgreementId}`);
627
+ return await this._fetchWithAgreement(resourceUrl, consumerParticipantId, consumerConnectorUrl, existingAgreementId);
628
+ }
629
+ const initialResponse = await fetch(resourceUrl, {
630
+ method: "GET",
631
+ headers: {
632
+ "DSP-PARTICIPANT-ID": consumerParticipantId,
633
+ "DSP-CONSUMER-CONNECTORURL": consumerConnectorUrl,
634
+ Accept: "application/ld+json"
635
+ },
636
+ mode: "cors"
637
+ });
638
+ if (initialResponse.ok) {
639
+ const data2 = await initialResponse.json();
640
+ console.log("\u2705 Resource accessed successfully (no agreement required)");
641
+ return data2;
642
+ }
643
+ if (initialResponse.status !== 449) {
644
+ const errorText = await initialResponse.text();
645
+ throw new Error(`Unexpected response: ${initialResponse.status} ${initialResponse.statusText} - ${errorText}`);
646
+ }
647
+ const contractInfo = await this._handlePolicyDiscovery(initialResponse, providerConnectorUrl, maxNegotiationRetries, negotiationRetryDelay);
648
+ console.log("\u{1F504} Retrying resource request with agreement...");
649
+ const data = await this._fetchWithAgreement(resourceUrl, consumerParticipantId, consumerConnectorUrl, contractInfo.agreementId);
650
+ if (data && typeof data === "object") {
651
+ data[_DataspaceConnectorStore.AUTO_NEGOTIATED_CONTRACT_KEY] = {
652
+ agreementId: contractInfo.agreementId,
653
+ negotiationId: contractInfo.negotiationId,
654
+ assetId: contractInfo.assetId,
655
+ providerId: contractInfo.providerId,
656
+ providerConnectorUrl,
657
+ policy: contractInfo.policy,
658
+ resourceUrl
659
+ };
660
+ }
661
+ return data;
662
+ }
663
+ async _handlePolicyDiscovery(initialResponse, providerConnectorUrl, maxNegotiationRetries, negotiationRetryDelay) {
664
+ console.log("\u{1F4CB} Contract negotiation required (449 response)");
665
+ const errorResponse = await initialResponse.json();
666
+ const suggestedPolicies = errorResponse.suggested_policies;
667
+ if (!suggestedPolicies || suggestedPolicies.length === 0) {
668
+ throw new Error("No suggested policies returned in 449 response");
669
+ }
670
+ const bestPolicy = suggestedPolicies.reduce((best, current) => {
671
+ return current.openness_score > best.openness_score ? current : best;
672
+ });
673
+ console.log(`\u{1F4DC} Selected policy: ${bestPolicy.policy_id} (openness: ${bestPolicy.openness_score})`);
674
+ const providerId = errorResponse.provider_id || errorResponse.participant_id;
675
+ const assetId = errorResponse.asset_id;
676
+ console.log(`\u{1F3E2} Provider ID for negotiation: ${providerId}`);
677
+ console.log("\u{1F91D} Initiating contract negotiation...");
678
+ const negotiationId = await this.negotiateContract(providerConnectorUrl, assetId, bestPolicy.policy, providerId);
679
+ console.log(`\u{1F4DD} Negotiation initiated: ${negotiationId}`);
680
+ for (let attempt = 1; attempt <= maxNegotiationRetries; attempt++) {
681
+ await new Promise((resolve) => setTimeout(resolve, negotiationRetryDelay));
682
+ const status = await this._getNegotiationStatus(negotiationId);
683
+ console.log(`\u23F3 Negotiation status (${attempt}/${maxNegotiationRetries}): ${status.state}`);
684
+ if (status.state === "FINALIZED") {
685
+ const agreement = await this.getContractAgreement(negotiationId, providerId);
686
+ if (!agreement) {
687
+ throw new Error(`Failed to retrieve contract agreement for negotiation ${negotiationId}`);
688
+ }
689
+ console.log(`\u2705 Agreement obtained: ${agreement["@id"]}`);
690
+ return {
691
+ agreementId: agreement["@id"],
692
+ negotiationId,
693
+ assetId,
694
+ providerId,
695
+ policy: bestPolicy.policy
696
+ };
697
+ }
698
+ if (status.state === "TERMINATED") {
699
+ throw new Error(`Negotiation terminated: ${status.errorDetail || "Unknown reason"}`);
700
+ }
701
+ }
702
+ throw new Error(`Negotiation ${negotiationId} failed or timed out after ${maxNegotiationRetries} attempts`);
703
+ }
704
+ async _fetchWithAgreement(resourceUrl, consumerParticipantId, providerConnectorUrl, agreementId) {
705
+ console.log(`\u{1F510} Requesting protected resource: ${resourceUrl} (with agreement)`);
706
+ const response = await fetch(resourceUrl, {
707
+ method: "GET",
708
+ headers: {
709
+ "DSP-PARTICIPANT-ID": consumerParticipantId,
710
+ "DSP-CONSUMER-CONNECTORURL": providerConnectorUrl,
711
+ "DSP-AGREEMENT-ID": agreementId,
712
+ Accept: "application/ld+json"
713
+ },
714
+ mode: "cors"
715
+ });
716
+ if (!response.ok) {
717
+ const errorText = await response.text();
718
+ throw new Error(`Failed to access protected resource: ${response.status} ${response.statusText} - ${errorText}`);
719
+ }
720
+ const data = await response.json();
721
+ console.log("\u2705 Resource accessed successfully");
722
+ return data;
723
+ }
578
724
  async fetchThroughDataspace(resourceId) {
579
725
  try {
580
726
  const catalog = await this.getCatalog();
@@ -610,11 +756,11 @@ let __tla = (async () => {
610
756
  async ensureAuthenticated() {
611
757
  if (this.authToken && this.headers) return;
612
758
  switch (this.config.authMethod) {
613
- case "edc-api-key":
614
- if (!this.config.edcApiKey) {
615
- throw new Error("EDC API key required but not provided. Set edcApiKey in configuration.");
759
+ case "dsp-api-key":
760
+ if (!this.config.dspApiKey) {
761
+ throw new Error("DSP API key required but not provided. Set dspApiKey in configuration.");
616
762
  }
617
- this.authToken = this.config.edcApiKey;
763
+ this.authToken = this.config.dspApiKey;
618
764
  this.headers = {
619
765
  ...this.headers,
620
766
  "X-Api-Key": this.authToken
@@ -900,39 +1046,60 @@ let __tla = (async () => {
900
1046
  }
901
1047
  async updateAsset(assetId, assetInput) {
902
1048
  await this.ensureAuthenticated();
903
- const apiVersion = this.config.apiVersion || "v3";
904
- const assetsEndpoint = this.config.assetsEndpoint || this.config.catalogEndpoint.replace("/catalog/request", apiVersion === "v3" ? "/assets" : "/assets");
905
- const assetData = {
906
- "@context": {
907
- "@vocab": "https://w3id.org/edc/v0.0.1/ns/",
908
- edc: "https://w3id.org/edc/v0.0.1/ns/"
909
- },
910
- "@type": "Asset",
911
- "@id": assetInput["@id"],
912
- properties: assetInput.properties || {},
913
- dataAddress: assetInput.dataAddress
914
- };
915
- const response = await this.fetchAuthn(`${assetsEndpoint}/${assetId}`, {
916
- method: "PUT",
917
- headers: this.headers,
918
- body: JSON.stringify(assetData)
919
- });
920
- if (!response.ok) {
921
- const errorText = await response.text();
922
- throw new Error(`Failed to update asset: ${response.status} ${response.statusText} - ${errorText}`);
1049
+ const hasAgreement = this.hasValidAgreement(assetId);
1050
+ if (hasAgreement) {
1051
+ const message = `Cannot update asset ${assetId}: Asset has active contract agreements. Deleting an asset with agreements would invalidate existing contracts. Please terminate or complete all negotiations first.`;
1052
+ throw new AssetValidationError(message, assetId, "update", "agreements");
1053
+ }
1054
+ const negotiations = await this.getAllContractNegotiations();
1055
+ const activeNegotiations = negotiations.filter((neg) => neg.state !== "FINALIZED" && neg.state !== "TERMINATED" && neg.assetId === assetId);
1056
+ if (activeNegotiations.length > 0) {
1057
+ const message = `Cannot update asset ${assetId}: Asset has ${activeNegotiations.length} active contract negotiation(s). Please wait for negotiations to complete or terminate them first.`;
1058
+ throw new AssetValidationError(message, assetId, "update", "negotiations", {
1059
+ negotiationCount: activeNegotiations.length,
1060
+ negotiations: activeNegotiations
1061
+ });
1062
+ }
1063
+ console.log(`\u26A0\uFE0F Using DELETE + POST pattern to update asset ${assetId}`);
1064
+ try {
1065
+ const deleted = await this.deleteAsset(assetId, true);
1066
+ if (!deleted) {
1067
+ throw new Error(`Failed to delete existing asset ${assetId} for update`);
1068
+ }
1069
+ } catch (deleteError) {
1070
+ if (deleteError instanceof AssetValidationError) {
1071
+ throw new AssetValidationError(deleteError.message.replace("Cannot delete", "Cannot update"), assetId, "update", deleteError.reason, deleteError.details);
1072
+ }
1073
+ throw deleteError;
1074
+ }
1075
+ try {
1076
+ const updatedAsset = await this.createAsset(assetInput);
1077
+ console.log(`\u2705 Asset ${assetId} updated successfully via DELETE + POST`);
1078
+ return updatedAsset;
1079
+ } catch (createError) {
1080
+ console.error(`\u274C Critical: Failed to recreate asset ${assetId} after deletion`, createError);
1081
+ const errorMessage = createError instanceof Error ? createError.message : String(createError);
1082
+ throw new Error(`Failed to recreate asset after deletion: ${errorMessage}. Asset ${assetId} has been deleted but not recreated.`);
923
1083
  }
924
- const updatedAsset = {
925
- "@type": "Asset",
926
- "@id": assetInput["@id"],
927
- properties: assetInput.properties,
928
- dataAddress: assetInput.dataAddress,
929
- createdAt: Date.now()
930
- };
931
- await this.cache.set(assetId, updatedAsset);
932
- return updatedAsset;
933
1084
  }
934
- async deleteAsset(assetId) {
1085
+ async deleteAsset(assetId, skipAgreementCheck = false) {
935
1086
  await this.ensureAuthenticated();
1087
+ if (!skipAgreementCheck) {
1088
+ const hasAgreement = this.hasValidAgreement(assetId);
1089
+ if (hasAgreement) {
1090
+ const message = `Cannot delete asset ${assetId}: Asset has active contract agreements. Deleting an asset with agreements would invalidate existing contracts. Please terminate or complete all negotiations first.`;
1091
+ throw new AssetValidationError(message, assetId, "delete", "agreements");
1092
+ }
1093
+ const negotiations = await this.getAllContractNegotiations();
1094
+ const activeNegotiations = negotiations.filter((neg) => neg.state !== "FINALIZED" && neg.state !== "TERMINATED" && neg.assetId === assetId);
1095
+ if (activeNegotiations.length > 0) {
1096
+ const message = `Cannot delete asset ${assetId}: Asset has ${activeNegotiations.length} active contract negotiation(s). Please wait for negotiations to complete or terminate them first.`;
1097
+ throw new AssetValidationError(message, assetId, "delete", "negotiations", {
1098
+ negotiationCount: activeNegotiations.length,
1099
+ negotiations: activeNegotiations
1100
+ });
1101
+ }
1102
+ }
936
1103
  const apiVersion = this.config.apiVersion || "v3";
937
1104
  const assetsEndpoint = this.config.assetsEndpoint || this.config.catalogEndpoint.replace("/catalog/request", apiVersion === "v3" ? "/assets" : "/assets");
938
1105
  const response = await this.fetchAuthn(`${assetsEndpoint}/${assetId}`, {
@@ -941,9 +1108,28 @@ let __tla = (async () => {
941
1108
  });
942
1109
  if (!response.ok) {
943
1110
  const errorText = await response.text();
1111
+ if (response.status === 409) {
1112
+ try {
1113
+ const errorDetails = JSON.parse(errorText);
1114
+ const errorMessage = Array.isArray(errorDetails) && errorDetails.length > 0 ? errorDetails[0].message : errorText;
1115
+ const message = `Cannot delete asset ${assetId}: ${errorMessage}`;
1116
+ throw new AssetValidationError(message, assetId, "delete", "agreements", {
1117
+ apiResponse: errorDetails
1118
+ });
1119
+ } catch (parseError) {
1120
+ if (parseError instanceof AssetValidationError) {
1121
+ throw parseError;
1122
+ }
1123
+ const message = `Cannot delete asset ${assetId}: ${errorText}`;
1124
+ throw new AssetValidationError(message, assetId, "delete", "agreements", {
1125
+ rawError: errorText
1126
+ });
1127
+ }
1128
+ }
944
1129
  throw new Error(`Failed to delete asset: ${response.status} ${response.statusText} - ${errorText}`);
945
1130
  }
946
1131
  await this.cache.delete(assetId);
1132
+ this.assetAgreements.delete(assetId);
947
1133
  return true;
948
1134
  }
949
1135
  async getAllPolicies(querySpec) {
@@ -1203,29 +1389,352 @@ let __tla = (async () => {
1203
1389
  getExpandedPredicate(property, _context) {
1204
1390
  return property;
1205
1391
  }
1206
- }
1207
- const _DataspaceConnectorStoreAdapter = class _DataspaceConnectorStoreAdapter {
1392
+ };
1393
+ __publicField(_DataspaceConnectorStore, "AUTO_NEGOTIATED_CONTRACT_KEY", "__autoNegotiatedContract");
1394
+ let DataspaceConnectorStore = _DataspaceConnectorStore;
1395
+ class DataspaceConnectorStoreAdapter {
1208
1396
  constructor() {
1209
1397
  }
1210
1398
  static getStoreInstance(cfg) {
1211
- if (!_DataspaceConnectorStoreAdapter.store) {
1212
- if (!cfg) {
1213
- throw new Error("DataspaceConnectorStore configuration is required");
1399
+ var _a2;
1400
+ if (!cfg) {
1401
+ throw new Error("DataspaceConnectorStore configuration is required");
1402
+ }
1403
+ const dspConfig = cfg;
1404
+ console.log("\u{1F3ED} [DataspaceConnectorStoreAdapter.getStoreInstance] Creating new store with config:", {
1405
+ endpoint: dspConfig.endpoint,
1406
+ catalogEndpoint: dspConfig.catalogEndpoint,
1407
+ negotiationEndpoint: dspConfig.contractNegotiationEndpoint
1408
+ });
1409
+ const newStore = new DataspaceConnectorStore(dspConfig);
1410
+ console.log("\u2705 [DataspaceConnectorStoreAdapter.getStoreInstance] Created store:", {
1411
+ storeType: typeof newStore,
1412
+ configEndpoint: (_a2 = newStore.config) == null ? void 0 : _a2.endpoint
1413
+ });
1414
+ return newStore;
1415
+ }
1416
+ }
1417
+ DEFAULT_AUTH_SELECTORS = [
1418
+ "sib-auth-oidc",
1419
+ "sib-auth"
1420
+ ];
1421
+ function findAuthElement(selectors = [
1422
+ ...DEFAULT_AUTH_SELECTORS
1423
+ ]) {
1424
+ for (const selector of selectors) {
1425
+ const element = document.querySelector(selector);
1426
+ if (element && typeof element.getFetch === "function") {
1427
+ return element;
1428
+ }
1429
+ }
1430
+ return null;
1431
+ }
1432
+ function getAuthFetch(selectors) {
1433
+ const authElement = findAuthElement(selectors);
1434
+ if (authElement) {
1435
+ try {
1436
+ const authFetch = authElement.getFetch();
1437
+ if (typeof authFetch === "function") {
1438
+ return authFetch;
1214
1439
  }
1215
- _DataspaceConnectorStoreAdapter.store = new DataspaceConnectorStore(cfg);
1440
+ } catch (error2) {
1441
+ console.warn("[AuthFetchResolver] Error getting auth fetch:", error2);
1216
1442
  }
1217
- return _DataspaceConnectorStoreAdapter.store;
1218
1443
  }
1444
+ return fetch.bind(globalThis);
1445
+ }
1446
+ function onAuthActivated(callback, eventName = "sib-auth:activated") {
1447
+ const handler2 = (event) => {
1448
+ var _a2;
1449
+ if (((_a2 = event.detail) == null ? void 0 : _a2.fetch) && typeof event.detail.fetch === "function") {
1450
+ callback(event);
1451
+ }
1452
+ };
1453
+ document.addEventListener(eventName, handler2);
1454
+ return () => {
1455
+ document.removeEventListener(eventName, handler2);
1456
+ };
1457
+ }
1458
+ async function waitForAuthElement(selectors = [
1459
+ ...DEFAULT_AUTH_SELECTORS
1460
+ ], timeout = 5e3) {
1461
+ const existing = findAuthElement(selectors);
1462
+ if (existing) {
1463
+ return existing;
1464
+ }
1465
+ return new Promise((resolve, reject) => {
1466
+ const observer = new MutationObserver(() => {
1467
+ const element = findAuthElement(selectors);
1468
+ if (element) {
1469
+ observer.disconnect();
1470
+ resolve(element);
1471
+ }
1472
+ });
1473
+ observer.observe(document.body, {
1474
+ childList: true,
1475
+ subtree: true
1476
+ });
1477
+ setTimeout(() => {
1478
+ observer.disconnect();
1479
+ reject(new Error(`No auth element found with selectors: ${selectors.join(", ")}`));
1480
+ }, timeout);
1481
+ });
1482
+ }
1483
+ AuthFetchResolver = {
1484
+ findAuthElement,
1485
+ getAuthFetch,
1486
+ onAuthActivated,
1487
+ waitForAuthElement
1219
1488
  };
1220
- __publicField(_DataspaceConnectorStoreAdapter, "store");
1221
- let DataspaceConnectorStoreAdapter = _DataspaceConnectorStoreAdapter;
1489
+ const _LocalStorageCacheMetadataManager = class _LocalStorageCacheMetadataManager {
1490
+ constructor(endpoint, ttlMs = _LocalStorageCacheMetadataManager.DEFAULT_TTL_MS) {
1491
+ this.endpoint = endpoint;
1492
+ this.ttlMs = ttlMs;
1493
+ this.cleanupOldCacheFormat();
1494
+ }
1495
+ cleanupOldCacheFormat() {
1496
+ try {
1497
+ const endpointHash = this.endpoint.replace(/[^a-zA-Z0-9]/g, "");
1498
+ const oldKey = `fc-cache-meta-${endpointHash}`;
1499
+ if (localStorage.getItem(oldKey)) {
1500
+ localStorage.removeItem(oldKey);
1501
+ }
1502
+ } catch (error2) {
1503
+ console.warn("[LocalStorageCache] Error cleaning up old cache format:", error2);
1504
+ }
1505
+ }
1506
+ getStorageKey() {
1507
+ const endpointHash = this.endpoint.replace(/[^a-zA-Z0-9]/g, "");
1508
+ return `${_LocalStorageCacheMetadataManager.STORAGE_KEY_PREFIX}-${endpointHash}`;
1509
+ }
1510
+ getCacheData() {
1511
+ try {
1512
+ const key = this.getStorageKey();
1513
+ const data = localStorage.getItem(key);
1514
+ if (!data) {
1515
+ return null;
1516
+ }
1517
+ const parsed = JSON.parse(data);
1518
+ const items = /* @__PURE__ */ new Map();
1519
+ if (parsed.items) {
1520
+ for (const [hash, metadata] of Object.entries(parsed.items)) {
1521
+ items.set(hash, metadata);
1522
+ }
1523
+ }
1524
+ return {
1525
+ version: parsed.version,
1526
+ lastFetchTimestamp: parsed.lastFetchTimestamp,
1527
+ cacheExpirationTimestamp: parsed.cacheExpirationTimestamp,
1528
+ resource: parsed.resource,
1529
+ items
1530
+ };
1531
+ } catch (error2) {
1532
+ console.error("[LocalStorageCache] Error reading cache data:", error2);
1533
+ return null;
1534
+ }
1535
+ }
1536
+ getCacheMetadata() {
1537
+ return this.getCacheData();
1538
+ }
1539
+ setCacheData(cacheData) {
1540
+ try {
1541
+ const key = this.getStorageKey();
1542
+ const itemsObj = {};
1543
+ cacheData.items.forEach((value, hash) => {
1544
+ itemsObj[hash] = value;
1545
+ });
1546
+ const data = JSON.stringify({
1547
+ version: cacheData.version,
1548
+ lastFetchTimestamp: cacheData.lastFetchTimestamp,
1549
+ cacheExpirationTimestamp: cacheData.cacheExpirationTimestamp,
1550
+ resource: cacheData.resource,
1551
+ items: itemsObj
1552
+ });
1553
+ localStorage.setItem(key, data);
1554
+ return true;
1555
+ } catch (error2) {
1556
+ console.error("[LocalStorageCache] Error writing cache data:", error2);
1557
+ return false;
1558
+ }
1559
+ }
1560
+ setCacheMetadata(cacheData) {
1561
+ return this.setCacheData(cacheData);
1562
+ }
1563
+ isCacheValid() {
1564
+ const cacheData = this.getCacheData();
1565
+ if (!cacheData) {
1566
+ return false;
1567
+ }
1568
+ if (cacheData.version !== _LocalStorageCacheMetadataManager.CACHE_VERSION) {
1569
+ console.log("[LocalStorageCache] Cache version mismatch, invalidating");
1570
+ return false;
1571
+ }
1572
+ const now = Date.now();
1573
+ if (now > cacheData.cacheExpirationTimestamp) {
1574
+ console.log("[LocalStorageCache] Cache TTL expired");
1575
+ return false;
1576
+ }
1577
+ return true;
1578
+ }
1579
+ getResource() {
1580
+ const cacheData = this.getCacheData();
1581
+ return (cacheData == null ? void 0 : cacheData.resource) || null;
1582
+ }
1583
+ getKnownHashes() {
1584
+ const cacheData = this.getCacheData();
1585
+ if (!cacheData) {
1586
+ return /* @__PURE__ */ new Set();
1587
+ }
1588
+ return new Set(cacheData.items.keys());
1589
+ }
1590
+ getItemMetadata(sdHash) {
1591
+ const cacheData = this.getCacheData();
1592
+ if (!cacheData) {
1593
+ return null;
1594
+ }
1595
+ return cacheData.items.get(sdHash) || null;
1596
+ }
1597
+ updateCache(resource, items) {
1598
+ const now = Date.now();
1599
+ let cacheData = this.getCacheData();
1600
+ if (!cacheData || !this.isCacheValid()) {
1601
+ cacheData = {
1602
+ version: _LocalStorageCacheMetadataManager.CACHE_VERSION,
1603
+ lastFetchTimestamp: now,
1604
+ cacheExpirationTimestamp: now + this.ttlMs,
1605
+ resource,
1606
+ items: /* @__PURE__ */ new Map()
1607
+ };
1608
+ } else {
1609
+ cacheData.resource = resource;
1610
+ }
1611
+ for (const item of items) {
1612
+ cacheData.items.set(item.sdHash, {
1613
+ ...item,
1614
+ cachedAt: now
1615
+ });
1616
+ }
1617
+ cacheData.lastFetchTimestamp = now;
1618
+ return this.setCacheData(cacheData);
1619
+ }
1620
+ removeItems(sdHashes) {
1621
+ var _a2;
1622
+ const cacheData = this.getCacheData();
1623
+ if (!cacheData) {
1624
+ return false;
1625
+ }
1626
+ for (const hash of sdHashes) {
1627
+ cacheData.items.delete(hash);
1628
+ }
1629
+ if ((_a2 = cacheData.resource) == null ? void 0 : _a2["ldp:contains"]) {
1630
+ const resourceIdsToRemove = /* @__PURE__ */ new Set();
1631
+ for (const hash of sdHashes) {
1632
+ const meta = cacheData.items.get(hash);
1633
+ if (meta) {
1634
+ resourceIdsToRemove.add(meta.resourceId);
1635
+ }
1636
+ }
1637
+ cacheData.resource["ldp:contains"] = cacheData.resource["ldp:contains"].filter((item) => !resourceIdsToRemove.has(item["@id"]));
1638
+ }
1639
+ return this.setCacheData(cacheData);
1640
+ }
1641
+ clear() {
1642
+ try {
1643
+ const key = this.getStorageKey();
1644
+ localStorage.removeItem(key);
1645
+ return true;
1646
+ } catch (error2) {
1647
+ console.error("[LocalStorageCache] Error clearing cache data:", error2);
1648
+ return false;
1649
+ }
1650
+ }
1651
+ getCacheStats() {
1652
+ const cacheData = this.getCacheData();
1653
+ if (!cacheData) {
1654
+ return {
1655
+ itemCount: 0,
1656
+ lastFetch: null,
1657
+ expiresAt: null,
1658
+ isValid: false
1659
+ };
1660
+ }
1661
+ return {
1662
+ itemCount: cacheData.items.size,
1663
+ lastFetch: new Date(cacheData.lastFetchTimestamp),
1664
+ expiresAt: new Date(cacheData.cacheExpirationTimestamp),
1665
+ isValid: this.isCacheValid()
1666
+ };
1667
+ }
1668
+ };
1669
+ __publicField(_LocalStorageCacheMetadataManager, "STORAGE_KEY_PREFIX", "fc-cache-data");
1670
+ __publicField(_LocalStorageCacheMetadataManager, "CACHE_VERSION", "2.0.0");
1671
+ __publicField(_LocalStorageCacheMetadataManager, "DEFAULT_TTL_MS", 2 * 60 * 60 * 1e3);
1672
+ let LocalStorageCacheMetadataManager = _LocalStorageCacheMetadataManager;
1222
1673
  class FederatedCatalogueAPIWrapper {
1223
- constructor(options, fcBaseUrl) {
1674
+ constructor(options, fcBaseUrl, fetchAuth) {
1224
1675
  __publicField(this, "fcBaseUrl");
1225
- __publicField(this, "connect");
1676
+ __publicField(this, "loginOptions");
1677
+ __publicField(this, "tokenState", null);
1678
+ __publicField(this, "tokenRefreshBuffer", 5 * 60 * 1e3);
1679
+ __publicField(this, "isRefreshing", false);
1680
+ __publicField(this, "refreshPromise", null);
1681
+ __publicField(this, "STORAGE_KEY", "fc_token_state");
1682
+ __publicField(this, "_fetch");
1683
+ __publicField(this, "useKeycloakAuth");
1226
1684
  this.fcBaseUrl = fcBaseUrl;
1227
- const connection = this.firstConnect(options);
1228
- this.connect = () => connection;
1685
+ this.loginOptions = options;
1686
+ if (fetchAuth && (!options.kc_url || options.kc_url === "")) {
1687
+ this._fetch = fetchAuth;
1688
+ this.useKeycloakAuth = false;
1689
+ } else {
1690
+ this._fetch = fetch.bind(globalThis);
1691
+ this.useKeycloakAuth = true;
1692
+ this.loadTokenState();
1693
+ }
1694
+ if (this.useKeycloakAuth) {
1695
+ try {
1696
+ this.firstConnect(options);
1697
+ } catch (e) {
1698
+ console.log("Error while establishing the first connection", e);
1699
+ }
1700
+ }
1701
+ }
1702
+ saveTokenState() {
1703
+ if (this.tokenState) {
1704
+ try {
1705
+ localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.tokenState));
1706
+ console.log("\u{1F4BE} [FederatedCatalogueAPIWrapper] Token state saved to localStorage");
1707
+ } catch (error2) {
1708
+ console.error("Failed to save token state to localStorage:", error2);
1709
+ }
1710
+ }
1711
+ }
1712
+ loadTokenState() {
1713
+ var _a2, _b, _c;
1714
+ try {
1715
+ const stored = localStorage.getItem(this.STORAGE_KEY);
1716
+ if (stored) {
1717
+ this.tokenState = JSON.parse(stored);
1718
+ console.log("\u{1F4C2} [FederatedCatalogueAPIWrapper] Token state loaded from localStorage:", {
1719
+ hasAccessToken: !!((_a2 = this.tokenState) == null ? void 0 : _a2.access_token),
1720
+ hasRefreshToken: !!((_b = this.tokenState) == null ? void 0 : _b.refresh_token),
1721
+ expiresAt: (_c = this.tokenState) == null ? void 0 : _c.expires_at,
1722
+ isExpired: this.tokenState ? Date.now() >= this.tokenState.expires_at : "N/A"
1723
+ });
1724
+ }
1725
+ } catch (error2) {
1726
+ console.error("Failed to load token state from localStorage:", error2);
1727
+ this.clearTokenState();
1728
+ }
1729
+ }
1730
+ clearTokenState() {
1731
+ this.tokenState = null;
1732
+ try {
1733
+ localStorage.removeItem(this.STORAGE_KEY);
1734
+ console.log("\u{1F5D1}\uFE0F [FederatedCatalogueAPIWrapper] Token state cleared");
1735
+ } catch (error2) {
1736
+ console.error("Failed to clear token state from localStorage:", error2);
1737
+ }
1229
1738
  }
1230
1739
  async firstConnect(options) {
1231
1740
  const body = new URLSearchParams({
@@ -1239,7 +1748,7 @@ let __tla = (async () => {
1239
1748
  const headers = new Headers({
1240
1749
  "Content-Type": "application/x-www-form-urlencoded"
1241
1750
  });
1242
- const response = await fetch(options.kc_url, {
1751
+ const response = await this._fetch(options.kc_url, {
1243
1752
  method: "POST",
1244
1753
  headers,
1245
1754
  body
@@ -1251,28 +1760,130 @@ let __tla = (async () => {
1251
1760
  cause: data
1252
1761
  });
1253
1762
  }
1763
+ this.tokenState = {
1764
+ access_token: token,
1765
+ refresh_token: data.refresh_token || null,
1766
+ expires_at: Date.now() + (data.expires_in || 3600) * 1e3
1767
+ };
1768
+ this.saveTokenState();
1254
1769
  return token;
1255
1770
  }
1256
- async getAllSelfDescriptions() {
1257
- const token = await this.connect();
1258
- const url2 = `${this.fcBaseUrl}/self-descriptions`;
1259
- const headers = new Headers({
1260
- Authorization: `Bearer ${token}`
1261
- });
1262
- const response = await fetch(url2, {
1771
+ async refreshToken() {
1772
+ if (this.isRefreshing && this.refreshPromise) {
1773
+ return this.refreshPromise;
1774
+ }
1775
+ this.isRefreshing = true;
1776
+ this.refreshPromise = this._performRefresh();
1777
+ try {
1778
+ const token = await this.refreshPromise;
1779
+ return token;
1780
+ } finally {
1781
+ this.isRefreshing = false;
1782
+ this.refreshPromise = null;
1783
+ }
1784
+ }
1785
+ async _performRefresh() {
1786
+ var _a2;
1787
+ if (!((_a2 = this.tokenState) == null ? void 0 : _a2.refresh_token)) {
1788
+ console.log("No refresh token available, re-authenticating with credentials");
1789
+ return this.firstConnect(this.loginOptions);
1790
+ }
1791
+ try {
1792
+ const body = new URLSearchParams({
1793
+ grant_type: "refresh_token",
1794
+ client_id: this.loginOptions.kc_client_id,
1795
+ client_secret: this.loginOptions.kc_client_secret,
1796
+ refresh_token: this.tokenState.refresh_token
1797
+ });
1798
+ const headers = new Headers({
1799
+ "Content-Type": "application/x-www-form-urlencoded"
1800
+ });
1801
+ const response = await this._fetch(this.loginOptions.kc_url, {
1802
+ method: "POST",
1803
+ headers,
1804
+ body
1805
+ });
1806
+ if (!response.ok) {
1807
+ console.warn("Token refresh failed, re-authenticating with credentials");
1808
+ return this.firstConnect(this.loginOptions);
1809
+ }
1810
+ const data = await response.json();
1811
+ const token = data.access_token;
1812
+ if (token == null) {
1813
+ throw new Error("Token refresh failed: no access_token in response", {
1814
+ cause: data
1815
+ });
1816
+ }
1817
+ this.tokenState = {
1818
+ access_token: token,
1819
+ refresh_token: data.refresh_token || this.tokenState.refresh_token,
1820
+ expires_at: Date.now() + (data.expires_in || 3600) * 1e3
1821
+ };
1822
+ this.saveTokenState();
1823
+ return token;
1824
+ } catch (error2) {
1825
+ console.error("Error refreshing token:", error2);
1826
+ this.clearTokenState();
1827
+ return this.firstConnect(this.loginOptions);
1828
+ }
1829
+ }
1830
+ async getValidToken() {
1831
+ if (!this.tokenState) {
1832
+ return await this.firstConnect(this.loginOptions);
1833
+ }
1834
+ const now = Date.now();
1835
+ const isExpiringSoon = now >= this.tokenState.expires_at - this.tokenRefreshBuffer;
1836
+ if (isExpiringSoon) {
1837
+ return await this.refreshToken();
1838
+ }
1839
+ return this.tokenState.access_token;
1840
+ }
1841
+ async fetchWithAuth(url2, options = {}) {
1842
+ var _a2;
1843
+ if (!this.useKeycloakAuth) {
1844
+ return this._fetch(url2, options);
1845
+ }
1846
+ const token = await this.getValidToken();
1847
+ const headers = new Headers(options.headers);
1848
+ headers.set("Authorization", `Bearer ${token}`);
1849
+ let response = await this._fetch(url2, {
1850
+ ...options,
1263
1851
  headers
1264
1852
  });
1853
+ if (response.status === 401 || response.status === 403) {
1854
+ console.log(`\u{1F510} [FederatedCatalogueAPIWrapper] Authentication failed (${response.status}) for ${url2}`);
1855
+ console.log("\u{1F504} [FederatedCatalogueAPIWrapper] Attempting token refresh...", {
1856
+ hasRefreshToken: !!((_a2 = this.tokenState) == null ? void 0 : _a2.refresh_token),
1857
+ tokenExpired: this.tokenState ? Date.now() >= this.tokenState.expires_at : "N/A"
1858
+ });
1859
+ try {
1860
+ const newToken = await this.refreshToken();
1861
+ console.log("\u2705 [FederatedCatalogueAPIWrapper] Token refreshed successfully, retrying request...");
1862
+ headers.set("Authorization", `Bearer ${newToken}`);
1863
+ response = await this._fetch(url2, {
1864
+ ...options,
1865
+ headers
1866
+ });
1867
+ if (response.status === 401 || response.status === 403) {
1868
+ console.error(`\u274C [FederatedCatalogueAPIWrapper] Authentication still failed after token refresh (${response.status}). Please check credentials.`);
1869
+ } else {
1870
+ console.log(`\u2705 [FederatedCatalogueAPIWrapper] Retry succeeded with status ${response.status}`);
1871
+ }
1872
+ } catch (error2) {
1873
+ console.error("\u274C [FederatedCatalogueAPIWrapper] Failed to refresh token:", error2);
1874
+ }
1875
+ }
1876
+ return response;
1877
+ }
1878
+ async getAllSelfDescriptions() {
1879
+ const url2 = `${this.fcBaseUrl}/self-descriptions`;
1880
+ const response = await this.fetchWithAuth(url2);
1265
1881
  return await response.json();
1266
1882
  }
1267
1883
  async getSelfDescriptionByHash(sdHash) {
1268
- const token = await this.connect();
1269
1884
  const url2 = `${this.fcBaseUrl}/self-descriptions/${sdHash}`;
1270
- const headers = new Headers({
1271
- Authorization: `Bearer ${token}`
1272
- });
1273
- const response = await fetch(url2, {
1274
- method: "GET",
1275
- headers
1885
+ const response = await this.fetchWithAuth(url2, {
1886
+ method: "GET"
1276
1887
  });
1277
1888
  if (!response.ok) throw new Error(`GET /self-descriptions/${sdHash} failed: ${response.status} ${response.statusText}`, {
1278
1889
  cause: response
@@ -1280,19 +1891,16 @@ let __tla = (async () => {
1280
1891
  return await response.json();
1281
1892
  }
1282
1893
  async postQuery(statement, parameters = {}) {
1283
- const token = await this.connect();
1284
1894
  const url2 = `${this.fcBaseUrl}/query`;
1285
- const headers = new Headers({
1286
- Authorization: `Bearer ${token}`,
1287
- "Content-Type": "application/json"
1288
- });
1289
1895
  const body = JSON.stringify({
1290
1896
  statement,
1291
1897
  parameters
1292
1898
  });
1293
- const response = await fetch(url2, {
1899
+ const response = await this.fetchWithAuth(url2, {
1294
1900
  method: "POST",
1295
- headers,
1901
+ headers: {
1902
+ "Content-Type": "application/json"
1903
+ },
1296
1904
  body
1297
1905
  });
1298
1906
  if (!response.ok) {
@@ -1303,12 +1911,7 @@ let __tla = (async () => {
1303
1911
  return await response.json();
1304
1912
  }
1305
1913
  async postQuerySearch(statement, parameters = {}, queryLanguage = "OPENCYPHER", annotations) {
1306
- const token = await this.connect();
1307
1914
  const url2 = `${this.fcBaseUrl}/query/search`;
1308
- const headers = new Headers({
1309
- Authorization: `Bearer ${token}`,
1310
- "Content-Type": "application/json"
1311
- });
1312
1915
  const body = JSON.stringify({
1313
1916
  statement,
1314
1917
  parameters,
@@ -1316,9 +1919,11 @@ let __tla = (async () => {
1316
1919
  queryLanguage
1317
1920
  }
1318
1921
  });
1319
- const response = await fetch(url2, {
1922
+ const response = await this.fetchWithAuth(url2, {
1320
1923
  method: "POST",
1321
- headers,
1924
+ headers: {
1925
+ "Content-Type": "application/json"
1926
+ },
1322
1927
  body
1323
1928
  });
1324
1929
  if (!response.ok) {
@@ -1329,55 +1934,272 @@ let __tla = (async () => {
1329
1934
  return await response.json();
1330
1935
  }
1331
1936
  }
1332
- function getFederatedCatalogueAPIWrapper(baseUrl, optionLogin, optionsServer) {
1333
- const options = Object.assign({}, optionsServer, optionLogin);
1334
- return new FederatedCatalogueAPIWrapper(options, baseUrl);
1937
+ function getFederatedCatalogueAPIWrapper(baseUrl, loginOptions, fetch2) {
1938
+ return new FederatedCatalogueAPIWrapper(loginOptions, baseUrl, fetch2);
1335
1939
  }
1336
1940
  class FederatedCatalogueStore {
1337
1941
  constructor(cfg) {
1338
1942
  __publicField(this, "cache");
1339
- __publicField(this, "session");
1340
1943
  __publicField(this, "fcApi");
1944
+ __publicField(this, "metadataManager");
1945
+ __publicField(this, "enableCaching");
1946
+ __publicField(this, "cleanupAuth");
1947
+ __publicField(this, "isFetching", false);
1948
+ __publicField(this, "pendingGetData", null);
1949
+ __publicField(this, "resolveFetch", (event) => {
1950
+ if (!this.cfg.endpoint) {
1951
+ throw new Error("Missing required `endpoint` in StoreConfig for FederatedCatalogueStore");
1952
+ }
1953
+ if (event.detail.fetch) {
1954
+ this.fcApi = getFederatedCatalogueAPIWrapper(this.cfg.endpoint, event.detail.fetch);
1955
+ }
1956
+ });
1341
1957
  this.cfg = cfg;
1342
- if (!this.cfg.login) {
1343
- throw new Error("Login must be provided for FederatedCatalogueStore");
1344
- }
1345
1958
  if (!this.cfg.endpoint) {
1346
1959
  throw new Error("Missing required `endpoint` in StoreConfig for FederatedCatalogueStore");
1347
1960
  }
1348
- if (!this.cfg.optionsServer) {
1349
- throw new Error("Missing required `optionsServer` in StoreConfig for FederatedCatalogueStore");
1961
+ const fetchAuth = AuthFetchResolver.getAuthFetch();
1962
+ this.cleanupAuth = AuthFetchResolver.onAuthActivated(this.resolveFetch.bind(this));
1963
+ if (fetchAuth && !this.cfg.login) {
1964
+ this.fcApi = getFederatedCatalogueAPIWrapper(this.cfg.endpoint, {}, fetchAuth);
1965
+ } else {
1966
+ this.fcApi = getFederatedCatalogueAPIWrapper(this.cfg.endpoint, this.cfg.login, fetchAuth);
1350
1967
  }
1351
- this.fcApi = getFederatedCatalogueAPIWrapper(this.cfg.endpoint, this.cfg.login, this.cfg.optionsServer);
1352
1968
  this.cache = new InMemoryCacheManager();
1969
+ this.enableCaching = this.cfg.enableLocalStorageMetadata === true;
1970
+ if (this.enableCaching && this.cfg.endpoint) {
1971
+ const cacheTTL = this.cfg.cacheTTL || 2 * 60 * 60 * 1e3;
1972
+ this.metadataManager = new LocalStorageCacheMetadataManager(this.cfg.endpoint, cacheTTL);
1973
+ this.handlePageReload();
1974
+ } else {
1975
+ this.metadataManager = null;
1976
+ }
1977
+ }
1978
+ disconnectedCallback() {
1979
+ var _a2;
1980
+ (_a2 = this.cleanupAuth) == null ? void 0 : _a2.call(this);
1981
+ }
1982
+ handlePageReload() {
1983
+ var _a2, _b;
1984
+ try {
1985
+ const SESSION_KEY = "fc-session-id";
1986
+ let sessionId = sessionStorage.getItem(SESSION_KEY);
1987
+ if (!sessionId) {
1988
+ sessionId = `session-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1989
+ sessionStorage.setItem(SESSION_KEY, sessionId);
1990
+ (_a2 = this.metadataManager) == null ? void 0 : _a2.clear();
1991
+ }
1992
+ const stats = (_b = this.metadataManager) == null ? void 0 : _b.getCacheStats();
1993
+ if (stats) {
1994
+ }
1995
+ } catch (error2) {
1996
+ console.warn("[FederatedCatalogueStore] Error handling page reload:", error2);
1997
+ }
1998
+ }
1999
+ resolveTargetType(args) {
2000
+ if (typeof args === "string") return args;
2001
+ if (typeof args === "object" && args !== null) {
2002
+ return args.targetType ?? args.id ?? "";
2003
+ }
2004
+ return "";
2005
+ }
2006
+ buildContainerId(containerType = "default") {
2007
+ var _a2;
2008
+ const endpointHash = ((_a2 = this.cfg.endpoint) == null ? void 0 : _a2.replace(/[^a-zA-Z0-9]/g, "")) || "unknown";
2009
+ return `store://local.fc-${endpointHash}-${containerType}/`;
1353
2010
  }
1354
2011
  async getData(args) {
1355
- const targetType = "targetType" in args ? args.targetType : args.id;
2012
+ if (this.isFetching) {
2013
+ if (this.pendingGetData) {
2014
+ return this.pendingGetData;
2015
+ }
2016
+ return null;
2017
+ }
2018
+ this.isFetching = true;
2019
+ const executeGetData = async () => {
2020
+ var _a2;
2021
+ const targetType = this.resolveTargetType(args);
2022
+ if (!this.fcApi) {
2023
+ throw new Error("Federated API not initialized, returning empty data.");
2024
+ }
2025
+ const cacheIsValid = this.enableCaching && ((_a2 = this.metadataManager) == null ? void 0 : _a2.isCacheValid());
2026
+ const hasCached = this.hasCachedData();
2027
+ if (cacheIsValid && hasCached) {
2028
+ return await this.getDeltaUpdatedData(targetType);
2029
+ }
2030
+ if (cacheIsValid && !hasCached && this.metadataManager) {
2031
+ this.metadataManager.clear();
2032
+ }
2033
+ return await this.getFullData(targetType);
2034
+ };
2035
+ this.pendingGetData = executeGetData().finally(() => {
2036
+ this.isFetching = false;
2037
+ this.pendingGetData = null;
2038
+ });
2039
+ return this.pendingGetData;
2040
+ }
2041
+ hasCachedData() {
2042
+ try {
2043
+ if (!this.metadataManager) {
2044
+ return false;
2045
+ }
2046
+ const resource = this.metadataManager.getResource();
2047
+ const hasResourceData = !!((resource == null ? void 0 : resource["ldp:contains"]) && resource["ldp:contains"].length > 0);
2048
+ const metadataItemCount = this.metadataManager.getCacheStats().itemCount || 0;
2049
+ return hasResourceData && metadataItemCount > 0;
2050
+ } catch (error2) {
2051
+ console.error("[FederatedCatalogueStore] Error checking cached data:", error2);
2052
+ return false;
2053
+ }
2054
+ }
2055
+ async getDeltaUpdatedData(targetType) {
2056
+ if (!this.fcApi || !this.metadataManager) {
2057
+ return await this.getFullData(targetType);
2058
+ }
2059
+ try {
2060
+ const apiList = await this.fcApi.getAllSelfDescriptions();
2061
+ if (!apiList || !apiList.items) {
2062
+ console.warn("[FederatedCatalogueStore] No items returned from API");
2063
+ return await this.getFullData(targetType);
2064
+ }
2065
+ const resource = this.metadataManager.getResource();
2066
+ if (!resource) {
2067
+ return await this.getFullData(targetType);
2068
+ }
2069
+ if (!resource["@id"]) {
2070
+ resource["@id"] = this.buildContainerId();
2071
+ }
2072
+ if (!resource["ldp:contains"]) {
2073
+ resource["ldp:contains"] = [];
2074
+ }
2075
+ const knownHashes = this.metadataManager.getKnownHashes();
2076
+ const items = (apiList == null ? void 0 : apiList.items) || [];
2077
+ if (!Array.isArray(items)) {
2078
+ console.warn("[FederatedCatalogueStore] apiList.items is not an array");
2079
+ return resource;
2080
+ }
2081
+ const apiHashes = new Set(items.map((item) => item.meta.sdHash));
2082
+ const newHashes = [];
2083
+ const updatedHashes = [];
2084
+ const deletedHashes = [];
2085
+ for (const item of items) {
2086
+ const hash = item.meta.sdHash;
2087
+ if (!knownHashes.has(hash)) {
2088
+ newHashes.push(hash);
2089
+ } else {
2090
+ const cachedMeta = this.metadataManager.getItemMetadata(hash);
2091
+ if (cachedMeta) {
2092
+ if (item.meta.uploadDatetime > cachedMeta.uploadDatetime || item.meta.statusDatetime > cachedMeta.statusDatetime) {
2093
+ updatedHashes.push(hash);
2094
+ }
2095
+ }
2096
+ }
2097
+ }
2098
+ for (const hash of knownHashes) {
2099
+ if (!apiHashes.has(hash)) {
2100
+ deletedHashes.push(hash);
2101
+ }
2102
+ }
2103
+ const toFetch = [
2104
+ ...newHashes,
2105
+ ...updatedHashes
2106
+ ];
2107
+ const newMetadata = [];
2108
+ if (toFetch.length > 0) {
2109
+ for (const hash of toFetch) {
2110
+ try {
2111
+ const sd = await this.fcApi.getSelfDescriptionByHash(hash);
2112
+ if (sd) {
2113
+ const mappedResource = this.mapSourceToDestination(sd, {
2114
+ temsServiceBase: this.cfg.temsServiceBase,
2115
+ temsCategoryBase: this.cfg.temsCategoryBase,
2116
+ temsImageBase: this.cfg.temsImageBase,
2117
+ temsProviderBase: this.cfg.temsProviderBase
2118
+ });
2119
+ if (updatedHashes.includes(hash)) {
2120
+ const index = resource["ldp:contains"].findIndex((r) => r["@id"] === mappedResource["@id"]);
2121
+ if (index !== -1) {
2122
+ resource["ldp:contains"].splice(index, 1);
2123
+ }
2124
+ }
2125
+ resource["ldp:contains"].push(mappedResource);
2126
+ const apiItem = apiList.items.find((i) => i.meta.sdHash === hash);
2127
+ if (apiItem) {
2128
+ newMetadata.push({
2129
+ sdHash: hash,
2130
+ uploadDatetime: apiItem.meta.uploadDatetime,
2131
+ statusDatetime: apiItem.meta.statusDatetime,
2132
+ cachedAt: Date.now(),
2133
+ resourceId: mappedResource["@id"]
2134
+ });
2135
+ }
2136
+ }
2137
+ } catch (error2) {
2138
+ console.error(`[FederatedCatalogueStore] Error fetching hash ${hash}:`, error2);
2139
+ }
2140
+ }
2141
+ }
2142
+ if (deletedHashes.length > 0) {
2143
+ this.metadataManager.removeItems(deletedHashes);
2144
+ }
2145
+ if (newMetadata.length > 0) {
2146
+ this.metadataManager.updateCache(resource, newMetadata);
2147
+ }
2148
+ document.dispatchEvent(new CustomEvent("save", {
2149
+ detail: {
2150
+ resource: {
2151
+ "@id": resource == null ? void 0 : resource["@id"]
2152
+ }
2153
+ },
2154
+ bubbles: true
2155
+ }));
2156
+ return resource;
2157
+ } catch (error2) {
2158
+ console.error("[FederatedCatalogueStore] Delta update failed, falling back to full fetch:", error2);
2159
+ return await this.getFullData(targetType);
2160
+ }
2161
+ }
2162
+ async getFullData(_targetType) {
1356
2163
  if (!this.fcApi) {
1357
- throw new Error("Federated API not initialized, returning empty data.");
1358
- }
1359
- let resource = await this.get(targetType);
1360
- if (!resource || resource["ldp:contains"].length === 0) {
1361
- resource = await this.initLocalDataSourceContainer(targetType);
1362
- const dataset2 = await this.fcApi.getAllSelfDescriptions();
1363
- for (const item in dataset2.items) {
1364
- const sd = await this.fcApi.getSelfDescriptionByHash(dataset2.items[item].meta.sdHash);
2164
+ throw new Error("Federated API not initialized");
2165
+ }
2166
+ const resource = await this.initLocalDataSourceContainer();
2167
+ const dataset2 = await this.fcApi.getAllSelfDescriptions();
2168
+ const newMetadata = [];
2169
+ if ((dataset2 == null ? void 0 : dataset2.items) && Array.isArray(dataset2.items)) {
2170
+ for (const item of dataset2.items) {
2171
+ const sd = await this.fcApi.getSelfDescriptionByHash(item.meta.sdHash);
1365
2172
  if (sd) {
1366
- const mappedResource = this.mapSourceToDestination(sd, {
1367
- temsServiceBase: this.cfg.temsServiceBase,
1368
- temsCategoryBase: this.cfg.temsCategoryBase,
1369
- temsImageBase: this.cfg.temsImageBase,
1370
- temsProviderBase: this.cfg.temsProviderBase
1371
- });
1372
- resource["ldp:contains"].push(mappedResource);
2173
+ try {
2174
+ const mappedResource = this.mapSourceToDestination(sd, {
2175
+ temsServiceBase: this.cfg.temsServiceBase,
2176
+ temsCategoryBase: this.cfg.temsCategoryBase,
2177
+ temsImageBase: this.cfg.temsImageBase,
2178
+ temsProviderBase: this.cfg.temsProviderBase
2179
+ });
2180
+ resource["ldp:contains"].push(mappedResource);
2181
+ if (this.enableCaching) {
2182
+ newMetadata.push({
2183
+ sdHash: item.meta.sdHash,
2184
+ uploadDatetime: item.meta.uploadDatetime,
2185
+ statusDatetime: item.meta.statusDatetime,
2186
+ cachedAt: Date.now(),
2187
+ resourceId: mappedResource["@id"]
2188
+ });
2189
+ }
2190
+ } catch (error2) {
2191
+ console.error("[FederatedCatalogueStore] Error mapping resource:", error2);
2192
+ }
1373
2193
  }
1374
2194
  }
1375
- this.setLocalData(resource, targetType);
2195
+ }
2196
+ if (this.enableCaching && this.metadataManager && newMetadata.length > 0) {
2197
+ this.metadataManager.updateCache(resource, newMetadata);
1376
2198
  }
1377
2199
  document.dispatchEvent(new CustomEvent("save", {
1378
2200
  detail: {
1379
2201
  resource: {
1380
- "@id": resource["@id"]
2202
+ "@id": resource == null ? void 0 : resource["@id"]
1381
2203
  }
1382
2204
  },
1383
2205
  bubbles: true
@@ -1385,11 +2207,8 @@ let __tla = (async () => {
1385
2207
  return resource;
1386
2208
  }
1387
2209
  async initLocalDataSourceContainer(dataSrc = "", containerType = "default") {
1388
- var _a2;
1389
- const endpointHash = ((_a2 = this.cfg.endpoint) == null ? void 0 : _a2.replace(/[^a-zA-Z0-9]/g, "")) || "unknown";
1390
- const idField = `fc-${endpointHash}-${containerType}`;
1391
2210
  if (!dataSrc) {
1392
- dataSrc = `store://local.${idField}/`;
2211
+ dataSrc = this.buildContainerId(containerType);
1393
2212
  }
1394
2213
  const localContainer = {
1395
2214
  "@context": "https://cdn.startinblox.com/owl/context.jsonld",
@@ -1450,10 +2269,10 @@ let __tla = (async () => {
1450
2269
  }
1451
2270
  subscribeResourceTo(_resourceId, _nestedResourceId) {
1452
2271
  }
1453
- fetchAuthn(_iri, _options) {
1454
- return Promise.resolve({});
2272
+ async fetchAuthn(_iri, _options) {
2273
+ return await Promise.resolve({});
1455
2274
  }
1456
- async setLocalData(resource, id, _skipFetch) {
2275
+ async setLocalData(resource, id) {
1457
2276
  try {
1458
2277
  const resourceWithId = {
1459
2278
  ...resource,
@@ -1477,8 +2296,39 @@ let __tla = (async () => {
1477
2296
  bubbles: true
1478
2297
  }));
1479
2298
  }
2299
+ stripUrnPrefix(id, prefix) {
2300
+ if (id == null ? void 0 : id.startsWith(prefix)) {
2301
+ return id.substring(prefix.length);
2302
+ }
2303
+ return id;
2304
+ }
2305
+ stripTemsUrnFromPolicy(obj) {
2306
+ if (obj === null || obj === void 0) {
2307
+ return obj;
2308
+ }
2309
+ if (typeof obj === "string") {
2310
+ return this.stripUrnPrefix(obj, "urn:tems:");
2311
+ }
2312
+ if (Array.isArray(obj)) {
2313
+ return obj.map((item) => this.stripTemsUrnFromPolicy(item));
2314
+ }
2315
+ if (typeof obj === "object") {
2316
+ const result = {};
2317
+ for (const key in obj) {
2318
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
2319
+ if (key === "@id") {
2320
+ result[key] = this.stripUrnPrefix(obj[key], "urn:tems:");
2321
+ } else {
2322
+ result[key] = this.stripTemsUrnFromPolicy(obj[key]);
2323
+ }
2324
+ }
2325
+ }
2326
+ return result;
2327
+ }
2328
+ return obj;
2329
+ }
1480
2330
  mapSourceToDestination(src, opts) {
1481
- var _a2, _b, _c, _d, _e, _f, _g, _h;
2331
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1482
2332
  const vc = src.verifiableCredential;
1483
2333
  const cs = vc.credentialSubject;
1484
2334
  let catInfo;
@@ -1489,9 +2339,16 @@ let __tla = (async () => {
1489
2339
  usedKey = "service";
1490
2340
  type = "tems:Service";
1491
2341
  } else if (cs["dcat:dataset"] && cs["dcat:dataset"].length > 0) {
1492
- catInfo = cs["dcat:dataset"][0];
1493
- usedKey = "dataset";
1494
- type = "tems:DataOffer";
2342
+ const dataset2 = cs["dcat:dataset"][0];
2343
+ if (dataset2["dcat:service"]) {
2344
+ catInfo = dataset2["dcat:service"];
2345
+ usedKey = "nested-service";
2346
+ type = "tems:Service";
2347
+ } else {
2348
+ catInfo = dataset2;
2349
+ usedKey = "dataset";
2350
+ type = "tems:DataOffer";
2351
+ }
1495
2352
  } else {
1496
2353
  throw new Error("Expected either credentialSubject['dcat:service'] or a non-empty array in ['dcat:dataset']");
1497
2354
  }
@@ -1500,7 +2357,7 @@ let __tla = (async () => {
1500
2357
  const serviceId = `${opts.temsServiceBase}${encodeURIComponent(slug)}/`;
1501
2358
  const creation_date = vc.issuanceDate;
1502
2359
  const update_date = vc.expirationDate;
1503
- const name = catInfo["dcterms:title"];
2360
+ const name = catInfo["dcterms:title"] || catInfo["dct:title"];
1504
2361
  const description = catInfo["rdfs:comment"];
1505
2362
  const keywords = catInfo["dcat:keyword"] || [];
1506
2363
  const long_description = keywords.length > 0 ? `Keywords: ${keywords.join(", ")}` : "";
@@ -1540,19 +2397,24 @@ let __tla = (async () => {
1540
2397
  const contact_url = catInfo["dcat:endpointDescription"] || "";
1541
2398
  const documentation_url = contact_url || "";
1542
2399
  let service_url = catInfo["dcat:endpointURL"] || "";
2400
+ if (!service_url) {
2401
+ console.warn("[FederatedCatalogueStore] dcat:endpointURL is missing from dcat:service. Available fields:", Object.keys(catInfo));
2402
+ }
1543
2403
  if (service_url.includes("demo.isan.org")) service_url = new URL(service_url).origin;
1544
2404
  let providerRef;
1545
2405
  if (usedKey === "service") {
1546
2406
  providerRef = ((_d = cs["gax-core:operatedBy"]) == null ? void 0 : _d["@id"]) || "";
2407
+ } else if (usedKey === "nested-service") {
2408
+ providerRef = ((_e = cs["gax-core:operatedBy"]) == null ? void 0 : _e["@id"]) || ((_f = cs["gax-core:offeredBy"]) == null ? void 0 : _f["@id"]) || "";
1547
2409
  } else {
1548
- providerRef = ((_e = cs["gax-core:offeredBy"]) == null ? void 0 : _e["@id"]) || "";
2410
+ providerRef = ((_g = cs["gax-core:offeredBy"]) == null ? void 0 : _g["@id"]) || "";
1549
2411
  }
1550
2412
  const providerSlug = providerRef.split(":").pop() + String(Math.random()) || "0";
1551
- const providerLogo = ((_g = (_f = catInfo["dcterms:creator"]) == null ? void 0 : _f["foaf:thumbnail"]) == null ? void 0 : _g["rdf:resource"]) || "";
2413
+ const providerLogo = ((_i = (_h = catInfo["dcterms:creator"]) == null ? void 0 : _h["foaf:thumbnail"]) == null ? void 0 : _i["rdf:resource"]) || "";
1552
2414
  const provider = {
1553
2415
  "@id": `${opts.temsProviderBase}${encodeURIComponent(providerSlug)}/`,
1554
2416
  "@type": "tems:Provider",
1555
- name: ((_h = catInfo["dcterms:creator"]) == null ? void 0 : _h["foaf:name"]) || "",
2417
+ name: ((_j = catInfo["dcterms:creator"]) == null ? void 0 : _j["foaf:name"]) || "",
1556
2418
  image: {
1557
2419
  "@id": `${opts.temsImageBase}${encodeURIComponent(providerLogo.split("/").pop() || "0")}/`,
1558
2420
  "@type": "tems:Image",
@@ -1562,6 +2424,49 @@ let __tla = (async () => {
1562
2424
  }
1563
2425
  };
1564
2426
  const data_offers = [];
2427
+ const counterPartyAddress = cs["dcat:endpointURL"];
2428
+ const counterPartyId = cs["dspace:participantId"];
2429
+ const assetId = this.stripUrnPrefix(cs["@id"], "urn:uuid:");
2430
+ let datasetId;
2431
+ let policy;
2432
+ let policies = [];
2433
+ if (cs["dcat:dataset"] && cs["dcat:dataset"].length > 0) {
2434
+ const dataset2 = cs["dcat:dataset"][0];
2435
+ if (dataset2["@id"]) {
2436
+ datasetId = this.stripUrnPrefix(dataset2["@id"], "urn:uuid:");
2437
+ }
2438
+ if (dataset2["odrl:hasPolicy"]) {
2439
+ const rawPolicy = dataset2["odrl:hasPolicy"];
2440
+ const processSinglePolicy = (policyObj) => {
2441
+ const processedPolicy = this.stripTemsUrnFromPolicy(JSON.parse(JSON.stringify(policyObj)));
2442
+ if (datasetId) {
2443
+ processedPolicy.target = datasetId;
2444
+ }
2445
+ return processedPolicy;
2446
+ };
2447
+ if (Array.isArray(rawPolicy)) {
2448
+ policies = rawPolicy.map(processSinglePolicy);
2449
+ policy = policies[0];
2450
+ } else {
2451
+ policy = processSinglePolicy(rawPolicy);
2452
+ policies = [
2453
+ policy
2454
+ ];
2455
+ }
2456
+ }
2457
+ }
2458
+ console.log("[FederatedCatalogueStore] \u{1F50D} Policy processing for", name, ":", {
2459
+ hasPolicy: !!policy,
2460
+ policiesCount: policies.length,
2461
+ policy: policy ? {
2462
+ "@id": policy["@id"],
2463
+ hasTarget: !!policy.target
2464
+ } : null,
2465
+ policies: policies.map((p) => ({
2466
+ "@id": p["@id"],
2467
+ hasTarget: !!p.target
2468
+ }))
2469
+ });
1565
2470
  const dest = {
1566
2471
  "@id": serviceId,
1567
2472
  creation_date,
@@ -1585,12 +2490,35 @@ let __tla = (async () => {
1585
2490
  url: service_url,
1586
2491
  provider,
1587
2492
  data_offers,
1588
- "@type": type
2493
+ "@type": type,
2494
+ ...counterPartyAddress && {
2495
+ counterPartyAddress
2496
+ },
2497
+ ...counterPartyId && {
2498
+ counterPartyId
2499
+ },
2500
+ ...assetId && {
2501
+ assetId
2502
+ },
2503
+ ...datasetId && {
2504
+ datasetId
2505
+ },
2506
+ ...policy && {
2507
+ policy
2508
+ },
2509
+ ...policies.length > 0 && {
2510
+ policies
2511
+ }
1589
2512
  };
2513
+ console.log("[FederatedCatalogueStore] \u{1F50D} Destination object contract fields:", {
2514
+ hasPolicy: "policy" in dest,
2515
+ hasPolicies: "policies" in dest,
2516
+ policiesValue: dest.policies
2517
+ });
1590
2518
  return dest;
1591
2519
  }
1592
2520
  }
1593
- const _FederatedCatalogueStoreAdapter = class _FederatedCatalogueStoreAdapter {
2521
+ class FederatedCatalogueStoreAdapter {
1594
2522
  constructor() {
1595
2523
  }
1596
2524
  static validateConfiguration(cfg) {
@@ -1606,18 +2534,13 @@ let __tla = (async () => {
1606
2534
  }
1607
2535
  }
1608
2536
  static getStoreInstance(cfg) {
1609
- if (!_FederatedCatalogueStoreAdapter.store) {
1610
- if (!cfg) {
1611
- throw new Error("[FederatedCatalogueStoreAdapter] configuration is required");
1612
- }
1613
- _FederatedCatalogueStoreAdapter.validateConfiguration(cfg);
1614
- _FederatedCatalogueStoreAdapter.store = new FederatedCatalogueStore(cfg);
2537
+ if (!cfg) {
2538
+ throw new Error("[FederatedCatalogueStoreAdapter] configuration is required");
1615
2539
  }
1616
- return _FederatedCatalogueStoreAdapter.store;
2540
+ FederatedCatalogueStoreAdapter.validateConfiguration(cfg);
2541
+ return new FederatedCatalogueStore(cfg);
1617
2542
  }
1618
- };
1619
- __publicField(_FederatedCatalogueStoreAdapter, "store");
1620
- let FederatedCatalogueStoreAdapter = _FederatedCatalogueStoreAdapter;
2543
+ }
1621
2544
  var lib = {};
1622
2545
  var IdentifierIssuer_1;
1623
2546
  var hasRequiredIdentifierIssuer;
@@ -2934,7 +3857,7 @@ let __tla = (async () => {
2934
3857
  function requireLib() {
2935
3858
  if (hasRequiredLib) return lib;
2936
3859
  hasRequiredLib = 1;
2937
- (function(exports) {
3860
+ (function(exports$1) {
2938
3861
  const URDNA2015 = requireURDNA2015();
2939
3862
  const URGNA20122 = requireURGNA2012();
2940
3863
  const URDNA2015Sync = requireURDNA2015Sync();
@@ -2946,19 +3869,19 @@ let __tla = (async () => {
2946
3869
  }
2947
3870
  function _inputToDataset(input) {
2948
3871
  if (!Array.isArray(input)) {
2949
- return exports.NQuads.legacyDatasetToQuads(input);
3872
+ return exports$1.NQuads.legacyDatasetToQuads(input);
2950
3873
  }
2951
3874
  return input;
2952
3875
  }
2953
- exports.NQuads = requireNQuads$1();
2954
- exports.IdentifierIssuer = requireIdentifierIssuer();
2955
- exports._rdfCanonizeNative = function(api) {
3876
+ exports$1.NQuads = requireNQuads$1();
3877
+ exports$1.IdentifierIssuer = requireIdentifierIssuer();
3878
+ exports$1._rdfCanonizeNative = function(api) {
2956
3879
  if (api) {
2957
3880
  rdfCanonizeNative = api;
2958
3881
  }
2959
3882
  return rdfCanonizeNative;
2960
3883
  };
2961
- exports.canonize = async function(input, options) {
3884
+ exports$1.canonize = async function(input, options) {
2962
3885
  const dataset2 = _inputToDataset(input);
2963
3886
  if (options.useNative) {
2964
3887
  if (!rdfCanonizeNative) {
@@ -2983,7 +3906,7 @@ let __tla = (async () => {
2983
3906
  }
2984
3907
  throw new Error("Invalid RDF Dataset Canonicalization algorithm: " + options.algorithm);
2985
3908
  };
2986
- exports._canonizeSync = function(input, options) {
3909
+ exports$1._canonizeSync = function(input, options) {
2987
3910
  const dataset2 = _inputToDataset(input);
2988
3911
  if (options.useNative) {
2989
3912
  if (!rdfCanonizeNative) {
@@ -9809,7 +10732,7 @@ let __tla = (async () => {
9809
10732
  function requirePubsub() {
9810
10733
  if (hasRequiredPubsub) return pubsub$1.exports;
9811
10734
  hasRequiredPubsub = 1;
9812
- (function(module, exports) {
10735
+ (function(module, exports$1) {
9813
10736
  (function(root, factory2) {
9814
10737
  var PubSub2 = {};
9815
10738
  if (root.PubSub) {
@@ -9821,10 +10744,10 @@ let __tla = (async () => {
9821
10744
  }
9822
10745
  {
9823
10746
  if (module !== void 0 && module.exports) {
9824
- exports = module.exports = PubSub2;
10747
+ exports$1 = module.exports = PubSub2;
9825
10748
  }
9826
- exports.PubSub = PubSub2;
9827
- module.exports = exports = PubSub2;
10749
+ exports$1.PubSub = PubSub2;
10750
+ module.exports = exports$1 = PubSub2;
9828
10751
  }
9829
10752
  })(typeof window === "object" && window || pubsub || globalThis, function(PubSub2) {
9830
10753
  var messages = {}, lastUid = -1, ALL_SUBSCRIBING_MSG = "*";
@@ -10597,15 +11520,15 @@ let __tla = (async () => {
10597
11520
  function requireBuffer() {
10598
11521
  if (hasRequiredBuffer) return buffer;
10599
11522
  hasRequiredBuffer = 1;
10600
- (function(exports) {
11523
+ (function(exports$1) {
10601
11524
  const base64 = requireBase64Js();
10602
11525
  const ieee7542 = requireIeee754();
10603
11526
  const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
10604
- exports.Buffer = Buffer2;
10605
- exports.SlowBuffer = SlowBuffer;
10606
- exports.INSPECT_MAX_BYTES = 50;
11527
+ exports$1.Buffer = Buffer2;
11528
+ exports$1.SlowBuffer = SlowBuffer;
11529
+ exports$1.INSPECT_MAX_BYTES = 50;
10607
11530
  const K_MAX_LENGTH = 2147483647;
10608
- exports.kMaxLength = K_MAX_LENGTH;
11531
+ exports$1.kMaxLength = K_MAX_LENGTH;
10609
11532
  Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport();
10610
11533
  if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
10611
11534
  console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");
@@ -11019,7 +11942,7 @@ let __tla = (async () => {
11019
11942
  };
11020
11943
  Buffer2.prototype.inspect = function inspect2() {
11021
11944
  let str = "";
11022
- const max = exports.INSPECT_MAX_BYTES;
11945
+ const max = exports$1.INSPECT_MAX_BYTES;
11023
11946
  str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
11024
11947
  if (this.length > max) str += " ... ";
11025
11948
  return "<Buffer " + str + ">";
@@ -12110,7 +13033,7 @@ let __tla = (async () => {
12110
13033
  function numberIsNaN(obj) {
12111
13034
  return obj !== obj;
12112
13035
  }
12113
- const hexSliceLookupTable = function() {
13036
+ const hexSliceLookupTable = (function() {
12114
13037
  const alphabet = "0123456789abcdef";
12115
13038
  const table = new Array(256);
12116
13039
  for (let i = 0; i < 16; ++i) {
@@ -12120,7 +13043,7 @@ let __tla = (async () => {
12120
13043
  }
12121
13044
  }
12122
13045
  return table;
12123
- }();
13046
+ })();
12124
13047
  function defineBigIntMethod(fn) {
12125
13048
  return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
12126
13049
  }
@@ -12211,7 +13134,7 @@ let __tla = (async () => {
12211
13134
  function copyBuffer(src, target, offset) {
12212
13135
  Buffer2.prototype.copy.call(src, target, offset);
12213
13136
  }
12214
- buffer_list$1 = function() {
13137
+ buffer_list$1 = (function() {
12215
13138
  function BufferList() {
12216
13139
  _classCallCheck(this, BufferList);
12217
13140
  this.head = null;
@@ -12379,7 +13302,7 @@ let __tla = (async () => {
12379
13302
  }
12380
13303
  ]);
12381
13304
  return BufferList;
12382
- }();
13305
+ })();
12383
13306
  return buffer_list$1;
12384
13307
  }
12385
13308
  var destroy_1$1;
@@ -12493,13 +13416,13 @@ let __tla = (async () => {
12493
13416
  return message(arg1, arg2, arg3);
12494
13417
  }
12495
13418
  }
12496
- var NodeError = function(_Base) {
13419
+ var NodeError = (function(_Base) {
12497
13420
  _inheritsLoose(NodeError2, _Base);
12498
13421
  function NodeError2(arg1, arg2, arg3) {
12499
13422
  return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
12500
13423
  }
12501
13424
  return NodeError2;
12502
- }(Base);
13425
+ })(Base);
12503
13426
  NodeError.prototype.name = Base.name;
12504
13427
  NodeError.prototype.code = code;
12505
13428
  codes[code] = NodeError;
@@ -13194,7 +14117,7 @@ let __tla = (async () => {
13194
14117
  function requireSafeBuffer() {
13195
14118
  if (hasRequiredSafeBuffer) return safeBuffer.exports;
13196
14119
  hasRequiredSafeBuffer = 1;
13197
- (function(module, exports) {
14120
+ (function(module, exports$1) {
13198
14121
  var buffer2 = requireBuffer();
13199
14122
  var Buffer2 = buffer2.Buffer;
13200
14123
  function copyProps(src, dst) {
@@ -13205,8 +14128,8 @@ let __tla = (async () => {
13205
14128
  if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) {
13206
14129
  module.exports = buffer2;
13207
14130
  } else {
13208
- copyProps(buffer2, exports);
13209
- exports.Buffer = SafeBuffer;
14131
+ copyProps(buffer2, exports$1);
14132
+ exports$1.Buffer = SafeBuffer;
13210
14133
  }
13211
14134
  function SafeBuffer(arg, encodingOrOffset, length) {
13212
14135
  return Buffer2(arg, encodingOrOffset, length);
@@ -14393,11 +15316,11 @@ let __tla = (async () => {
14393
15316
  });
14394
15317
  for (var i in stream2) {
14395
15318
  if (this[i] === void 0 && typeof stream2[i] === "function") {
14396
- this[i] = /* @__PURE__ */ function methodWrap(method) {
15319
+ this[i] = /* @__PURE__ */ (function methodWrap(method) {
14397
15320
  return function methodWrapReturnFunction() {
14398
15321
  return stream2[method].apply(stream2, arguments);
14399
15322
  };
14400
- }(i);
15323
+ })(i);
14401
15324
  }
14402
15325
  }
14403
15326
  for (var n = 0; n < kProxyEvents.length; n++) {
@@ -19163,50 +20086,64 @@ let __tla = (async () => {
19163
20086
  createDebug.namespaces = namespaces2;
19164
20087
  createDebug.names = [];
19165
20088
  createDebug.skips = [];
19166
- let i;
19167
- const split = (typeof namespaces2 === "string" ? namespaces2 : "").split(/[\s,]+/);
19168
- const len = split.length;
19169
- for (i = 0; i < len; i++) {
19170
- if (!split[i]) {
19171
- continue;
20089
+ const split = (typeof namespaces2 === "string" ? namespaces2 : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
20090
+ for (const ns2 of split) {
20091
+ if (ns2[0] === "-") {
20092
+ createDebug.skips.push(ns2.slice(1));
20093
+ } else {
20094
+ createDebug.names.push(ns2);
19172
20095
  }
19173
- namespaces2 = split[i].replace(/\*/g, ".*?");
19174
- if (namespaces2[0] === "-") {
19175
- createDebug.skips.push(new RegExp("^" + namespaces2.slice(1) + "$"));
20096
+ }
20097
+ }
20098
+ function matchesTemplate(search, template) {
20099
+ let searchIndex = 0;
20100
+ let templateIndex = 0;
20101
+ let starIndex = -1;
20102
+ let matchIndex = 0;
20103
+ while (searchIndex < search.length) {
20104
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
20105
+ if (template[templateIndex] === "*") {
20106
+ starIndex = templateIndex;
20107
+ matchIndex = searchIndex;
20108
+ templateIndex++;
20109
+ } else {
20110
+ searchIndex++;
20111
+ templateIndex++;
20112
+ }
20113
+ } else if (starIndex !== -1) {
20114
+ templateIndex = starIndex + 1;
20115
+ matchIndex++;
20116
+ searchIndex = matchIndex;
19176
20117
  } else {
19177
- createDebug.names.push(new RegExp("^" + namespaces2 + "$"));
20118
+ return false;
19178
20119
  }
19179
20120
  }
20121
+ while (templateIndex < template.length && template[templateIndex] === "*") {
20122
+ templateIndex++;
20123
+ }
20124
+ return templateIndex === template.length;
19180
20125
  }
19181
20126
  function disable() {
19182
20127
  const namespaces2 = [
19183
- ...createDebug.names.map(toNamespace),
19184
- ...createDebug.skips.map(toNamespace).map((namespace2) => "-" + namespace2)
20128
+ ...createDebug.names,
20129
+ ...createDebug.skips.map((namespace2) => "-" + namespace2)
19185
20130
  ].join(",");
19186
20131
  createDebug.enable("");
19187
20132
  return namespaces2;
19188
20133
  }
19189
20134
  function enabled(name) {
19190
- if (name[name.length - 1] === "*") {
19191
- return true;
19192
- }
19193
- let i;
19194
- let len;
19195
- for (i = 0, len = createDebug.skips.length; i < len; i++) {
19196
- if (createDebug.skips[i].test(name)) {
20135
+ for (const skip of createDebug.skips) {
20136
+ if (matchesTemplate(name, skip)) {
19197
20137
  return false;
19198
20138
  }
19199
20139
  }
19200
- for (i = 0, len = createDebug.names.length; i < len; i++) {
19201
- if (createDebug.names[i].test(name)) {
20140
+ for (const ns2 of createDebug.names) {
20141
+ if (matchesTemplate(name, ns2)) {
19202
20142
  return true;
19203
20143
  }
19204
20144
  }
19205
20145
  return false;
19206
20146
  }
19207
- function toNamespace(regexp) {
19208
- return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
19209
- }
19210
20147
  function coerce(val) {
19211
20148
  if (val instanceof Error) {
19212
20149
  return val.stack || val.message;
@@ -19226,13 +20163,13 @@ let __tla = (async () => {
19226
20163
  function requireBrowser$3() {
19227
20164
  if (hasRequiredBrowser$3) return browser$3.exports;
19228
20165
  hasRequiredBrowser$3 = 1;
19229
- (function(module, exports) {
19230
- exports.formatArgs = formatArgs;
19231
- exports.save = save;
19232
- exports.load = load;
19233
- exports.useColors = useColors;
19234
- exports.storage = localstorage();
19235
- exports.destroy = /* @__PURE__ */ (() => {
20166
+ (function(module, exports$1) {
20167
+ exports$1.formatArgs = formatArgs;
20168
+ exports$1.save = save;
20169
+ exports$1.load = load;
20170
+ exports$1.useColors = useColors;
20171
+ exports$1.storage = localstorage();
20172
+ exports$1.destroy = /* @__PURE__ */ (() => {
19236
20173
  let warned = false;
19237
20174
  return () => {
19238
20175
  if (!warned) {
@@ -19241,7 +20178,7 @@ let __tla = (async () => {
19241
20178
  }
19242
20179
  };
19243
20180
  })();
19244
- exports.colors = [
20181
+ exports$1.colors = [
19245
20182
  "#0000CC",
19246
20183
  "#0000FF",
19247
20184
  "#0033CC",
@@ -19326,7 +20263,8 @@ let __tla = (async () => {
19326
20263
  if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
19327
20264
  return false;
19328
20265
  }
19329
- return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
20266
+ let m;
20267
+ return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
19330
20268
  }
19331
20269
  function formatArgs(args) {
19332
20270
  args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
@@ -19348,14 +20286,14 @@ let __tla = (async () => {
19348
20286
  });
19349
20287
  args.splice(lastC, 0, c);
19350
20288
  }
19351
- exports.log = console.debug || console.log || (() => {
20289
+ exports$1.log = console.debug || console.log || (() => {
19352
20290
  });
19353
20291
  function save(namespaces2) {
19354
20292
  try {
19355
20293
  if (namespaces2) {
19356
- exports.storage.setItem("debug", namespaces2);
20294
+ exports$1.storage.setItem("debug", namespaces2);
19357
20295
  } else {
19358
- exports.storage.removeItem("debug");
20296
+ exports$1.storage.removeItem("debug");
19359
20297
  }
19360
20298
  } catch (error2) {
19361
20299
  }
@@ -19363,7 +20301,7 @@ let __tla = (async () => {
19363
20301
  function load() {
19364
20302
  let r;
19365
20303
  try {
19366
- r = exports.storage.getItem("debug");
20304
+ r = exports$1.storage.getItem("debug") || exports$1.storage.getItem("DEBUG");
19367
20305
  } catch (error2) {
19368
20306
  }
19369
20307
  if (!r && typeof process !== "undefined" && "env" in process) {
@@ -19377,7 +20315,7 @@ let __tla = (async () => {
19377
20315
  } catch (error2) {
19378
20316
  }
19379
20317
  }
19380
- module.exports = requireCommon()(exports);
20318
+ module.exports = requireCommon()(exports$1);
19381
20319
  const { formatters } = module.exports;
19382
20320
  formatters.j = function(v) {
19383
20321
  try {
@@ -20222,8 +21160,8 @@ let __tla = (async () => {
20222
21160
  function requireRdfDataFactory() {
20223
21161
  if (hasRequiredRdfDataFactory) return rdfDataFactory;
20224
21162
  hasRequiredRdfDataFactory = 1;
20225
- (function(exports) {
20226
- var __createBinding = rdfDataFactory && rdfDataFactory.__createBinding || (Object.create ? function(o, m, k, k2) {
21163
+ (function(exports$1) {
21164
+ var __createBinding = rdfDataFactory && rdfDataFactory.__createBinding || (Object.create ? (function(o, m, k, k2) {
20227
21165
  if (k2 === void 0) k2 = k;
20228
21166
  var desc = Object.getOwnPropertyDescriptor(m, k);
20229
21167
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
@@ -20235,23 +21173,23 @@ let __tla = (async () => {
20235
21173
  };
20236
21174
  }
20237
21175
  Object.defineProperty(o, k2, desc);
20238
- } : function(o, m, k, k2) {
21176
+ }) : (function(o, m, k, k2) {
20239
21177
  if (k2 === void 0) k2 = k;
20240
21178
  o[k2] = m[k];
20241
- });
20242
- var __exportStar = rdfDataFactory && rdfDataFactory.__exportStar || function(m, exports2) {
20243
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
21179
+ }));
21180
+ var __exportStar = rdfDataFactory && rdfDataFactory.__exportStar || function(m, exports$12) {
21181
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p);
20244
21182
  };
20245
- Object.defineProperty(exports, "__esModule", {
21183
+ Object.defineProperty(exports$1, "__esModule", {
20246
21184
  value: true
20247
21185
  });
20248
- __exportStar(requireBlankNode(), exports);
20249
- __exportStar(requireDataFactory(), exports);
20250
- __exportStar(requireDefaultGraph(), exports);
20251
- __exportStar(requireLiteral(), exports);
20252
- __exportStar(requireNamedNode(), exports);
20253
- __exportStar(requireQuad(), exports);
20254
- __exportStar(requireVariable(), exports);
21186
+ __exportStar(requireBlankNode(), exports$1);
21187
+ __exportStar(requireDataFactory(), exports$1);
21188
+ __exportStar(requireDefaultGraph(), exports$1);
21189
+ __exportStar(requireLiteral(), exports$1);
21190
+ __exportStar(requireNamedNode(), exports$1);
21191
+ __exportStar(requireQuad(), exports$1);
21192
+ __exportStar(requireVariable(), exports$1);
20255
21193
  })(rdfDataFactory);
20256
21194
  return rdfDataFactory;
20257
21195
  }
@@ -20555,8 +21493,8 @@ let __tla = (async () => {
20555
21493
  function requireHandler() {
20556
21494
  if (hasRequiredHandler) return handler;
20557
21495
  hasRequiredHandler = 1;
20558
- (function(exports) {
20559
- var __createBinding = handler && handler.__createBinding || (Object.create ? function(o, m, k, k2) {
21496
+ (function(exports$1) {
21497
+ var __createBinding = handler && handler.__createBinding || (Object.create ? (function(o, m, k, k2) {
20560
21498
  if (k2 === void 0) k2 = k;
20561
21499
  var desc = Object.getOwnPropertyDescriptor(m, k);
20562
21500
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
@@ -20568,21 +21506,21 @@ let __tla = (async () => {
20568
21506
  };
20569
21507
  }
20570
21508
  Object.defineProperty(o, k2, desc);
20571
- } : function(o, m, k, k2) {
21509
+ }) : (function(o, m, k, k2) {
20572
21510
  if (k2 === void 0) k2 = k;
20573
21511
  o[k2] = m[k];
20574
- });
20575
- var __exportStar = handler && handler.__exportStar || function(m, exports2) {
20576
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
21512
+ }));
21513
+ var __exportStar = handler && handler.__exportStar || function(m, exports$12) {
21514
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p);
20577
21515
  };
20578
- Object.defineProperty(exports, "__esModule", {
21516
+ Object.defineProperty(exports$1, "__esModule", {
20579
21517
  value: true
20580
21518
  });
20581
- __exportStar(requireTypeHandlerBoolean(), exports);
20582
- __exportStar(requireTypeHandlerDate(), exports);
20583
- __exportStar(requireTypeHandlerNumberDouble(), exports);
20584
- __exportStar(requireTypeHandlerNumberInteger(), exports);
20585
- __exportStar(requireTypeHandlerString(), exports);
21519
+ __exportStar(requireTypeHandlerBoolean(), exports$1);
21520
+ __exportStar(requireTypeHandlerDate(), exports$1);
21521
+ __exportStar(requireTypeHandlerNumberDouble(), exports$1);
21522
+ __exportStar(requireTypeHandlerNumberInteger(), exports$1);
21523
+ __exportStar(requireTypeHandlerString(), exports$1);
20586
21524
  })(handler);
20587
21525
  return handler;
20588
21526
  }
@@ -20600,8 +21538,8 @@ let __tla = (async () => {
20600
21538
  function requireRdfLiteral() {
20601
21539
  if (hasRequiredRdfLiteral) return rdfLiteral;
20602
21540
  hasRequiredRdfLiteral = 1;
20603
- (function(exports) {
20604
- var __createBinding = rdfLiteral && rdfLiteral.__createBinding || (Object.create ? function(o, m, k, k2) {
21541
+ (function(exports$1) {
21542
+ var __createBinding = rdfLiteral && rdfLiteral.__createBinding || (Object.create ? (function(o, m, k, k2) {
20605
21543
  if (k2 === void 0) k2 = k;
20606
21544
  var desc = Object.getOwnPropertyDescriptor(m, k);
20607
21545
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
@@ -20613,27 +21551,27 @@ let __tla = (async () => {
20613
21551
  };
20614
21552
  }
20615
21553
  Object.defineProperty(o, k2, desc);
20616
- } : function(o, m, k, k2) {
21554
+ }) : (function(o, m, k, k2) {
20617
21555
  if (k2 === void 0) k2 = k;
20618
21556
  o[k2] = m[k];
20619
- });
20620
- var __exportStar = rdfLiteral && rdfLiteral.__exportStar || function(m, exports2) {
20621
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
21557
+ }));
21558
+ var __exportStar = rdfLiteral && rdfLiteral.__exportStar || function(m, exports$12) {
21559
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p);
20622
21560
  };
20623
- Object.defineProperty(exports, "__esModule", {
21561
+ Object.defineProperty(exports$1, "__esModule", {
20624
21562
  value: true
20625
21563
  });
20626
- exports.fromRdf = fromRdf2;
20627
- exports.toRdf = toRdf2;
20628
- exports.getTermRaw = getTermRaw;
20629
- exports.getSupportedRdfDatatypes = getSupportedRdfDatatypes;
20630
- exports.getSupportedJavaScriptPrimitives = getSupportedJavaScriptPrimitives;
21564
+ exports$1.fromRdf = fromRdf2;
21565
+ exports$1.toRdf = toRdf2;
21566
+ exports$1.getTermRaw = getTermRaw;
21567
+ exports$1.getSupportedRdfDatatypes = getSupportedRdfDatatypes;
21568
+ exports$1.getSupportedJavaScriptPrimitives = getSupportedJavaScriptPrimitives;
20631
21569
  const rdf_data_factory_1 = requireRdfDataFactory();
20632
21570
  const handler_1 = requireHandler();
20633
21571
  const Translator_1 = requireTranslator();
20634
- __exportStar(requireHandler(), exports);
20635
- __exportStar(requireITypeHandler(), exports);
20636
- __exportStar(requireTranslator(), exports);
21572
+ __exportStar(requireHandler(), exports$1);
21573
+ __exportStar(requireITypeHandler(), exports$1);
21574
+ __exportStar(requireTranslator(), exports$1);
20637
21575
  const DF = new rdf_data_factory_1.DataFactory();
20638
21576
  const translator = new Translator_1.Translator();
20639
21577
  translator.registerHandler(new handler_1.TypeHandlerString(), handler_1.TypeHandlerString.TYPES.map((t) => DF.namedNode(t)), [
@@ -24971,8 +25909,8 @@ let __tla = (async () => {
24971
25909
  this.pipes = [];
24972
25910
  this.flowing = null;
24973
25911
  this[kPaused] = null;
24974
- if (options && options.emitClose === false) this.state &= -2049;
24975
- if (options && options.autoDestroy === false) this.state &= -4097;
25912
+ if (options && options.emitClose === false) this.state &= ~kEmitClose;
25913
+ if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy;
24976
25914
  this.errored = null;
24977
25915
  this.defaultEncoding = options && options.defaultEncoding || "utf8";
24978
25916
  this.awaitDrainWriters = null;
@@ -25053,7 +25991,7 @@ let __tla = (async () => {
25053
25991
  if (err) {
25054
25992
  errorOrDestroy(stream2, err);
25055
25993
  } else if (chunk === null) {
25056
- state2.state &= -9;
25994
+ state2.state &= ~kReading;
25057
25995
  onEofChunk(stream2, state2);
25058
25996
  } else if ((state2.state & kObjectMode) !== 0 || chunk && chunk.length > 0) {
25059
25997
  if (addToFront) {
@@ -25065,7 +26003,7 @@ let __tla = (async () => {
25065
26003
  } else if (state2.destroyed || state2.errored) {
25066
26004
  return false;
25067
26005
  } else {
25068
- state2.state &= -9;
26006
+ state2.state &= ~kReading;
25069
26007
  if (state2.decoder && !encoding) {
25070
26008
  chunk = state2.decoder.write(chunk);
25071
26009
  if (state2.objectMode || chunk.length !== 0) addChunk(stream2, state2, chunk, false);
@@ -25075,7 +26013,7 @@ let __tla = (async () => {
25075
26013
  }
25076
26014
  }
25077
26015
  } else if (!addToFront) {
25078
- state2.state &= -9;
26016
+ state2.state &= ~kReading;
25079
26017
  maybeReadMore(stream2, state2);
25080
26018
  }
25081
26019
  return !state2.ended && (state2.length < state2.highWaterMark || state2.length === 0);
@@ -25150,7 +26088,7 @@ let __tla = (async () => {
25150
26088
  const state2 = this._readableState;
25151
26089
  const nOrig = n;
25152
26090
  if (n > state2.highWaterMark) state2.highWaterMark = computeNewHighWaterMark(n);
25153
- if (n !== 0) state2.state &= -129;
26091
+ if (n !== 0) state2.state &= ~kEmittedReadable;
25154
26092
  if (n === 0 && state2.needReadable && ((state2.highWaterMark !== 0 ? state2.length >= state2.highWaterMark : state2.length > 0) || state2.ended)) {
25155
26093
  debug2("read: emitReadable", state2.length, state2.ended);
25156
26094
  if (state2.length === 0 && state2.ended) endReadable(this);
@@ -25180,7 +26118,7 @@ let __tla = (async () => {
25180
26118
  } catch (err) {
25181
26119
  errorOrDestroy(this, err);
25182
26120
  }
25183
- state2.state &= -33;
26121
+ state2.state &= ~kSync;
25184
26122
  if (!state2.reading) n = howMuchToRead(nOrig, state2);
25185
26123
  }
25186
26124
  let ret;
@@ -26556,7 +27494,7 @@ let __tla = (async () => {
26556
27494
  let { promise, resolve } = createDeferredPromise();
26557
27495
  const ac = new AbortController();
26558
27496
  const signal = ac.signal;
26559
- const value = fn(async function* () {
27497
+ const value = fn((async function* () {
26560
27498
  while (true) {
26561
27499
  const _promise = promise;
26562
27500
  promise = null;
@@ -26569,7 +27507,7 @@ let __tla = (async () => {
26569
27507
  ({ promise, resolve } = createDeferredPromise());
26570
27508
  yield chunk;
26571
27509
  }
26572
- }(), {
27510
+ })(), {
26573
27511
  signal
26574
27512
  });
26575
27513
  return {
@@ -28112,6 +29050,25 @@ let __tla = (async () => {
28112
29050
  constructor(dataFetcher) {
28113
29051
  this.dataFetcher = dataFetcher;
28114
29052
  }
29053
+ getGlobalIndexLoader() {
29054
+ return globalThis.SEMANTIZER_INDEX_LOADER;
29055
+ }
29056
+ getGlobalQuadStreamLoader() {
29057
+ return globalThis.SEMANTIZER_QUAD_STREAM_LOADER;
29058
+ }
29059
+ buildHttpHeaders(dspHeaders) {
29060
+ const headers = {};
29061
+ if (dspHeaders == null ? void 0 : dspHeaders.agreementId) {
29062
+ headers["DSP-AGREEMENT-ID"] = dspHeaders.agreementId;
29063
+ }
29064
+ if (dspHeaders == null ? void 0 : dspHeaders.participantId) {
29065
+ headers["DSP-PARTICIPANT-ID"] = dspHeaders.participantId;
29066
+ }
29067
+ if (dspHeaders == null ? void 0 : dspHeaders.consumerConnectorUrl) {
29068
+ headers["DSP-CONSUMER-CONNECTORURL"] = dspHeaders.consumerConnectorUrl;
29069
+ }
29070
+ return headers;
29071
+ }
28115
29072
  isValidUrl(url2) {
28116
29073
  if (!url2 || typeof url2 !== "string") {
28117
29074
  return false;
@@ -28126,19 +29083,39 @@ let __tla = (async () => {
28126
29083
  hasValidIndexUrl(options) {
28127
29084
  return this.isValidUrl(options.dataSrcIndex ?? "") || this.isValidUrl(options.dataSrcProfile ?? "");
28128
29085
  }
29086
+ hasValidIndexSource(options) {
29087
+ return this.hasValidIndexUrl(options) || options.indexData !== void 0 && options.indexData !== null;
29088
+ }
29089
+ async buildIndexFromJsonLd(jsonLdData) {
29090
+ const jsonString = JSON.stringify(jsonLdData);
29091
+ const base64Data = btoa(unescape(encodeURIComponent(jsonString)));
29092
+ const dataUrl = `data:application/ld+json;base64,${base64Data}`;
29093
+ const index = await SEMANTIZER.load(dataUrl, indexFactory);
29094
+ return index;
29095
+ }
28129
29096
  async query(options) {
28130
- let indexUri;
28131
- if (options.dataSrcIndex) {
28132
- indexUri = options.dataSrcIndex;
28133
- } else if (options.dataSrcProfile) {
28134
- indexUri = await this.discoverIndexFromProfile(options.dataSrcProfile);
28135
- } else {
28136
- console.warn("Either dataSrcIndex or dataSrcProfile must be specified");
28137
- return [];
28138
- }
28139
- if (!this.isValidUrl(indexUri)) {
28140
- console.warn("\u26A0\uFE0F [SolidIndexingSearchProvider.queryIndex] Invalid index URI, returning empty results");
28141
- return [];
29097
+ const dspHttpHeaders = this.buildHttpHeaders(options.dspHeaders);
29098
+ const hasDspHeaders = Object.keys(dspHttpHeaders).length > 0;
29099
+ if (hasDspHeaders) {
29100
+ console.log("[SolidIndexingSearchProvider] Setting DSP headers on global loaders:", dspHttpHeaders);
29101
+ this.getGlobalIndexLoader().setCustomHeaders(dspHttpHeaders);
29102
+ this.getGlobalQuadStreamLoader().setCustomHeaders(dspHttpHeaders);
29103
+ }
29104
+ let indexUri = null;
29105
+ const hasDirectData = options.indexData !== void 0 && options.indexData !== null;
29106
+ if (!hasDirectData) {
29107
+ if (options.dataSrcIndex) {
29108
+ indexUri = options.dataSrcIndex;
29109
+ } else if (options.dataSrcProfile) {
29110
+ indexUri = await this.discoverIndexFromProfile(options.dataSrcProfile);
29111
+ } else {
29112
+ console.warn("Either dataSrcIndex, dataSrcProfile, or indexData must be specified");
29113
+ return [];
29114
+ }
29115
+ if (!this.isValidUrl(indexUri)) {
29116
+ console.warn("\u26A0\uFE0F [SolidIndexingSearchProvider.queryIndex] Invalid index URI, returning empty results");
29117
+ return [];
29118
+ }
28142
29119
  }
28143
29120
  const filterFields = Object.entries(options.filterValues);
28144
29121
  const firstField = filterFields[0];
@@ -28167,10 +29144,28 @@ let __tla = (async () => {
28167
29144
  subIndexShapeGraph.addAll(parser.parse(subIndexShape));
28168
29145
  const shaclValidator = new ValidatorImpl();
28169
29146
  const entryTransformer = new EntryStreamTransformerDefaultImpl(SEMANTIZER);
29147
+ console.log("[SolidIndexingSearchProvider] Generated shapes for query:");
29148
+ console.log("[SolidIndexingSearchProvider] - targetShape:", targetShape);
29149
+ console.log("[SolidIndexingSearchProvider] - subIndexShape:", subIndexShape);
29150
+ console.log("[SolidIndexingSearchProvider] - finalShape:", finalShape);
28170
29151
  const finalIndexStrategy = new IndexStrategyFinalShapeDefaultImpl(finalIndexShapeGraph, subIndexShapeGraph, shaclValidator, entryTransformer);
28171
29152
  const shaclStrategy = new IndexQueryingStrategyShaclUsingFinalIndex(targetShapeGraph, finalIndexStrategy, shaclValidator, entryTransformer);
28172
- const index = await SEMANTIZER.load(indexUri, indexFactory);
29153
+ let index;
29154
+ if (hasDirectData && options.indexData) {
29155
+ index = await this.buildIndexFromJsonLd(options.indexData);
29156
+ } else if (indexUri) {
29157
+ index = await SEMANTIZER.load(indexUri, indexFactory);
29158
+ } else {
29159
+ console.warn("\u26A0\uFE0F [SolidIndexingSearchProvider.queryIndex] No index source available");
29160
+ return [];
29161
+ }
29162
+ console.log("[SolidIndexingSearchProvider] Starting index query...");
29163
+ console.log("[SolidIndexingSearchProvider] Index loaded, starting query with shaclStrategy");
28173
29164
  const resultStream = index.mixins.index.query(shaclStrategy);
29165
+ resultStream.on("error", (err) => {
29166
+ console.error("[SolidIndexingSearchProvider] Stream error:", err);
29167
+ });
29168
+ const skipResourceFetch = options.skipResourceFetch === true;
28174
29169
  return new Promise((resolve, reject) => {
28175
29170
  const resultIds = [];
28176
29171
  const resources = [];
@@ -28178,15 +29173,24 @@ let __tla = (async () => {
28178
29173
  let streamEnded = false;
28179
29174
  const checkComplete = () => {
28180
29175
  if (streamEnded && pendingFetches === 0) {
28181
- resolve(resources);
29176
+ if (skipResourceFetch) {
29177
+ resolve(resultIds.map((id) => ({
29178
+ "@id": id
29179
+ })));
29180
+ } else {
29181
+ resolve(resources);
29182
+ }
28182
29183
  }
28183
29184
  };
28184
29185
  resultStream.on("data", async (result) => {
28185
29186
  if (result.value) {
28186
29187
  resultIds.push(result.value);
29188
+ if (skipResourceFetch) {
29189
+ return;
29190
+ }
28187
29191
  pendingFetches++;
28188
29192
  try {
28189
- const resource = await this.dataFetcher(result.value);
29193
+ const resource = await this.dataFetcher(result.value, hasDspHeaders ? dspHttpHeaders : void 0);
28190
29194
  if (resource) {
28191
29195
  resources.push(resource);
28192
29196
  } else {
@@ -28206,6 +29210,10 @@ let __tla = (async () => {
28206
29210
  });
28207
29211
  resultStream.on("end", () => {
28208
29212
  streamEnded = true;
29213
+ if (hasDspHeaders) {
29214
+ this.getGlobalIndexLoader().clearCustomHeaders();
29215
+ this.getGlobalQuadStreamLoader().clearCustomHeaders();
29216
+ }
28209
29217
  checkComplete();
28210
29218
  });
28211
29219
  });
@@ -28226,7 +29234,8 @@ let __tla = (async () => {
28226
29234
  filterValues: {
28227
29235
  [propertyName]: filterValue
28228
29236
  },
28229
- exactMatchMapping: options.exactMatchMapping
29237
+ exactMatchMapping: options.exactMatchMapping,
29238
+ dspHeaders: options.dspHeaders
28230
29239
  };
28231
29240
  return this.query(queryOptions);
28232
29241
  });
@@ -28467,9 +29476,9 @@ sh:property [
28467
29476
  __publicField(this, "loadingList");
28468
29477
  __publicField(this, "headers");
28469
29478
  __publicField(this, "fetch");
28470
- __publicField(this, "session");
28471
29479
  __publicField(this, "contextParser");
28472
29480
  __publicField(this, "searchProvider");
29481
+ __publicField(this, "cleanupAuth");
28473
29482
  __publicField(this, "resolveResource", (id, resolve) => {
28474
29483
  const handler2 = (event) => {
28475
29484
  if (event.detail.id === id) {
@@ -28483,6 +29492,11 @@ sh:property [
28483
29492
  };
28484
29493
  return handler2;
28485
29494
  });
29495
+ __publicField(this, "resolveFetch", (event) => {
29496
+ if (event.detail.fetch) {
29497
+ this.fetch = event.detail.fetch.bind ? event.detail.fetch.bind(globalThis) : event.detail.fetch;
29498
+ }
29499
+ });
28486
29500
  this.storeOptions = storeOptions;
28487
29501
  this.cache = this.storeOptions.cacheManager ?? new InMemoryCacheManager();
28488
29502
  this.subscriptionIndex = /* @__PURE__ */ new Map();
@@ -28493,15 +29507,38 @@ sh:property [
28493
29507
  "Content-Type": "application/ld+json",
28494
29508
  "Cache-Control": "must-revalidate"
28495
29509
  };
28496
- this.fetch = this.storeOptions.fetchMethod;
28497
- this.session = this.storeOptions.session;
28498
29510
  this.contextParser = new jsonldContextParserExports.ContextParser();
28499
- this.searchProvider = new SolidIndexingSearchProvider(this.getData.bind(this));
29511
+ const headersAwareDataFetcher = (id, customHeaders) => {
29512
+ return this.getData(id, void 0, void 0, void 0, false, void 0, void 0, customHeaders);
29513
+ };
29514
+ this.searchProvider = new SolidIndexingSearchProvider(headersAwareDataFetcher);
29515
+ if (this.storeOptions.fetchMethod) {
29516
+ this.fetch = this.storeOptions.fetchMethod.bind(globalThis);
29517
+ } else {
29518
+ const authFetch = AuthFetchResolver.getAuthFetch();
29519
+ this.fetch = authFetch.bind ? authFetch.bind(globalThis) : authFetch;
29520
+ this.cleanupAuth = AuthFetchResolver.onAuthActivated(this.resolveFetch.bind(this));
29521
+ }
29522
+ if (!this.fetch) {
29523
+ this.fetch = fetch;
29524
+ }
29525
+ const event = new CustomEvent("sib-core:loaded", {
29526
+ bubbles: true,
29527
+ composed: true,
29528
+ detail: {
29529
+ store: this
29530
+ }
29531
+ });
29532
+ window.dispatchEvent(event);
28500
29533
  }
28501
29534
  async initGetter() {
28502
- const { CustomGetter } = await import("./custom-getter-cITbP3Tj.js");
29535
+ const { CustomGetter } = await import("./custom-getter-BrHW1EBb.js");
28503
29536
  return CustomGetter;
28504
29537
  }
29538
+ disconnectedCallback() {
29539
+ var _a2;
29540
+ (_a2 = this.cleanupAuth) == null ? void 0 : _a2.call(this);
29541
+ }
28505
29542
  async getData(id, context2, parentId, localData, forceFetch, serverPagination, serverSearch, headers, bypassLoadingList) {
28506
29543
  var _a2;
28507
29544
  let key = id;
@@ -28567,17 +29604,7 @@ sh:property [
28567
29604
  if (!this.fetch) {
28568
29605
  console.warn("No fetch method available");
28569
29606
  }
28570
- let authenticated = false;
28571
- if (this.session) authenticated = await this.session;
28572
- if (this.fetch && authenticated) {
28573
- return this.fetch.then((fn) => {
28574
- return fn(iri, options);
28575
- });
28576
- }
28577
- if (options.headers) {
28578
- options.headers = this._convertHeaders(options.headers);
28579
- }
28580
- return fetch(iri, options).then((response) => response);
29607
+ return await this.fetch(iri, options);
28581
29608
  }
28582
29609
  async fetchData(id, context2 = null, parentId = "", serverPagination, serverSearch, headers) {
28583
29610
  let iri = this._getAbsoluteIri(id, context2, parentId);
@@ -28820,19 +29847,19 @@ sh:property [
28820
29847
  ]);
28821
29848
  }
28822
29849
  _getAbsoluteIri(id, context2, parentId) {
29850
+ var _a2;
28823
29851
  let iri = normalizeContext(context2, base_context).expandTerm(id);
28824
29852
  if (!iri) return "";
28825
- if (parentId && !parentId.startsWith("store://local")) {
28826
- const parentIri = new URL(parentId, document.location.href).href;
28827
- iri = new URL(iri, parentIri).href;
28828
- } else {
28829
- iri = new URL(iri, document.location.href).href;
29853
+ try {
29854
+ const baseHref = ((_a2 = document == null ? void 0 : document.location) == null ? void 0 : _a2.href) || "";
29855
+ const canUseParent = parentId && !parentId.startsWith("store://local");
29856
+ const base = canUseParent ? new URL(parentId, baseHref).href : baseHref;
29857
+ iri = new URL(iri, base).href;
29858
+ } catch (err) {
29859
+ console.log("[LDPStore _getAbsoluteIri()]", err);
28830
29860
  }
28831
29861
  return iri;
28832
29862
  }
28833
- async getSession() {
28834
- return await this.session;
28835
- }
28836
29863
  _getLanguage() {
28837
29864
  return localStorage.getItem("language") || window.navigator.language.slice(0, 2);
28838
29865
  }
@@ -28850,9 +29877,11 @@ sh:property [
28850
29877
  if (window.sibStore) {
28851
29878
  return window.sibStore;
28852
29879
  }
28853
- const store2 = new LdpStore((_cfg == null ? void 0 : _cfg.options) || {});
28854
- window.sibStore = store2;
28855
- return store2;
29880
+ const store = new LdpStore({
29881
+ ..._cfg == null ? void 0 : _cfg.options
29882
+ });
29883
+ window.sibStore = store;
29884
+ return store;
28856
29885
  }
28857
29886
  const _LdpStoreAdapter = class _LdpStoreAdapter {
28858
29887
  constructor() {
@@ -28866,11 +29895,11 @@ sh:property [
28866
29895
  };
28867
29896
  __publicField(_LdpStoreAdapter, "store");
28868
29897
  let LdpStoreAdapter = _LdpStoreAdapter;
28869
- hasQueryIndex = function(store2) {
28870
- return "queryIndex" in store2 && typeof store2.queryIndex === "function";
29898
+ hasQueryIndex = function(store) {
29899
+ return "queryIndex" in store && typeof store.queryIndex === "function";
28871
29900
  };
28872
- hasSetLocalData = function(store2) {
28873
- return "setLocalData" in store2 && typeof store2.setLocalData === "function";
29901
+ hasSetLocalData = function(store) {
29902
+ return "setLocalData" in store && typeof store.setLocalData === "function";
28874
29903
  };
28875
29904
  StoreType = ((StoreType2) => {
28876
29905
  StoreType2["LDP"] = "ldp";
@@ -28895,37 +29924,106 @@ sh:property [
28895
29924
  StoreFactory.register(StoreType.FederatedCatalogue, FederatedCatalogueStoreAdapter);
28896
29925
  StoreFactory.register(StoreType.DataspaceConnector, DataspaceConnectorStoreAdapter);
28897
29926
  StoreService = (_a = class {
28898
- static init(config) {
28899
- if (StoreService.currentStore) {
28900
- console.warn("[StoreService] Store already initialized. Ignoring duplicate init.");
28901
- return;
29927
+ static addStore(name, config) {
29928
+ var _a2;
29929
+ const trimmedName = name.trim();
29930
+ if (!trimmedName) {
29931
+ throw new Error("[StoreService] Store name cannot be empty.");
29932
+ }
29933
+ if (!config) {
29934
+ throw new Error("[StoreService] Store configuration is required.");
29935
+ }
29936
+ console.log(`\u{1F527} [StoreService.addStore] Adding store "${trimmedName}":`, {
29937
+ storeType: config.type,
29938
+ endpoint: config.endpoint,
29939
+ alreadyExists: StoreService.stores.has(trimmedName)
29940
+ });
29941
+ if (StoreService.stores.has(trimmedName)) {
29942
+ StoreService.logWarning(`Store with name "${trimmedName}" already exists. Overwriting.`);
29943
+ }
29944
+ const store = StoreFactory.create(config);
29945
+ console.log(`\u2705 [StoreService.addStore] Created store for "${trimmedName}":`, {
29946
+ storeType: typeof store,
29947
+ storeConfig: store.config,
29948
+ storeEndpoint: (_a2 = store.config) == null ? void 0 : _a2.endpoint
29949
+ });
29950
+ StoreService.stores.set(trimmedName, {
29951
+ store,
29952
+ config
29953
+ });
29954
+ return store;
29955
+ }
29956
+ static getStore(name) {
29957
+ var _a2;
29958
+ const storeName = StoreService.resolveStoreName(name);
29959
+ if (!storeName) {
29960
+ return null;
29961
+ }
29962
+ const instance = StoreService.stores.get(storeName);
29963
+ if (!instance) {
29964
+ if (storeName === StoreService.defaultStoreName) {
29965
+ return StoreService.fallbackInitIfNeeded();
29966
+ }
29967
+ StoreService.logWarning(`Store with name "${storeName}" not found.`);
29968
+ return null;
28902
29969
  }
28903
- StoreService.currentConfig = config ?? {
29970
+ console.log(`\u{1F4E6} [StoreService.getStore] Retrieving store "${storeName}":`, {
29971
+ found: !!instance,
29972
+ storeEndpoint: (_a2 = instance.store.config) == null ? void 0 : _a2.endpoint,
29973
+ configEndpoint: instance.config.endpoint
29974
+ });
29975
+ return instance.store;
29976
+ }
29977
+ static setDefaultStore(name) {
29978
+ if (!(name == null ? void 0 : name.trim())) {
29979
+ throw new Error("[StoreService] Store name cannot be empty.");
29980
+ }
29981
+ if (!StoreService.stores.has(name)) {
29982
+ throw new Error(`[StoreService] Store with name "${name}" not found.`);
29983
+ }
29984
+ StoreService.defaultStoreName = name;
29985
+ }
29986
+ static init(config) {
29987
+ const storeConfig = config ?? {
28904
29988
  type: StoreType.LDP
28905
29989
  };
28906
- const store2 = StoreFactory.create(StoreService.currentConfig);
28907
- StoreService.currentStore = store2;
29990
+ StoreService.addStore(StoreService.defaultStoreName, storeConfig);
29991
+ StoreService.setDefaultStore(StoreService.defaultStoreName);
28908
29992
  }
28909
29993
  static fallbackInitIfNeeded() {
28910
- if (!StoreService.currentStore) {
29994
+ let instance = StoreService.stores.get(StoreService.defaultStoreName);
29995
+ if (!instance) {
28911
29996
  const defaultConfig = {
28912
29997
  type: StoreType.LDP
28913
29998
  };
28914
- const store2 = StoreFactory.create(defaultConfig);
28915
- StoreService.currentStore = store2;
28916
- StoreService.currentConfig = defaultConfig;
29999
+ const store = StoreFactory.create(defaultConfig);
30000
+ instance = {
30001
+ store,
30002
+ config: defaultConfig
30003
+ };
30004
+ StoreService.stores.set(StoreService.defaultStoreName, instance);
28917
30005
  }
28918
- return StoreService.currentStore;
30006
+ return instance.store;
28919
30007
  }
28920
30008
  static getInstance() {
28921
- if (StoreService.currentStore) return StoreService.currentStore;
28922
- const store2 = StoreService.fallbackInitIfNeeded();
28923
- return store2;
30009
+ const store = StoreService.getStore(StoreService.defaultStoreName);
30010
+ if (!store) {
30011
+ throw new Error("[StoreService] Failed to get or create default store instance.");
30012
+ }
30013
+ return store;
28924
30014
  }
28925
- static getConfig() {
28926
- return StoreService.currentConfig;
30015
+ static getConfig(name) {
30016
+ const storeName = StoreService.resolveStoreName(name);
30017
+ const instance = StoreService.stores.get(storeName);
30018
+ return (instance == null ? void 0 : instance.config) || null;
28927
30019
  }
28928
- }, __publicField(_a, "currentStore", null), __publicField(_a, "currentConfig", null), _a);
30020
+ static resolveStoreName(name) {
30021
+ return (name == null ? void 0 : name.trim()) || StoreService.defaultStoreName;
30022
+ }
30023
+ static logWarning(message) {
30024
+ console.warn(`[StoreService] ${message}`);
30025
+ }
30026
+ }, __publicField(_a, "stores", /* @__PURE__ */ new Map()), __publicField(_a, "defaultStoreName", "default"), _a);
28929
30027
  var __awaiter$3 = function(thisArg, _arguments, P, generator) {
28930
30028
  function adopt(value) {
28931
30029
  return value instanceof P ? value : new P(function(resolve) {
@@ -29156,8 +30254,8 @@ sh:property [
29156
30254
  setLoader(loader) {
29157
30255
  this._loader = loader;
29158
30256
  }
29159
- setLoaderQuadStream(loaderQuadStream) {
29160
- this._loaderQuadStream = loaderQuadStream;
30257
+ setLoaderQuadStream(loaderQuadStream2) {
30258
+ this._loaderQuadStream = loaderQuadStream2;
29161
30259
  }
29162
30260
  setRdfDataModelFactory(dataFactory) {
29163
30261
  this._rdfModelDataFactory = dataFactory;
@@ -32742,8 +33840,8 @@ sh:property [
32742
33840
  function requireJsonldStreamingParser() {
32743
33841
  if (hasRequiredJsonldStreamingParser) return jsonldStreamingParser;
32744
33842
  hasRequiredJsonldStreamingParser = 1;
32745
- (function(exports) {
32746
- var __createBinding = jsonldStreamingParser && jsonldStreamingParser.__createBinding || (Object.create ? function(o, m, k, k2) {
33843
+ (function(exports$1) {
33844
+ var __createBinding = jsonldStreamingParser && jsonldStreamingParser.__createBinding || (Object.create ? (function(o, m, k, k2) {
32747
33845
  if (k2 === void 0) k2 = k;
32748
33846
  var desc = Object.getOwnPropertyDescriptor(m, k);
32749
33847
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
@@ -32755,17 +33853,17 @@ sh:property [
32755
33853
  };
32756
33854
  }
32757
33855
  Object.defineProperty(o, k2, desc);
32758
- } : function(o, m, k, k2) {
33856
+ }) : (function(o, m, k, k2) {
32759
33857
  if (k2 === void 0) k2 = k;
32760
33858
  o[k2] = m[k];
32761
- });
32762
- var __exportStar = jsonldStreamingParser && jsonldStreamingParser.__exportStar || function(m, exports2) {
32763
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
33859
+ }));
33860
+ var __exportStar = jsonldStreamingParser && jsonldStreamingParser.__exportStar || function(m, exports$12) {
33861
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p);
32764
33862
  };
32765
- Object.defineProperty(exports, "__esModule", {
33863
+ Object.defineProperty(exports$1, "__esModule", {
32766
33864
  value: true
32767
33865
  });
32768
- __exportStar(requireJsonLdParser(), exports);
33866
+ __exportStar(requireJsonLdParser(), exports$1);
32769
33867
  })(jsonldStreamingParser);
32770
33868
  return jsonldStreamingParser;
32771
33869
  }
@@ -32853,17 +33951,35 @@ sh:property [
32853
33951
  this.getSemantizer().logError(this, message, options);
32854
33952
  }
32855
33953
  }
32856
- const store$1 = StoreService.getInstance();
32857
33954
  class LoaderQuadStreamCore extends LoaderBase {
33955
+ constructor() {
33956
+ super(...arguments);
33957
+ __publicField(this, "customHeaders", {});
33958
+ }
32858
33959
  getLoggingComponent() {
32859
33960
  return {
32860
33961
  type: "PACKAGE",
32861
33962
  name: "loader-quad-stream-core"
32862
33963
  };
32863
33964
  }
33965
+ setCustomHeaders(headers) {
33966
+ console.log("[LoaderQuadStreamCore] setCustomHeaders called:", headers);
33967
+ this.customHeaders = headers;
33968
+ }
33969
+ clearCustomHeaders() {
33970
+ console.log("[LoaderQuadStreamCore] clearCustomHeaders called");
33971
+ this.customHeaders = {};
33972
+ }
32864
33973
  async load(uri, _otherFetch) {
32865
- const headers = store$1.headers;
32866
- const response = await store$1.fetchAuthn(uri, {
33974
+ const store = StoreService.getInstance();
33975
+ const headers = {
33976
+ ...store.headers,
33977
+ ...this.customHeaders
33978
+ };
33979
+ console.log("[LoaderQuadStreamCore] Loading URI:", uri);
33980
+ console.log("[LoaderQuadStreamCore] Custom headers:", this.customHeaders);
33981
+ console.log("[LoaderQuadStreamCore] Final headers:", headers);
33982
+ const response = await store.fetchAuthn(uri, {
32867
33983
  method: "GET",
32868
33984
  headers,
32869
33985
  credentials: "include"
@@ -32883,16 +33999,34 @@ sh:property [
32883
33999
  return quads;
32884
34000
  }
32885
34001
  }
32886
- const store = StoreService.getInstance();
32887
34002
  class IndexLoader extends LoaderBase {
34003
+ constructor() {
34004
+ super(...arguments);
34005
+ __publicField(this, "customHeaders", {});
34006
+ }
32888
34007
  getLoggingComponent() {
32889
34008
  return {
32890
34009
  type: "PACKAGE",
32891
34010
  name: "loader-quad-stream-core"
32892
34011
  };
32893
34012
  }
34013
+ setCustomHeaders(headers) {
34014
+ console.log("[IndexLoader] setCustomHeaders called:", headers);
34015
+ this.customHeaders = headers;
34016
+ }
34017
+ clearCustomHeaders() {
34018
+ console.log("[IndexLoader] clearCustomHeaders called");
34019
+ this.customHeaders = {};
34020
+ }
32894
34021
  async load(uri) {
32895
- const headers = store.headers;
34022
+ const store = StoreService.getInstance();
34023
+ const headers = {
34024
+ ...store.headers,
34025
+ ...this.customHeaders
34026
+ };
34027
+ console.log("[IndexLoader] Loading URI:", uri);
34028
+ console.log("[IndexLoader] Custom headers:", this.customHeaders);
34029
+ console.log("[IndexLoader] Final headers:", headers);
32896
34030
  const response = await store.fetchAuthn(uri, {
32897
34031
  method: "GET",
32898
34032
  headers,
@@ -32929,19 +34063,37 @@ sh:property [
32929
34063
  return quadsRes;
32930
34064
  }
32931
34065
  }
34066
+ const indexLoader = new IndexLoader();
34067
+ const loaderQuadStream = new LoaderQuadStreamCore();
32932
34068
  const semantizer$1 = new SemantizerImpl(new ConfigurationImpl({
32933
- loader: new IndexLoader(),
32934
- loaderQuadStream: new LoaderQuadStreamCore(),
34069
+ loader: indexLoader,
34070
+ loaderQuadStream,
32935
34071
  datasetImpl: DatasetMixin(DatasetCoreRdfjsImpl),
32936
34072
  rdfModelDataFactory: factory$3,
32937
34073
  mixinFactoryImpl: MixinFactoryImpl,
32938
34074
  datasetBaseFactoryImpl: DatasetBaseFactoryImpl
32939
34075
  }));
32940
- Object.defineProperty(globalThis, "SEMANTIZER", {
32941
- value: semantizer$1,
32942
- writable: false,
32943
- configurable: false
32944
- });
34076
+ if (!globalThis.SEMANTIZER) {
34077
+ Object.defineProperty(globalThis, "SEMANTIZER", {
34078
+ value: semantizer$1,
34079
+ writable: false,
34080
+ configurable: true
34081
+ });
34082
+ }
34083
+ if (!globalThis.SEMANTIZER_INDEX_LOADER) {
34084
+ Object.defineProperty(globalThis, "SEMANTIZER_INDEX_LOADER", {
34085
+ value: indexLoader,
34086
+ writable: false,
34087
+ configurable: true
34088
+ });
34089
+ }
34090
+ if (!globalThis.SEMANTIZER_QUAD_STREAM_LOADER) {
34091
+ Object.defineProperty(globalThis, "SEMANTIZER_QUAD_STREAM_LOADER", {
34092
+ value: loaderQuadStream,
34093
+ writable: false,
34094
+ configurable: true
34095
+ });
34096
+ }
32945
34097
  if (typeof window !== "undefined") {
32946
34098
  if (typeof window.process === "undefined") {
32947
34099
  window.process = {
@@ -32969,6 +34121,8 @@ sh:property [
32969
34121
  semantizer = globalThis.SEMANTIZER;
32970
34122
  })();
32971
34123
  export {
34124
+ AuthFetchResolver as A,
34125
+ DEFAULT_AUTH_SELECTORS as D,
32972
34126
  StoreService as S,
32973
34127
  __tla,
32974
34128
  formatAttributesToServerSearchOptions as a,