cocoda-sdk 1.0.13 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +74 -28
  3. package/dist/cjs/index.cjs +2673 -0
  4. package/dist/cocoda-sdk.js +33 -17423
  5. package/dist/cocoda-sdk.js.LICENSES.txt +105 -86
  6. package/dist/cocoda-sdk.js.map +7 -0
  7. package/dist/esm/errors/index.js +46 -0
  8. package/dist/esm/index.js +9 -0
  9. package/dist/esm/lib/CocodaSDK.js +269 -0
  10. package/dist/esm/providers/base-provider.js +368 -0
  11. package/dist/esm/providers/concept-api-provider.js +278 -0
  12. package/dist/esm/providers/index.js +20 -0
  13. package/dist/esm/providers/label-search-suggestion-provider.js +101 -0
  14. package/dist/esm/providers/loc-api-provider.js +185 -0
  15. package/dist/esm/providers/local-mappings-provider.js +337 -0
  16. package/dist/esm/providers/mappings-api-provider.js +264 -0
  17. package/dist/esm/providers/occurrences-api-provider.js +163 -0
  18. package/dist/esm/providers/reconciliation-api-provider.js +140 -0
  19. package/dist/esm/providers/skosmos-api-provider.js +345 -0
  20. package/{utils → dist/esm/utils}/index.js +40 -53
  21. package/dist/esm/utils/lodash.js +34 -0
  22. package/package.json +16 -17
  23. package/errors/index.js +0 -119
  24. package/index.js +0 -5
  25. package/lib/CocodaSDK.js +0 -360
  26. package/providers/base-provider.js +0 -581
  27. package/providers/concept-api-provider.js +0 -377
  28. package/providers/index.js +0 -34
  29. package/providers/label-search-suggestion-provider.js +0 -219
  30. package/providers/loc-api-provider.js +0 -275
  31. package/providers/local-mappings-provider.js +0 -459
  32. package/providers/mappings-api-provider.js +0 -396
  33. package/providers/occurrences-api-provider.js +0 -234
  34. package/providers/reconciliation-api-provider.js +0 -211
  35. package/providers/skosmos-api-provider.js +0 -441
  36. package/utils/lodash.js +0 -21
@@ -0,0 +1,2673 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
+ var __require = typeof require !== "undefined" ? require : (x) => {
9
+ throw new Error('Dynamic require of "' + x + '" is not supported');
10
+ };
11
+ var __export = (target, all) => {
12
+ __markAsModule(target);
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __reExport = (target, module2, desc) => {
17
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
18
+ for (let key of __getOwnPropNames(module2))
19
+ if (!__hasOwnProp.call(target, key) && key !== "default")
20
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
21
+ }
22
+ return target;
23
+ };
24
+ var __toModule = (module2) => {
25
+ return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
26
+ };
27
+
28
+ // src/index.js
29
+ __export(exports, {
30
+ BaseProvider: () => BaseProvider,
31
+ CocodaSDK: () => CocodaSDK,
32
+ ConceptApiProvider: () => ConceptApiProvider,
33
+ LabelSearchSuggestionProvider: () => LabelSearchSuggestionProvider,
34
+ LocApiProvider: () => LocApiProvider,
35
+ LocalMappingsProvider: () => LocalMappingsProvider,
36
+ MappingsApiProvider: () => MappingsApiProvider,
37
+ OccurrencesApiProvider: () => OccurrencesApiProvider,
38
+ ReconciliationApiProvider: () => ReconciliationApiProvider,
39
+ SkosmosApiProvider: () => SkosmosApiProvider,
40
+ cdk: () => cdk,
41
+ errors: () => errors_exports
42
+ });
43
+
44
+ // src/errors/index.js
45
+ var errors_exports = {};
46
+ __export(errors_exports, {
47
+ BackendError: () => BackendError,
48
+ BackendUnavailableError: () => BackendUnavailableError,
49
+ CDKError: () => CDKError,
50
+ InvalidOrMissingParameterError: () => InvalidOrMissingParameterError,
51
+ InvalidProviderError: () => InvalidProviderError,
52
+ InvalidRequestError: () => InvalidRequestError,
53
+ MethodNotImplementedError: () => MethodNotImplementedError,
54
+ MissingApiUrlError: () => MissingApiUrlError,
55
+ NetworkError: () => NetworkError
56
+ });
57
+ var CDKError = class extends Error {
58
+ constructor({ message = "", relatedError = null, code = null } = {}) {
59
+ if (!message && relatedError && relatedError.message) {
60
+ message = relatedError.message;
61
+ }
62
+ super(message);
63
+ this.name = this.constructor.name;
64
+ this.relatedError = relatedError;
65
+ this.code = code;
66
+ }
67
+ };
68
+ var MethodNotImplementedError = class extends CDKError {
69
+ constructor({ method, message = "", ...options }) {
70
+ options.message = `Method not implemented: ${method} (${message})`;
71
+ super(options);
72
+ }
73
+ };
74
+ var InvalidOrMissingParameterError = class extends CDKError {
75
+ constructor({ parameter, message = "", ...options }) {
76
+ options.message = `Invalid or missing parameter: ${parameter} (${message})`;
77
+ super(options);
78
+ }
79
+ };
80
+ var InvalidRequestError = class extends CDKError {
81
+ };
82
+ var BackendError = class extends CDKError {
83
+ };
84
+ var BackendUnavailableError = class extends CDKError {
85
+ };
86
+ var NetworkError = class extends CDKError {
87
+ };
88
+ var MissingApiUrlError = class extends CDKError {
89
+ };
90
+ var InvalidProviderError = class extends CDKError {
91
+ };
92
+
93
+ // src/lib/CocodaSDK.js
94
+ var import_axios3 = __toModule(require("axios"));
95
+
96
+ // src/utils/lodash.js
97
+ var import_lodash_es = __toModule(require("lodash-es"));
98
+
99
+ // src/lib/CocodaSDK.js
100
+ var import_jskos_tools10 = __toModule(require("jskos-tools"));
101
+
102
+ // src/providers/base-provider.js
103
+ var import_jskos_tools = __toModule(require("jskos-tools"));
104
+ var import_axios = __toModule(require("axios"));
105
+
106
+ // src/utils/index.js
107
+ var requestMethods = [
108
+ {
109
+ method: "getRegistries",
110
+ fallback: [],
111
+ type: "Registries"
112
+ },
113
+ {
114
+ method: "getSchemes",
115
+ fallback: [],
116
+ type: "Schemes"
117
+ },
118
+ {
119
+ method: "vocSearch",
120
+ fallback: [],
121
+ type: "Schemes"
122
+ },
123
+ {
124
+ method: "getTypes",
125
+ fallback: [],
126
+ type: "Types"
127
+ },
128
+ {
129
+ method: "suggest",
130
+ fallback: ["", [], [], []]
131
+ },
132
+ {
133
+ method: "vocSuggest",
134
+ fallback: ["", [], [], []]
135
+ },
136
+ {
137
+ method: "getConcordances",
138
+ fallback: [],
139
+ type: "Concordances"
140
+ },
141
+ {
142
+ method: "getOccurrences",
143
+ fallback: [],
144
+ type: "Occurrences"
145
+ },
146
+ {
147
+ method: "getTop",
148
+ fallback: [],
149
+ type: "Concepts"
150
+ },
151
+ {
152
+ method: "getConcepts",
153
+ fallback: [],
154
+ type: "Concepts"
155
+ },
156
+ {
157
+ method: "getNarrower",
158
+ fallback: [],
159
+ type: "Concepts"
160
+ },
161
+ {
162
+ method: "getAncestors",
163
+ fallback: [],
164
+ type: "Concepts"
165
+ },
166
+ {
167
+ method: "search",
168
+ fallback: [],
169
+ type: "Concepts"
170
+ },
171
+ {
172
+ method: "getMapping",
173
+ fallback: null,
174
+ type: "Mapping"
175
+ },
176
+ {
177
+ method: "getMappings",
178
+ fallback: [],
179
+ type: "Mappings"
180
+ },
181
+ {
182
+ method: "postMapping",
183
+ fallback: null,
184
+ type: "Mapping"
185
+ },
186
+ {
187
+ method: "postMappings",
188
+ fallback: [],
189
+ type: "Mapping"
190
+ },
191
+ {
192
+ method: "putMapping",
193
+ fallback: null,
194
+ type: "Mapping"
195
+ },
196
+ {
197
+ method: "patchMapping",
198
+ fallback: null,
199
+ type: "Mapping"
200
+ },
201
+ {
202
+ method: "deleteMapping",
203
+ fallback: false
204
+ },
205
+ {
206
+ method: "deleteMappings",
207
+ fallback: []
208
+ },
209
+ {
210
+ method: "getAnnotations",
211
+ fallback: [],
212
+ type: "Annotations"
213
+ },
214
+ {
215
+ method: "postAnnotation",
216
+ fallback: null,
217
+ type: "Annotation"
218
+ },
219
+ {
220
+ method: "putAnnotation",
221
+ fallback: null,
222
+ type: "Annotation"
223
+ },
224
+ {
225
+ method: "patchAnnotation",
226
+ fallback: null,
227
+ type: "Annotation"
228
+ },
229
+ {
230
+ method: "deleteAnnotation",
231
+ fallback: false
232
+ }
233
+ ];
234
+ function concatUrl(...parts) {
235
+ let [url, ...otherParts] = parts;
236
+ for (let part of otherParts) {
237
+ if (!url.endsWith("/")) {
238
+ url += "/";
239
+ }
240
+ if (part.startsWith("/")) {
241
+ part = part.slice(1);
242
+ }
243
+ url += part;
244
+ }
245
+ return url;
246
+ }
247
+ function withCustomProps(arr, from) {
248
+ arr._totalCount = from._totalCount;
249
+ arr._url = from._url;
250
+ return arr;
251
+ }
252
+
253
+ // src/providers/base-provider.js
254
+ var BaseProvider = class {
255
+ constructor(registry = {}) {
256
+ this._jskos = registry;
257
+ this.axios = import_axios.default.create({
258
+ timeout: 2e4
259
+ });
260
+ this._path = typeof window !== "undefined" && window.location.pathname;
261
+ this.has = {};
262
+ this._defaultLanguages = "en,de,fr,es,nl,it,fi,pl,ru,cs,jp".split(",");
263
+ this.languages = [];
264
+ this._auth = {
265
+ key: null,
266
+ bearerToken: null
267
+ };
268
+ this._repeating = [];
269
+ this._api = {
270
+ status: registry.status,
271
+ schemes: registry.schemes,
272
+ top: registry.top,
273
+ data: registry.data,
274
+ concepts: registry.concepts,
275
+ narrower: registry.narrower,
276
+ ancestors: registry.ancestors,
277
+ types: registry.types,
278
+ suggest: registry.suggest,
279
+ search: registry.search,
280
+ "voc-suggest": registry["voc-suggest"],
281
+ "voc-search": registry["voc-search"],
282
+ mappings: registry.mappings,
283
+ concordances: registry.concordances,
284
+ annotations: registry.annotations,
285
+ occurrences: registry.occurrences,
286
+ reconcile: registry.reconcile,
287
+ api: registry.api
288
+ };
289
+ this._config = {};
290
+ this.setRetryConfig();
291
+ this.axios.interceptors.request.use((config) => {
292
+ const language = import_lodash_es.uniq([].concat(import_lodash_es.get(config, "params.language", "").split(","), this.languages, this._defaultLanguages).filter((lang) => lang != "")).join(",");
293
+ import_lodash_es.set(config, "params.language", language);
294
+ if (this.has.auth && this._auth.bearerToken && !import_lodash_es.get(config, "headers.Authorization")) {
295
+ import_lodash_es.set(config, "headers.Authorization", `Bearer ${this._auth.bearerToken}`);
296
+ }
297
+ if (config.url.startsWith("http:") && typeof window !== "undefined" && window.location.protocol == "https:") {
298
+ throw new import_axios.default.Cancel("Can't call http API from https.");
299
+ }
300
+ return config;
301
+ });
302
+ this.axios.interceptors.response.use(({ data, headers = {}, config = {} }) => {
303
+ data = import_jskos_tools.default.normalize(data);
304
+ let url = config.url;
305
+ if (!url.endsWith("?")) {
306
+ url += "?";
307
+ }
308
+ import_lodash_es.forOwn(config.params || {}, (value, key) => {
309
+ url += `${key}=${encodeURIComponent(value)}&`;
310
+ });
311
+ if (import_lodash_es.isArray(data) || import_lodash_es.isObject(data)) {
312
+ let totalCount = parseInt(headers["x-total-count"]);
313
+ if (!isNaN(totalCount)) {
314
+ data._totalCount = totalCount;
315
+ }
316
+ data._url = url;
317
+ }
318
+ return data;
319
+ }, (error) => {
320
+ const count = import_lodash_es.get(error, "config._retryCount", 0);
321
+ const method = import_lodash_es.get(error, "config.method");
322
+ const statusCode = import_lodash_es.get(error, "response.status");
323
+ if (this._retryConfig.methods.includes(method) && this._retryConfig.statusCodes.includes(statusCode) && count < this._retryConfig.count) {
324
+ error.config._retryCount = count + 1;
325
+ if (error.config.data)
326
+ error.config.data = JSON.parse(error.config.data);
327
+ return new Promise((resolve, reject) => {
328
+ setTimeout(() => {
329
+ this.axios(error.config).then(resolve).catch(reject);
330
+ }, (() => {
331
+ const delay = this._retryConfig.delay;
332
+ if (typeof delay === "function") {
333
+ return delay(count);
334
+ }
335
+ return delay;
336
+ })());
337
+ });
338
+ } else {
339
+ return Promise.reject(error);
340
+ }
341
+ });
342
+ const currentRequests = [];
343
+ for (let { method, type } of requestMethods) {
344
+ const existingMethod = this[method] && this[method].bind(this);
345
+ if (!existingMethod) {
346
+ this[method] = () => {
347
+ throw new MethodNotImplementedError({ method });
348
+ };
349
+ continue;
350
+ }
351
+ this[method] = (options = {}) => {
352
+ if (options._raw) {
353
+ delete options._raw;
354
+ return existingMethod(options);
355
+ }
356
+ const existingRequest = currentRequests.find((r) => r.method == method && import_lodash_es.isEqual(r.options, options));
357
+ if (existingRequest) {
358
+ return existingRequest.promise;
359
+ }
360
+ let source;
361
+ if (!options.cancelToken) {
362
+ source = this.getCancelTokenSource();
363
+ options.cancelToken = source.token;
364
+ }
365
+ const promise = this.init().then(() => existingMethod(options)).then((result) => {
366
+ if (import_lodash_es.isArray(result) && result._totalCount === void 0) {
367
+ result._totalCount = result.length;
368
+ } else if (import_lodash_es.isObject(result) && result._totalCount === void 0) {
369
+ result._totalCount = 1;
370
+ }
371
+ if (result && type && this[`adjust${type}`]) {
372
+ result = this[`adjust${type}`](result);
373
+ }
374
+ return result;
375
+ }).catch((error) => {
376
+ if (error instanceof CDKError) {
377
+ throw error;
378
+ } else {
379
+ if (error.response) {
380
+ if (error.response.status.toString().startsWith(4)) {
381
+ throw new InvalidRequestError({ relatedError: error, code: error.response.status });
382
+ } else {
383
+ throw new BackendError({ relatedError: error, code: error.response.status });
384
+ }
385
+ } else if (error.request) {
386
+ if (typeof navigator !== "undefined") {
387
+ if (navigator.connection || navigator.mozConnection || navigator.webkitConnection) {
388
+ throw new BackendUnavailableError({ relatedError: error });
389
+ }
390
+ }
391
+ throw new NetworkError({ relatedError: error });
392
+ } else {
393
+ throw new CDKError({ relatedError: error });
394
+ }
395
+ }
396
+ });
397
+ if (source) {
398
+ promise.cancel = (...args) => {
399
+ return source.cancel(...args);
400
+ };
401
+ }
402
+ const request = {
403
+ method,
404
+ options: import_lodash_es.omit(options, ["cancelToken"]),
405
+ promise
406
+ };
407
+ currentRequests.push(request);
408
+ promise.catch(() => {
409
+ }).then(() => currentRequests.splice(currentRequests.indexOf(request), 1));
410
+ return promise;
411
+ };
412
+ }
413
+ }
414
+ get uri() {
415
+ return this._jskos.uri;
416
+ }
417
+ get notation() {
418
+ return this._jskos.notation;
419
+ }
420
+ get prefLabel() {
421
+ return this._jskos.prefLabel;
422
+ }
423
+ get definition() {
424
+ return this._jskos.definition;
425
+ }
426
+ get schemes() {
427
+ return this._jskos.schemes;
428
+ }
429
+ get excludedSchemes() {
430
+ return this._jskos.excludedSchemes;
431
+ }
432
+ get stored() {
433
+ return this._jskos.stored !== void 0 ? this._jskos.stored : this.constructor.stored;
434
+ }
435
+ async init() {
436
+ if (this._init) {
437
+ return this._init;
438
+ }
439
+ this._init = (async () => {
440
+ this._prepare();
441
+ let status;
442
+ if (import_lodash_es.isString(this._api.status)) {
443
+ try {
444
+ status = await this.axios({
445
+ method: "get",
446
+ url: this._api.status
447
+ });
448
+ } catch (error) {
449
+ if (import_lodash_es.get(error, "response.status") === 404) {
450
+ this._api.status = null;
451
+ }
452
+ }
453
+ } else {
454
+ status = this._api.status;
455
+ }
456
+ if (import_lodash_es.isObject(status) && !import_lodash_es.isEmpty(status)) {
457
+ this._config = status.config || {};
458
+ for (let key of Object.keys(this._api)) {
459
+ if (this._api[key] === void 0) {
460
+ this._api[key] = status[key] || null;
461
+ }
462
+ }
463
+ }
464
+ this._setup();
465
+ })();
466
+ return this._init;
467
+ }
468
+ _prepare() {
469
+ }
470
+ _setup() {
471
+ }
472
+ getCancelTokenSource() {
473
+ return import_axios.default.CancelToken.source();
474
+ }
475
+ setAuth({ key = this._auth.key, bearerToken = this._auth.bearerToken }) {
476
+ this._auth.key = key;
477
+ this._auth.bearerToken = bearerToken;
478
+ }
479
+ setRetryConfig(config = {}) {
480
+ this._retryConfig = Object.assign({
481
+ methods: ["get", "head", "options"],
482
+ statusCodes: [401, 403],
483
+ count: 3,
484
+ delay: (count) => {
485
+ return 300 * count;
486
+ }
487
+ }, config);
488
+ }
489
+ isAuthorizedFor({ type, action, user, crossUser }) {
490
+ if (action == "read" && this.has[type] === true) {
491
+ return true;
492
+ }
493
+ if (!this.has[type]) {
494
+ return false;
495
+ }
496
+ const options = import_lodash_es.get(this._config, `${type}.${action}`);
497
+ if (!options) {
498
+ return !!this.has[type][action];
499
+ }
500
+ if (options.auth && (!user || !this._auth.key)) {
501
+ return false;
502
+ }
503
+ if (options.auth && this._auth.key != import_lodash_es.get(this._config, "auth.key")) {
504
+ return false;
505
+ }
506
+ if (options.auth && options.identities) {
507
+ const uris = [user.uri].concat(Object.values(user.identities || {}).map((id) => id.uri)).filter((uri) => uri != null);
508
+ if (import_lodash_es.intersection(uris, options.identities).length == 0) {
509
+ return false;
510
+ }
511
+ }
512
+ if (options.auth && options.identityProviders) {
513
+ const providers2 = Object.keys(user && user.identities || {});
514
+ if (import_lodash_es.intersection(providers2, options.identityProviders).length == 0) {
515
+ return false;
516
+ }
517
+ }
518
+ if (crossUser) {
519
+ return !!options.crossUser;
520
+ }
521
+ return !!this.has[type][action];
522
+ }
523
+ supportsScheme(scheme) {
524
+ if (!scheme) {
525
+ return false;
526
+ }
527
+ let schemes = import_lodash_es.isArray(this.schemes) ? this.schemes : null;
528
+ if (schemes == null && !import_jskos_tools.default.isContainedIn(scheme, this.excludedSchemes || [])) {
529
+ return true;
530
+ }
531
+ return import_jskos_tools.default.isContainedIn(scheme, schemes);
532
+ }
533
+ adjustConcept(concept) {
534
+ concept._getNarrower = (config) => {
535
+ return this.getNarrower({ ...config, concept });
536
+ };
537
+ concept._getAncestors = (config) => {
538
+ return this.getAncestors({ ...config, concept });
539
+ };
540
+ concept._getDetails = async (config) => {
541
+ return (await this.getConcepts({ ...config, concepts: [concept] }))[0];
542
+ };
543
+ for (let type of ["broader", "narrower", "ancestors"]) {
544
+ if (Array.isArray(concept[type]) && !concept[type].includes(null)) {
545
+ concept[type] = this.adjustConcepts(concept[type]);
546
+ }
547
+ }
548
+ concept._registry = this;
549
+ return concept;
550
+ }
551
+ adjustConcepts(concepts) {
552
+ return withCustomProps(concepts.map((concept) => this.adjustConcept(concept)), concepts);
553
+ }
554
+ adjustRegistries(registries) {
555
+ return registries;
556
+ }
557
+ adjustScheme(scheme) {
558
+ scheme._registry = this.cdk && this.cdk.registryForScheme(scheme) || this;
559
+ if (scheme._registry) {
560
+ scheme._getTop = (config) => {
561
+ return scheme._registry.getTop({ ...config, scheme });
562
+ };
563
+ scheme._getTypes = (config) => {
564
+ return scheme._registry.getTypes({ ...config, scheme });
565
+ };
566
+ scheme._suggest = ({ search, ...config }) => {
567
+ return scheme._registry.suggest({ ...config, search, scheme });
568
+ };
569
+ }
570
+ return scheme;
571
+ }
572
+ adjustSchemes(schemes) {
573
+ return withCustomProps(schemes.map((scheme) => this.adjustScheme(scheme)), schemes);
574
+ }
575
+ adjustConcordances(concordances) {
576
+ for (let concordance of concordances) {
577
+ concordance._registry = this;
578
+ }
579
+ return concordances;
580
+ }
581
+ adjustMapping(mapping) {
582
+ for (let side of ["from", "to"]) {
583
+ let sideScheme = `${side}Scheme`;
584
+ if (!mapping[sideScheme]) {
585
+ mapping[sideScheme] = import_lodash_es.get(import_jskos_tools.default.conceptsOfMapping(mapping, side), "[0].inScheme[0]", null);
586
+ }
587
+ }
588
+ mapping._registry = this;
589
+ if (!mapping.identifier) {
590
+ let identifier = import_lodash_es.get(import_jskos_tools.default.addMappingIdentifiers(mapping), "identifier");
591
+ if (identifier) {
592
+ mapping.identifier = identifier;
593
+ }
594
+ }
595
+ return mapping;
596
+ }
597
+ adjustMappings(mappings) {
598
+ return withCustomProps(mappings.map((mapping) => this.adjustMapping(mapping)), mappings);
599
+ }
600
+ async postMappings({ mappings, ...config } = {}) {
601
+ if (!mappings || !mappings.length) {
602
+ throw new InvalidOrMissingParameterError({ parameter: "mappings" });
603
+ }
604
+ return Promise.all(mappings.map((mapping) => this.postMapping({ mapping, ...config, _raw: true })));
605
+ }
606
+ async deleteMappings({ mappings, ...config } = {}) {
607
+ if (!mappings || !mappings.length) {
608
+ throw new InvalidOrMissingParameterError({ parameter: "mappings" });
609
+ }
610
+ return Promise.all(mappings.map((mapping) => this.deleteMapping({ mapping, ...config, _raw: true })));
611
+ }
612
+ };
613
+ BaseProvider.providerName = "Base";
614
+
615
+ // src/providers/local-mappings-provider.js
616
+ var import_jskos_tools2 = __toModule(require("jskos-tools"));
617
+ var import_localforage = __toModule(require("localforage"));
618
+ var import_uuid = __toModule(require("uuid"));
619
+ var uriPrefix = "urn:uuid:";
620
+ var LocalMappingsProvider = class extends BaseProvider {
621
+ _setup() {
622
+ this.has.mappings = {
623
+ read: true,
624
+ create: true,
625
+ update: true,
626
+ delete: true
627
+ };
628
+ this.queue = [];
629
+ this.localStorageKey = "cocoda-mappings--" + this._path;
630
+ let oldLocalStorageKey = "mappings";
631
+ let addUris = () => {
632
+ return import_localforage.default.getItem(this.localStorageKey).then((mappings) => {
633
+ mappings = mappings || [];
634
+ let adjusted = 0;
635
+ for (let mapping of mappings.filter((m) => !m.uri || !m.uri.startsWith(uriPrefix))) {
636
+ if (mapping.uri) {
637
+ if (!mapping.identifier) {
638
+ mapping.identifier = [];
639
+ }
640
+ mapping.identifier.push(mapping.uri);
641
+ }
642
+ mapping.uri = `${uriPrefix}${(0, import_uuid.v4)()}`;
643
+ adjusted += 1;
644
+ }
645
+ if (adjusted) {
646
+ console.warn(`URIs added to ${adjusted} local mappings.`);
647
+ }
648
+ return import_localforage.default.setItem(this.localStorageKey, mappings);
649
+ });
650
+ };
651
+ import_localforage.default.getItem(oldLocalStorageKey).then((results) => {
652
+ if (results) {
653
+ console.warn(`Warning: There is old data in local storage (or IndexedDB, depending on the ) with the key "${oldLocalStorageKey}". This data will not be used anymore. A manual export is necessary to get this data back.`);
654
+ }
655
+ });
656
+ this.queue.push(addUris().catch((error) => {
657
+ console.warn("Error when adding URIs to local mappings:", error);
658
+ }));
659
+ }
660
+ isAuthorizedFor({ type, action }) {
661
+ if (type == "mappings" && action != "anonymous") {
662
+ return true;
663
+ }
664
+ return false;
665
+ }
666
+ _getMappingsQueue() {
667
+ let last2 = import_lodash_es.last(this.queue) || Promise.resolve();
668
+ return new Promise((resolve) => {
669
+ function defer() {
670
+ var res, rej;
671
+ var promise2 = new Promise((resolve2, reject) => {
672
+ res = resolve2;
673
+ rej = reject;
674
+ });
675
+ promise2.resolve = res;
676
+ promise2.reject = rej;
677
+ return promise2;
678
+ }
679
+ let promise = defer();
680
+ let done = () => {
681
+ promise.resolve();
682
+ };
683
+ this.queue.push(promise);
684
+ last2.then(() => {
685
+ return import_localforage.default.getItem(this.localStorageKey);
686
+ }).then((mappings) => {
687
+ resolve({ mappings, done });
688
+ });
689
+ });
690
+ }
691
+ async getMapping({ mapping, ...config }) {
692
+ config._raw = true;
693
+ if (!mapping || !mapping.uri) {
694
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
695
+ }
696
+ return (await this.getMappings({ ...config, uri: mapping.uri }))[0];
697
+ }
698
+ async getMappings({ from, fromScheme, to, toScheme, creator, type, partOf, offset, limit, direction, mode, identifier, uri } = {}) {
699
+ let params = {};
700
+ if (from) {
701
+ params.from = import_lodash_es.isString(from) ? from : from.uri;
702
+ }
703
+ if (fromScheme) {
704
+ params.fromScheme = import_lodash_es.isString(fromScheme) ? { uri: fromScheme } : fromScheme;
705
+ }
706
+ if (to) {
707
+ params.to = import_lodash_es.isString(to) ? to : to.uri;
708
+ }
709
+ if (toScheme) {
710
+ params.toScheme = import_lodash_es.isString(toScheme) ? { uri: toScheme } : toScheme;
711
+ }
712
+ if (creator) {
713
+ params.creator = import_lodash_es.isString(creator) ? creator : import_jskos_tools2.default.prefLabel(creator);
714
+ }
715
+ if (type) {
716
+ params.type = import_lodash_es.isString(type) ? type : type.uri;
717
+ }
718
+ if (partOf) {
719
+ params.partOf = import_lodash_es.isString(partOf) ? partOf : partOf.uri;
720
+ }
721
+ if (offset) {
722
+ params.offset = offset;
723
+ }
724
+ if (limit) {
725
+ params.limit = limit;
726
+ }
727
+ if (direction) {
728
+ params.direction = direction;
729
+ }
730
+ if (mode) {
731
+ params.mode = mode;
732
+ }
733
+ if (identifier) {
734
+ params.identifier = identifier;
735
+ }
736
+ if (uri) {
737
+ params.uri = uri;
738
+ }
739
+ return this._getMappingsQueue().catch((relatedError) => {
740
+ throw new CDKError({ message: "Could not get mappings from local storage", relatedError });
741
+ }).then(({ mappings, done }) => {
742
+ done();
743
+ let checkConcept = (concept, param) => concept.uri == param || param && concept.notation && concept.notation[0].toLowerCase() == param.toLowerCase();
744
+ if (params.from || params.to) {
745
+ mappings = mappings.filter((mapping) => {
746
+ let fromInFrom = import_jskos_tools2.default.conceptsOfMapping(mapping, "from").find((concept) => checkConcept(concept, params.from)) != null;
747
+ let fromInTo = import_jskos_tools2.default.conceptsOfMapping(mapping, "to").find((concept) => checkConcept(concept, params.from)) != null;
748
+ let toInFrom = import_jskos_tools2.default.conceptsOfMapping(mapping, "from").find((concept) => checkConcept(concept, params.to)) != null;
749
+ let toInTo = import_jskos_tools2.default.conceptsOfMapping(mapping, "to").find((concept) => checkConcept(concept, params.to)) != null;
750
+ if (params.direction == "backward") {
751
+ if (params.mode == "or") {
752
+ return params.from && fromInTo || params.to && toInFrom;
753
+ } else {
754
+ return (!params.from || fromInTo) && (!params.to || toInFrom);
755
+ }
756
+ } else if (params.direction == "both") {
757
+ if (params.mode == "or") {
758
+ return params.from && (fromInFrom || fromInTo) || params.to && (toInFrom || toInTo);
759
+ } else {
760
+ return (!params.from || fromInFrom) && (!params.to || toInTo) || (!params.from || fromInTo) && (!params.to || toInFrom);
761
+ }
762
+ } else {
763
+ if (params.mode == "or") {
764
+ return params.from && fromInFrom || params.to && toInTo;
765
+ } else {
766
+ return (!params.from || fromInFrom) && (!params.to || toInTo);
767
+ }
768
+ }
769
+ });
770
+ }
771
+ if (params.fromScheme || params.toScheme) {
772
+ mappings = mappings.filter((mapping) => {
773
+ let fromInFrom = import_jskos_tools2.default.compare(mapping.fromScheme, params.fromScheme);
774
+ let fromInTo = import_jskos_tools2.default.compare(mapping.toScheme, params.fromScheme);
775
+ let toInFrom = import_jskos_tools2.default.compare(mapping.fromScheme, params.toScheme);
776
+ let toInTo = import_jskos_tools2.default.compare(mapping.toScheme, params.toScheme);
777
+ if (params.direction == "backward") {
778
+ if (params.mode == "or") {
779
+ return params.fromScheme && fromInTo || params.toScheme && toInFrom;
780
+ } else {
781
+ return (!params.fromScheme || fromInTo) && (!params.toScheme || toInFrom);
782
+ }
783
+ } else if (params.direction == "both") {
784
+ if (params.mode == "or") {
785
+ return params.fromScheme && (fromInFrom || fromInTo) || params.toScheme && (toInFrom || toInTo);
786
+ } else {
787
+ return (!params.fromScheme || fromInFrom) && (!params.toScheme || toInTo) || (!params.fromScheme || fromInTo) && (!params.toScheme || toInFrom);
788
+ }
789
+ } else {
790
+ if (params.mode == "or") {
791
+ return params.fromScheme && fromInFrom || params.toScheme && toInTo;
792
+ } else {
793
+ return (!params.fromScheme || fromInFrom) && (!params.toScheme || toInTo);
794
+ }
795
+ }
796
+ });
797
+ }
798
+ if (params.creator) {
799
+ let creators = params.creator.split("|");
800
+ mappings = mappings.filter((mapping) => {
801
+ return (mapping.creator && mapping.creator.find((creator2) => creators.includes(import_jskos_tools2.default.prefLabel(creator2)) || creators.includes(creator2.uri))) != null;
802
+ });
803
+ }
804
+ if (params.type) {
805
+ mappings = mappings.filter((mapping) => (mapping.type || [import_jskos_tools2.default.defaultMappingType.uri]).includes(params.type));
806
+ }
807
+ if (params.partOf) {
808
+ mappings = mappings.filter((mapping) => {
809
+ return mapping.partOf != null && mapping.partOf.find((partOf2) => import_jskos_tools2.default.compare(partOf2, { uri: params.partOf })) != null;
810
+ });
811
+ }
812
+ if (params.identifier) {
813
+ mappings = mappings.filter((mapping) => {
814
+ return params.identifier.split("|").map((identifier2) => {
815
+ return (mapping.identifier || []).includes(identifier2) || mapping.uri == identifier2;
816
+ }).reduce((current, total) => current || total);
817
+ });
818
+ }
819
+ if (params.uri) {
820
+ mappings = mappings.filter((mapping) => mapping.uri == params.uri);
821
+ }
822
+ let totalCount = mappings.length;
823
+ mappings = mappings.sort((a, b) => {
824
+ let aDate = a.modified || a.created;
825
+ let bDate = b.modified || b.created;
826
+ if (bDate == null) {
827
+ return -1;
828
+ }
829
+ if (aDate == null) {
830
+ return 1;
831
+ }
832
+ if (aDate > bDate) {
833
+ return -1;
834
+ }
835
+ return 1;
836
+ });
837
+ mappings = mappings.slice(params.offset || 0);
838
+ mappings = mappings.slice(0, params.limit);
839
+ mappings._totalCount = totalCount;
840
+ return mappings;
841
+ });
842
+ }
843
+ async postMapping({ mapping }) {
844
+ if (!mapping) {
845
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
846
+ }
847
+ let { mappings: localMappings, done } = await this._getMappingsQueue();
848
+ if (!mapping.uri || !mapping.uri.startsWith(uriPrefix)) {
849
+ if (mapping.uri) {
850
+ if (!mapping.identifier) {
851
+ mapping.identifier = [];
852
+ }
853
+ mapping.identifier.push(mapping.uri);
854
+ }
855
+ mapping.uri = `${uriPrefix}${(0, import_uuid.v4)()}`;
856
+ }
857
+ if (localMappings.find((m) => m.uri == mapping.uri)) {
858
+ done();
859
+ throw new InvalidOrMissingParameterError({ parameter: "mapping", message: "Duplicate URI" });
860
+ }
861
+ if (!mapping.created) {
862
+ mapping.created = new Date().toISOString();
863
+ }
864
+ if (!mapping.modified) {
865
+ mapping.modified = mapping.created;
866
+ }
867
+ localMappings.push(mapping);
868
+ localMappings = localMappings.map((mapping2) => import_jskos_tools2.default.minifyMapping(mapping2));
869
+ try {
870
+ await import_localforage.default.setItem(this.localStorageKey, localMappings);
871
+ done();
872
+ return mapping;
873
+ } catch (error) {
874
+ done();
875
+ throw error;
876
+ }
877
+ }
878
+ async putMapping({ mapping }) {
879
+ if (!mapping) {
880
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
881
+ }
882
+ let { mappings: localMappings, done } = await this._getMappingsQueue();
883
+ const index = localMappings.findIndex((m) => m.uri == mapping.uri);
884
+ if (index == -1) {
885
+ done();
886
+ throw new InvalidOrMissingParameterError({ parameter: "mapping", message: "Mapping not found" });
887
+ }
888
+ if (!mapping.created) {
889
+ mapping.created = localMappings[index].created;
890
+ }
891
+ mapping.modified = new Date().toISOString();
892
+ localMappings[index] = mapping;
893
+ localMappings = localMappings.map((mapping2) => import_jskos_tools2.default.minifyMapping(mapping2));
894
+ try {
895
+ await import_localforage.default.setItem(this.localStorageKey, localMappings);
896
+ done();
897
+ return mapping;
898
+ } catch (error) {
899
+ done();
900
+ throw error;
901
+ }
902
+ }
903
+ async patchMapping({ mapping }) {
904
+ if (!mapping) {
905
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
906
+ }
907
+ let { mappings: localMappings, done } = await this._getMappingsQueue();
908
+ const index = localMappings.findIndex((m) => m.uri == mapping.uri);
909
+ if (index == -1) {
910
+ done();
911
+ throw new InvalidOrMissingParameterError({ parameter: "mapping", message: "Mapping not found" });
912
+ }
913
+ if (!mapping.created) {
914
+ mapping.created = localMappings[index].created;
915
+ }
916
+ mapping.modified = new Date().toISOString();
917
+ localMappings[index] = Object.assign(localMappings[index], mapping);
918
+ localMappings = localMappings.map((mapping2) => import_jskos_tools2.default.minifyMapping(mapping2));
919
+ try {
920
+ await import_localforage.default.setItem(this.localStorageKey, localMappings);
921
+ done();
922
+ return mapping;
923
+ } catch (error) {
924
+ done();
925
+ throw error;
926
+ }
927
+ }
928
+ async deleteMapping({ mapping }) {
929
+ if (!mapping) {
930
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
931
+ }
932
+ let { mappings: localMappings, done } = await this._getMappingsQueue();
933
+ try {
934
+ localMappings = localMappings.filter((m) => m.uri != mapping.uri);
935
+ localMappings = localMappings.map((mapping2) => import_jskos_tools2.default.minifyMapping(mapping2));
936
+ await import_localforage.default.setItem(this.localStorageKey, localMappings);
937
+ done();
938
+ return true;
939
+ } catch (error) {
940
+ done();
941
+ throw error;
942
+ }
943
+ }
944
+ };
945
+ LocalMappingsProvider.providerName = "LocalMappings";
946
+ LocalMappingsProvider.stored = true;
947
+
948
+ // src/providers/mappings-api-provider.js
949
+ var import_jskos_tools3 = __toModule(require("jskos-tools"));
950
+ var MappingsApiProvider = class extends BaseProvider {
951
+ _prepare() {
952
+ if (this._api.api && this._api.status === void 0) {
953
+ this._api.status = concatUrl(this._api.api, "/status");
954
+ }
955
+ }
956
+ _setup() {
957
+ if (this._api.api) {
958
+ const endpoints = {
959
+ mappings: "/mappings",
960
+ concordances: "/concordances",
961
+ annotations: "/annotations"
962
+ };
963
+ for (let key of Object.keys(endpoints)) {
964
+ if (this._api[key] === void 0) {
965
+ this._api[key] = concatUrl(this._api.api, endpoints[key]);
966
+ }
967
+ }
968
+ }
969
+ this.has.mappings = this._api.mappings ? {} : false;
970
+ if (this.has.mappings) {
971
+ this.has.mappings.read = !!import_lodash_es.get(this._config, "mappings.read", true);
972
+ this.has.mappings.create = !!import_lodash_es.get(this._config, "mappings.create");
973
+ this.has.mappings.update = !!import_lodash_es.get(this._config, "mappings.update");
974
+ this.has.mappings.delete = !!import_lodash_es.get(this._config, "mappings.delete");
975
+ this.has.mappings.anonymous = !!import_lodash_es.get(this._config, "mappings.anonymous");
976
+ }
977
+ this.has.concordances = !!this._api.concordances;
978
+ this.has.annotations = this._api.annotations ? {} : false;
979
+ if (this.has.annotations) {
980
+ this.has.annotations.read = !!import_lodash_es.get(this._config, "annotations.read");
981
+ this.has.annotations.create = !!import_lodash_es.get(this._config, "annotations.create");
982
+ this.has.annotations.update = !!import_lodash_es.get(this._config, "annotations.update");
983
+ this.has.annotations.delete = !!import_lodash_es.get(this._config, "annotations.delete");
984
+ }
985
+ this.has.auth = import_lodash_es.get(this._config, "auth.key") != null;
986
+ this._defaultParams = {
987
+ properties: "annotations"
988
+ };
989
+ }
990
+ async getMapping({ mapping, ...config }) {
991
+ if (!mapping) {
992
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
993
+ }
994
+ if (!mapping.uri || !mapping.uri.startsWith(this._api.mappings)) {
995
+ throw new InvalidOrMissingParameterError({ parameter: "mapping", message: "URI doesn't seem to be part of this registry." });
996
+ }
997
+ try {
998
+ return await this.axios({
999
+ ...config,
1000
+ url: mapping.uri,
1001
+ params: {
1002
+ ...this._defaultParams,
1003
+ ...config.params || {}
1004
+ }
1005
+ });
1006
+ } catch (error) {
1007
+ if (import_lodash_es.get(error, "response.status") == 404) {
1008
+ return null;
1009
+ }
1010
+ throw error;
1011
+ }
1012
+ }
1013
+ async getMappings({ from, fromScheme, to, toScheme, creator, type, partOf, offset, limit, direction, mode, identifier, sort, order, ...config }) {
1014
+ let params = {}, url = this._api.mappings;
1015
+ if (from) {
1016
+ params.from = import_lodash_es.isString(from) ? from : from.uri;
1017
+ }
1018
+ if (fromScheme) {
1019
+ params.fromScheme = import_lodash_es.isString(fromScheme) ? fromScheme : fromScheme.uri;
1020
+ }
1021
+ if (to) {
1022
+ params.to = import_lodash_es.isString(to) ? to : to.uri;
1023
+ }
1024
+ if (toScheme) {
1025
+ params.toScheme = import_lodash_es.isString(toScheme) ? toScheme : toScheme.uri;
1026
+ }
1027
+ if (creator) {
1028
+ params.creator = import_lodash_es.isString(creator) ? creator : import_jskos_tools3.default.prefLabel(creator);
1029
+ }
1030
+ if (type) {
1031
+ params.type = import_lodash_es.isString(type) ? type : type.uri;
1032
+ }
1033
+ if (partOf) {
1034
+ params.partOf = import_lodash_es.isString(partOf) ? partOf : partOf.uri;
1035
+ }
1036
+ if (offset) {
1037
+ params.offset = offset;
1038
+ }
1039
+ if (limit) {
1040
+ params.limit = limit;
1041
+ }
1042
+ if (direction) {
1043
+ params.direction = direction;
1044
+ }
1045
+ if (mode) {
1046
+ params.mode = mode;
1047
+ }
1048
+ if (identifier) {
1049
+ params.identifier = identifier;
1050
+ }
1051
+ if (sort) {
1052
+ params.sort = sort;
1053
+ }
1054
+ if (order) {
1055
+ params.order = order;
1056
+ }
1057
+ return this.axios({
1058
+ ...config,
1059
+ method: "get",
1060
+ url,
1061
+ params: {
1062
+ ...this._defaultParams,
1063
+ ...config.params || {},
1064
+ ...params
1065
+ }
1066
+ });
1067
+ }
1068
+ async postMapping({ mapping, ...config }) {
1069
+ if (!mapping) {
1070
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
1071
+ }
1072
+ mapping = import_jskos_tools3.default.minifyMapping(mapping);
1073
+ mapping = import_jskos_tools3.default.addMappingIdentifiers(mapping);
1074
+ return this.axios({
1075
+ ...config,
1076
+ method: "post",
1077
+ url: this._api.mappings,
1078
+ data: mapping,
1079
+ params: {
1080
+ ...this._defaultParams,
1081
+ ...config.params || {}
1082
+ }
1083
+ });
1084
+ }
1085
+ async putMapping({ mapping, ...config }) {
1086
+ if (!mapping) {
1087
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
1088
+ }
1089
+ mapping = import_jskos_tools3.default.minifyMapping(mapping);
1090
+ mapping = import_jskos_tools3.default.addMappingIdentifiers(mapping);
1091
+ const uri = mapping.uri;
1092
+ if (!uri || !uri.startsWith(this._api.mappings)) {
1093
+ throw new InvalidOrMissingParameterError({ parameter: "mapping", message: "URI doesn't seem to be part of this registry." });
1094
+ }
1095
+ return this.axios({
1096
+ ...config,
1097
+ method: "put",
1098
+ url: uri,
1099
+ data: mapping,
1100
+ params: {
1101
+ ...this._defaultParams,
1102
+ ...config.params || {}
1103
+ }
1104
+ });
1105
+ }
1106
+ async patchMapping({ mapping, ...config }) {
1107
+ if (!mapping) {
1108
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
1109
+ }
1110
+ mapping = import_jskos_tools3.default.minifyMapping(mapping);
1111
+ mapping = import_jskos_tools3.default.addMappingIdentifiers(mapping);
1112
+ const uri = mapping.uri;
1113
+ if (!uri || !uri.startsWith(this._api.mappings)) {
1114
+ throw new InvalidOrMissingParameterError({ parameter: "mapping", message: "URI doesn't seem to be part of this registry." });
1115
+ }
1116
+ return this.axios({
1117
+ ...config,
1118
+ method: "patch",
1119
+ url: uri,
1120
+ data: mapping,
1121
+ params: {
1122
+ ...this._defaultParams,
1123
+ ...config.params || {}
1124
+ }
1125
+ });
1126
+ }
1127
+ async deleteMapping({ mapping, ...config }) {
1128
+ if (!mapping) {
1129
+ throw new InvalidOrMissingParameterError({ parameter: "mapping" });
1130
+ }
1131
+ const uri = mapping.uri;
1132
+ if (!uri || !uri.startsWith(this._api.mappings)) {
1133
+ throw new InvalidOrMissingParameterError({ parameter: "mapping", message: "URI doesn't seem to be part of this registry." });
1134
+ }
1135
+ await this.axios({
1136
+ ...config,
1137
+ method: "delete",
1138
+ url: uri
1139
+ });
1140
+ return true;
1141
+ }
1142
+ async getAnnotations({ target, ...config }) {
1143
+ if (target) {
1144
+ import_lodash_es.set(config, "params.target", target);
1145
+ }
1146
+ return this.axios({
1147
+ ...config,
1148
+ method: "get",
1149
+ url: this._api.annotations
1150
+ });
1151
+ }
1152
+ async postAnnotation({ annotation, ...config }) {
1153
+ return this.axios({
1154
+ ...config,
1155
+ method: "post",
1156
+ url: this._api.annotations,
1157
+ data: annotation
1158
+ });
1159
+ }
1160
+ async putAnnotation({ annotation, ...config }) {
1161
+ const uri = annotation.id;
1162
+ if (!uri || !uri.startsWith(this._api.annotations)) {
1163
+ throw new InvalidOrMissingParameterError({ parameter: "annotation", message: "URI doesn't seem to be part of this registry." });
1164
+ }
1165
+ return this.axios({
1166
+ ...config,
1167
+ method: "put",
1168
+ url: uri,
1169
+ data: annotation
1170
+ });
1171
+ }
1172
+ async patchAnnotation({ annotation, ...config }) {
1173
+ const uri = annotation.id;
1174
+ if (!uri || !uri.startsWith(this._api.annotations)) {
1175
+ throw new InvalidOrMissingParameterError({ parameter: "annotation", message: "URI doesn't seem to be part of this registry." });
1176
+ }
1177
+ return this.axios({
1178
+ ...config,
1179
+ method: "patch",
1180
+ url: uri,
1181
+ data: annotation
1182
+ });
1183
+ }
1184
+ async deleteAnnotation({ annotation, ...config }) {
1185
+ const uri = annotation.id;
1186
+ if (!uri || !uri.startsWith(this._api.annotations)) {
1187
+ throw new InvalidOrMissingParameterError({ parameter: "annotation", message: "URI doesn't seem to be part of this registry." });
1188
+ }
1189
+ await this.axios({
1190
+ ...config,
1191
+ method: "delete",
1192
+ url: uri
1193
+ });
1194
+ return true;
1195
+ }
1196
+ async getConcordances(config) {
1197
+ return this.axios({
1198
+ ...config,
1199
+ method: "get",
1200
+ url: this._api.concordances
1201
+ });
1202
+ }
1203
+ };
1204
+ MappingsApiProvider.providerName = "MappingsApi";
1205
+ MappingsApiProvider.stored = true;
1206
+
1207
+ // src/providers/occurrences-api-provider.js
1208
+ var import_jskos_tools4 = __toModule(require("jskos-tools"));
1209
+ var OccurrencesApiProvider = class extends BaseProvider {
1210
+ _setup() {
1211
+ this._cache = [];
1212
+ this._occurrencesSupportedSchemes = [];
1213
+ this.has.occurrences = true;
1214
+ this.has.mappings = true;
1215
+ }
1216
+ async _occurrencesIsSupported(scheme) {
1217
+ if (this._occurrencesSupportedSchemes && this._occurrencesSupportedSchemes.length) {
1218
+ } else {
1219
+ try {
1220
+ const url = concatUrl(this._api.api, "voc");
1221
+ const data = await this.axios({
1222
+ method: "get",
1223
+ url
1224
+ });
1225
+ this._occurrencesSupportedSchemes = data || [];
1226
+ } catch (error) {
1227
+ }
1228
+ }
1229
+ let supported = false;
1230
+ for (let supportedScheme of this._occurrencesSupportedSchemes) {
1231
+ if (import_jskos_tools4.default.compare(scheme, supportedScheme)) {
1232
+ supported = true;
1233
+ }
1234
+ }
1235
+ return supported;
1236
+ }
1237
+ async getMappings(config) {
1238
+ const occurrences = await this.getOccurrences(config);
1239
+ const fromScheme = import_lodash_es.get(config, "from.inScheme[0]") || config.fromScheme;
1240
+ const toScheme = import_lodash_es.get(config, "to.inScheme[0]") || config.toScheme;
1241
+ const mappings = [];
1242
+ for (let occurrence of occurrences) {
1243
+ if (!occurrence) {
1244
+ continue;
1245
+ }
1246
+ let mapping = {};
1247
+ mapping.from = import_lodash_es.get(occurrence, "memberSet[0]");
1248
+ if (mapping.from) {
1249
+ mapping.from = { memberSet: [mapping.from] };
1250
+ } else {
1251
+ mapping.from = null;
1252
+ }
1253
+ mapping.fromScheme = import_lodash_es.get(occurrence, "memberSet[0].inScheme[0]");
1254
+ mapping.to = import_lodash_es.get(occurrence, "memberSet[1]");
1255
+ if (mapping.to) {
1256
+ mapping.to = { memberSet: [mapping.to] };
1257
+ } else {
1258
+ mapping.to = { memberSet: [] };
1259
+ }
1260
+ mapping.toScheme = import_lodash_es.get(occurrence, "memberSet[1].inScheme[0]");
1261
+ if (fromScheme && mapping.fromScheme && !import_jskos_tools4.default.compare(mapping.fromScheme, fromScheme) || toScheme && mapping.toScheme && !import_jskos_tools4.default.compare(mapping.toScheme, toScheme)) {
1262
+ [mapping.from, mapping.fromScheme, mapping.to, mapping.toScheme] = [mapping.to, mapping.toScheme, mapping.from, mapping.fromScheme];
1263
+ }
1264
+ if (!mapping.fromScheme && fromScheme) {
1265
+ mapping.fromScheme = fromScheme;
1266
+ }
1267
+ if (!mapping.toScheme && toScheme) {
1268
+ mapping.toScheme = toScheme;
1269
+ }
1270
+ mapping.type = [import_jskos_tools4.default.defaultMappingType.uri];
1271
+ mapping._occurrence = occurrence;
1272
+ mapping = import_jskos_tools4.default.addMappingIdentifiers(mapping);
1273
+ if (occurrence.database) {
1274
+ mapping.creator = [occurrence.database];
1275
+ }
1276
+ mappings.push(mapping);
1277
+ }
1278
+ return mappings;
1279
+ }
1280
+ async getOccurrences({ from, to, concepts, ...config }) {
1281
+ let promises = [];
1282
+ concepts = (concepts || []).concat([from, to]).filter((c) => !!c);
1283
+ for (let concept of concepts) {
1284
+ promises.push(this._occurrencesIsSupported(import_lodash_es.get(concept, "inScheme[0]")).then((supported) => {
1285
+ if (supported && concept.uri) {
1286
+ return concept.uri;
1287
+ } else {
1288
+ return null;
1289
+ }
1290
+ }));
1291
+ }
1292
+ let uris = await Promise.all(promises);
1293
+ uris = uris.filter((uri) => uri != null);
1294
+ if (uris.length == 0) {
1295
+ throw new InvalidOrMissingParameterError({ parameter: "concepts" });
1296
+ }
1297
+ promises = [];
1298
+ for (let uri of uris) {
1299
+ promises.push(this._getOccurrences({
1300
+ ...config,
1301
+ params: {
1302
+ member: uri,
1303
+ scheme: "*",
1304
+ threshold: 5
1305
+ }
1306
+ }));
1307
+ }
1308
+ if (uris.length > 1) {
1309
+ let urisString = uris.join(" ");
1310
+ promises.push(this._getOccurrences({
1311
+ ...config,
1312
+ params: {
1313
+ member: urisString,
1314
+ threshold: 5
1315
+ }
1316
+ }));
1317
+ }
1318
+ const results = await Promise.all(promises);
1319
+ let occurrences = import_lodash_es.concat([], ...results);
1320
+ let existingUris = [];
1321
+ let indexesToDelete = [];
1322
+ for (let i = 0; i < occurrences.length; i += 1) {
1323
+ let occurrence = occurrences[i];
1324
+ if (!occurrence) {
1325
+ continue;
1326
+ }
1327
+ let uris2 = occurrence.memberSet.reduce((total, current) => total.concat(current.uri), []).sort().join(" ");
1328
+ if (existingUris.includes(uris2)) {
1329
+ indexesToDelete.push(i);
1330
+ } else {
1331
+ existingUris.push(uris2);
1332
+ }
1333
+ }
1334
+ indexesToDelete.forEach((value) => {
1335
+ delete occurrences[value];
1336
+ });
1337
+ occurrences = occurrences.filter((o) => o != null);
1338
+ return occurrences.sort((a, b) => parseInt(b.count || 0) - parseInt(a.count || 0));
1339
+ }
1340
+ async _getOccurrences(config) {
1341
+ let resultsFromCache = this._cache.find((item) => {
1342
+ return import_lodash_es.isEqual(item.config.params, config.params);
1343
+ });
1344
+ if (resultsFromCache) {
1345
+ return resultsFromCache.data;
1346
+ }
1347
+ const data = await this.axios({
1348
+ ...config,
1349
+ method: "get",
1350
+ url: this._api.api
1351
+ });
1352
+ this._cache.push({
1353
+ config,
1354
+ data
1355
+ });
1356
+ if (this._cache.length > 20) {
1357
+ this._cache = this._cache.slice(this._cache.length - 20);
1358
+ }
1359
+ return data;
1360
+ }
1361
+ };
1362
+ OccurrencesApiProvider.providerName = "OccurrencesApi";
1363
+ OccurrencesApiProvider.stored = false;
1364
+
1365
+ // src/providers/concept-api-provider.js
1366
+ var import_jskos_tools5 = __toModule(require("jskos-tools"));
1367
+ var ConceptApiProvider = class extends BaseProvider {
1368
+ _prepare() {
1369
+ if (this._api.api && this._api.status === void 0) {
1370
+ this._api.status = concatUrl(this._api.api, "/status");
1371
+ }
1372
+ }
1373
+ _setup() {
1374
+ if (this._api.api) {
1375
+ const endpoints = {
1376
+ schemes: "/voc",
1377
+ top: "/voc/top",
1378
+ concepts: "/voc/concepts",
1379
+ data: "/data",
1380
+ narrower: "/narrower",
1381
+ ancestors: "/ancestors",
1382
+ types: "/types",
1383
+ suggest: "/suggest",
1384
+ search: "/search"
1385
+ };
1386
+ for (let key of Object.keys(endpoints)) {
1387
+ if (this._api[key] === void 0) {
1388
+ this._api[key] = concatUrl(this._api.api, endpoints[key]);
1389
+ }
1390
+ }
1391
+ }
1392
+ this.has.schemes = !!this._api.schemes;
1393
+ this.has.top = !!this._api.top;
1394
+ this.has.data = !!this._api.data;
1395
+ this.has.concepts = !!this._api.concepts || this.has.data;
1396
+ this.has.narrower = !!this._api.narrower;
1397
+ this.has.ancestors = !!this._api.ancestors;
1398
+ this.has.types = !!this._api.types;
1399
+ this.has.suggest = !!this._api.suggest;
1400
+ this.has.search = !!this._api.search;
1401
+ this.has.auth = import_lodash_es.get(this._config, "auth.key") != null;
1402
+ this._defaultParams = {
1403
+ properties: "uri,prefLabel,notation,inScheme"
1404
+ };
1405
+ }
1406
+ static _registryConfigForBartocApiConfig({ url } = {}) {
1407
+ if (!url) {
1408
+ return null;
1409
+ }
1410
+ return {
1411
+ api: url
1412
+ };
1413
+ }
1414
+ async _getSchemeUri(scheme) {
1415
+ this._approvedSchemes = this._approvedSchemes || [];
1416
+ this._rejectedSchemes = this._rejectedSchemes || [];
1417
+ let _scheme = this._approvedSchemes.find((s) => import_jskos_tools5.default.compare(scheme, s));
1418
+ if (_scheme) {
1419
+ return _scheme.uri;
1420
+ }
1421
+ if (this._rejectedSchemes.find((s) => import_jskos_tools5.default.compare(scheme, s))) {
1422
+ return null;
1423
+ }
1424
+ const schemes = await this.getSchemes({ uri: import_jskos_tools5.default.getAllUris(scheme) });
1425
+ const resultScheme = schemes.find((s) => import_jskos_tools5.default.compare(s, scheme));
1426
+ if (resultScheme) {
1427
+ this._approvedSchemes.push({
1428
+ uri: resultScheme.uri,
1429
+ identifier: import_jskos_tools5.default.getAllUris(scheme)
1430
+ });
1431
+ return resultScheme.uri;
1432
+ } else {
1433
+ this._rejectedSchemes.push({
1434
+ uri: scheme.uri,
1435
+ identifier: scheme.identifier
1436
+ });
1437
+ return null;
1438
+ }
1439
+ }
1440
+ async getSchemes(config) {
1441
+ if (!this._api.schemes) {
1442
+ throw new MissingApiUrlError();
1443
+ }
1444
+ if (Array.isArray(this._api.schemes)) {
1445
+ return this._api.schemes;
1446
+ }
1447
+ const schemes = await this.axios({
1448
+ ...config,
1449
+ method: "get",
1450
+ url: this._api.schemes,
1451
+ params: {
1452
+ ...this._defaultParams,
1453
+ limit: 500,
1454
+ ...config.params || {}
1455
+ }
1456
+ });
1457
+ if (Array.isArray(this._jskos.schemes)) {
1458
+ return withCustomProps(schemes.filter((s) => import_jskos_tools5.default.isContainedIn(s, this._jskos.schemes)), schemes);
1459
+ } else {
1460
+ return schemes;
1461
+ }
1462
+ }
1463
+ async getTop({ scheme, ...config }) {
1464
+ if (!this._api.top) {
1465
+ throw new MissingApiUrlError();
1466
+ }
1467
+ if (!scheme) {
1468
+ throw new InvalidOrMissingParameterError({ parameter: "scheme" });
1469
+ }
1470
+ const schemeUri = await this._getSchemeUri(scheme);
1471
+ if (!schemeUri) {
1472
+ throw new InvalidOrMissingParameterError({ parameter: "scheme", message: "Requested vocabulary seems to be unsupported by this API." });
1473
+ }
1474
+ if (Array.isArray(this._api.top)) {
1475
+ return this._api.top;
1476
+ }
1477
+ return this.axios({
1478
+ ...config,
1479
+ method: "get",
1480
+ url: this._api.top,
1481
+ params: {
1482
+ ...this._defaultParams,
1483
+ limit: 1e4,
1484
+ ...config.params || {},
1485
+ uri: schemeUri
1486
+ }
1487
+ });
1488
+ }
1489
+ async getConcepts({ concepts, ...config }) {
1490
+ if (!this.has.data) {
1491
+ throw new MissingApiUrlError();
1492
+ }
1493
+ if (!concepts) {
1494
+ throw new InvalidOrMissingParameterError({ parameter: "concepts" });
1495
+ }
1496
+ if (!Array.isArray(concepts)) {
1497
+ concepts = [concepts];
1498
+ }
1499
+ let uris = concepts.map((concept) => concept.uri).filter((uri) => uri != null);
1500
+ return this.axios({
1501
+ ...config,
1502
+ method: "get",
1503
+ url: this._api.data,
1504
+ params: {
1505
+ ...this._defaultParams,
1506
+ limit: 500,
1507
+ ...config.params || {},
1508
+ uri: uris.join("|")
1509
+ }
1510
+ });
1511
+ }
1512
+ async getNarrower({ concept, ...config }) {
1513
+ if (!this._api.narrower) {
1514
+ throw new MissingApiUrlError();
1515
+ }
1516
+ if (!concept || !concept.uri) {
1517
+ throw new InvalidOrMissingParameterError({ parameter: "concept" });
1518
+ }
1519
+ return this.axios({
1520
+ ...config,
1521
+ method: "get",
1522
+ url: this._api.narrower,
1523
+ params: {
1524
+ ...this._defaultParams,
1525
+ limit: 1e4,
1526
+ ...config.params || {},
1527
+ uri: concept.uri
1528
+ }
1529
+ });
1530
+ }
1531
+ async getAncestors({ concept, ...config }) {
1532
+ if (!this._api.ancestors) {
1533
+ throw new MissingApiUrlError();
1534
+ }
1535
+ if (!concept || !concept.uri) {
1536
+ throw new InvalidOrMissingParameterError({ parameter: "concept" });
1537
+ }
1538
+ return this.axios({
1539
+ ...config,
1540
+ method: "get",
1541
+ url: this._api.ancestors,
1542
+ params: {
1543
+ ...this._defaultParams,
1544
+ limit: 1e4,
1545
+ ...config.params || {},
1546
+ uri: concept.uri
1547
+ }
1548
+ });
1549
+ }
1550
+ async suggest({ scheme, use = "notation,label", types = [], sort = "score", ...config }) {
1551
+ return this._search({
1552
+ ...config,
1553
+ endpoint: "suggest",
1554
+ params: {
1555
+ ...config.params,
1556
+ voc: import_lodash_es.get(scheme, "uri", ""),
1557
+ type: types.join("|"),
1558
+ use,
1559
+ sort
1560
+ }
1561
+ });
1562
+ }
1563
+ async search({ scheme, types = [], ...config }) {
1564
+ return this._search({
1565
+ ...config,
1566
+ endpoint: "search",
1567
+ params: {
1568
+ ...config.params,
1569
+ voc: import_lodash_es.get(scheme, "uri", ""),
1570
+ type: types.join("|")
1571
+ }
1572
+ });
1573
+ }
1574
+ async vocSuggest({ use = "notation,label", sort = "score", ...config }) {
1575
+ return this._search({
1576
+ ...config,
1577
+ endpoint: "voc-suggest",
1578
+ params: {
1579
+ ...config.params,
1580
+ use,
1581
+ sort
1582
+ }
1583
+ });
1584
+ }
1585
+ async vocSearch(config) {
1586
+ return this._search({
1587
+ ...config,
1588
+ endpoint: "voc-search"
1589
+ });
1590
+ }
1591
+ async _search({ endpoint, search, limit, offset, params, ...config }) {
1592
+ let url = this._api[endpoint];
1593
+ if (!url) {
1594
+ throw new MissingApiUrlError();
1595
+ }
1596
+ if (!search) {
1597
+ throw new InvalidOrMissingParameterError({ parameter: "search" });
1598
+ }
1599
+ limit = limit || this._jskos.suggestResultLimit || 100;
1600
+ offset = offset || 0;
1601
+ url = url.replace("{searchTerms}", search);
1602
+ return this.axios({
1603
+ ...config,
1604
+ params: {
1605
+ ...this._defaultParams,
1606
+ ...params,
1607
+ limit,
1608
+ count: limit,
1609
+ offset,
1610
+ search,
1611
+ query: search
1612
+ },
1613
+ method: "get",
1614
+ url
1615
+ });
1616
+ }
1617
+ async getTypes({ scheme, ...config }) {
1618
+ if (!this._api.types) {
1619
+ throw new MissingApiUrlError();
1620
+ }
1621
+ if (Array.isArray(this._api.types)) {
1622
+ return this._api.types;
1623
+ }
1624
+ const schemeUri = scheme && await this._getSchemeUri(scheme);
1625
+ if (schemeUri) {
1626
+ import_lodash_es.set(config, "params.uri", schemeUri);
1627
+ }
1628
+ return this.axios({
1629
+ ...config,
1630
+ method: "get",
1631
+ url: this._api.types
1632
+ });
1633
+ }
1634
+ };
1635
+ ConceptApiProvider.providerName = "ConceptApi";
1636
+ ConceptApiProvider.providerType = "http://bartoc.org/api-type/jskos";
1637
+
1638
+ // src/providers/reconciliation-api-provider.js
1639
+ var import_jskos_tools6 = __toModule(require("jskos-tools"));
1640
+ var ReconciliationApiProvider = class extends BaseProvider {
1641
+ _setup() {
1642
+ this.has.mappings = true;
1643
+ this._cache = [];
1644
+ }
1645
+ async getMappings({ from, to, mode, ...config }) {
1646
+ let schemes = [];
1647
+ if (import_lodash_es.isArray(this.schemes)) {
1648
+ schemes = this.schemes;
1649
+ }
1650
+ let swap;
1651
+ let concept;
1652
+ let fromConceptScheme = import_lodash_es.get(from, "inScheme[0]");
1653
+ let toConceptScheme = import_lodash_es.get(to, "inScheme[0]");
1654
+ let fromScheme;
1655
+ let toScheme;
1656
+ if (!from || import_jskos_tools6.default.isContainedIn(fromConceptScheme, schemes)) {
1657
+ swap = true;
1658
+ concept = to;
1659
+ fromScheme = toConceptScheme;
1660
+ toScheme = schemes.find((scheme) => import_jskos_tools6.default.compare(scheme, fromConceptScheme)) || schemes[0];
1661
+ } else {
1662
+ swap = false;
1663
+ concept = from;
1664
+ fromScheme = fromConceptScheme;
1665
+ toScheme = schemes.find((scheme) => import_jskos_tools6.default.compare(scheme, toConceptScheme)) || schemes[0];
1666
+ }
1667
+ if (mode != "or") {
1668
+ return [];
1669
+ }
1670
+ if (!this._api.api) {
1671
+ throw new MissingApiUrlError();
1672
+ }
1673
+ if (!concept) {
1674
+ throw new InvalidOrMissingParameterError({ parameter: swap ? "to" : "from" });
1675
+ }
1676
+ let language = import_jskos_tools6.default.languagePreference.selectLanguage(concept.prefLabel);
1677
+ if (!language) {
1678
+ throw new InvalidOrMissingParameterError({ parameter: swap ? "to" : "from", message: "Missing language" });
1679
+ }
1680
+ let altLabels = import_lodash_es.get(concept, `altLabel.${language}`, []);
1681
+ if (import_lodash_es.isString(altLabels)) {
1682
+ altLabels = [altLabels];
1683
+ }
1684
+ let prefLabel = import_lodash_es.get(concept, `prefLabel.${language}`);
1685
+ let labels = altLabels.concat([prefLabel]);
1686
+ labels = [prefLabel];
1687
+ let { url, data: results } = await this._getReconciliationResults({ ...config, labels, language });
1688
+ results = [].concat(...Object.values(results).map((value) => value.result)).filter((r) => r);
1689
+ results = results.sort((a, b) => {
1690
+ if (a.score != b.score) {
1691
+ return b.score - a.score;
1692
+ }
1693
+ if (a.match != b.match) {
1694
+ if (a.match) {
1695
+ return -1;
1696
+ } else {
1697
+ return 1;
1698
+ }
1699
+ }
1700
+ return a.id.length - b.id.length;
1701
+ });
1702
+ let namespace = import_lodash_es.get(toScheme, "namespace", "");
1703
+ let mappings = results.map((result) => ({
1704
+ fromScheme,
1705
+ from: { memberSet: [concept] },
1706
+ toScheme,
1707
+ to: {
1708
+ memberSet: [
1709
+ {
1710
+ uri: namespace + result.id
1711
+ }
1712
+ ]
1713
+ },
1714
+ type: [
1715
+ result.match ? "http://www.w3.org/2004/02/skos/core#exactMatch" : result.score >= 80 ? "http://www.w3.org/2004/02/skos/core#closeMatch" : "http://www.w3.org/2004/02/skos/core#mappingRelation"
1716
+ ]
1717
+ }));
1718
+ if (swap) {
1719
+ mappings = mappings.map((mapping) => Object.assign(mapping, {
1720
+ fromScheme: mapping.toScheme,
1721
+ from: mapping.to,
1722
+ toScheme: mapping.fromScheme,
1723
+ to: mapping.from
1724
+ }));
1725
+ }
1726
+ mappings._url = url;
1727
+ return mappings;
1728
+ }
1729
+ async _getReconciliationResults({ labels, language, ...config }) {
1730
+ labels = labels.sort();
1731
+ let resultsFromCache = this._cache.find((item) => {
1732
+ return import_lodash_es.isEqual(item.labels, labels) && item.language == language;
1733
+ });
1734
+ if (resultsFromCache) {
1735
+ return resultsFromCache;
1736
+ }
1737
+ let queries = {};
1738
+ let index = 0;
1739
+ for (let label of labels) {
1740
+ queries[`q${index}`] = {
1741
+ query: label
1742
+ };
1743
+ index += 1;
1744
+ }
1745
+ let url = this._api.api;
1746
+ if (language) {
1747
+ url = url.replace("{language}", language);
1748
+ }
1749
+ const encodedData = `queries=${encodeURIComponent(JSON.stringify(queries))}`;
1750
+ import_lodash_es.set(config, ["headers", "Content-Type"], "application/x-www-form-urlencoded");
1751
+ let data = await this.axios({
1752
+ ...config,
1753
+ method: "post",
1754
+ url,
1755
+ data: encodedData
1756
+ });
1757
+ data = data || {};
1758
+ let newCacheEntry = {
1759
+ labels,
1760
+ language,
1761
+ data,
1762
+ url: `${url}${url.includes("?") ? "&" : "?"}${encodedData}`
1763
+ };
1764
+ this._cache.push(newCacheEntry);
1765
+ if (this._cache.length > 20) {
1766
+ this._cache = this._cache.slice(this._cache.length - 20);
1767
+ }
1768
+ return newCacheEntry;
1769
+ }
1770
+ };
1771
+ ReconciliationApiProvider.providerName = "ReconciliationApi";
1772
+ ReconciliationApiProvider.stored = false;
1773
+
1774
+ // src/providers/label-search-suggestion-provider.js
1775
+ var import_jskos_tools7 = __toModule(require("jskos-tools"));
1776
+ var LabelSearchSuggestionProvider = class extends BaseProvider {
1777
+ _setup() {
1778
+ this._cache = [];
1779
+ this.has.mappings = true;
1780
+ }
1781
+ supportsScheme(scheme) {
1782
+ return import_lodash_es.get(scheme, "_registry.has.search", false);
1783
+ }
1784
+ async getMappings({ from, to, mode, selected, limit = 10, ...config }) {
1785
+ if (mode != "or") {
1786
+ return [];
1787
+ }
1788
+ if (!selected) {
1789
+ throw new InvalidOrMissingParameterError({ parameter: "selected" });
1790
+ }
1791
+ let promises = [];
1792
+ if (from && this.supportsScheme(selected.scheme[false])) {
1793
+ promises.push(this._getMappings({ ...config, concept: from, sourceScheme: selected.scheme[true], targetScheme: selected.scheme[false], limit }));
1794
+ } else {
1795
+ promises.push(Promise.resolve([]));
1796
+ }
1797
+ if (to && this.supportsScheme(selected.scheme[true])) {
1798
+ promises.push(this._getMappings({ ...config, concept: to, sourceScheme: selected.scheme[false], targetScheme: selected.scheme[true], limit, swap: true }));
1799
+ } else {
1800
+ promises.push(Promise.resolve([]));
1801
+ }
1802
+ let [fromResult, toResult] = await Promise.all(promises);
1803
+ toResult = toResult.filter((m) => !fromResult.find((n) => import_jskos_tools7.default.compareMappingMembers(m, n)));
1804
+ while (fromResult.length + toResult.length > limit) {
1805
+ if (toResult.length >= fromResult.length) {
1806
+ toResult = toResult.slice(0, -1);
1807
+ } else {
1808
+ fromResult = fromResult.slice(0, -1);
1809
+ }
1810
+ }
1811
+ return import_lodash_es.union(fromResult, toResult);
1812
+ }
1813
+ async _getMappings({ concept, sourceScheme, targetScheme, limit, swap = false, ...config }) {
1814
+ if (!concept || !sourceScheme || !targetScheme) {
1815
+ return [];
1816
+ }
1817
+ if (import_jskos_tools7.default.compare(sourceScheme, targetScheme)) {
1818
+ return [];
1819
+ }
1820
+ let label = import_jskos_tools7.default.prefLabel(concept, {
1821
+ fallbackToUri: false,
1822
+ language: this.languages[0] || this._defaultLanguages[0]
1823
+ });
1824
+ if (!label) {
1825
+ return [];
1826
+ }
1827
+ const results = await this._getResults({ ...config, label, targetScheme, limit });
1828
+ let mappings = results.map((result) => ({
1829
+ fromScheme: sourceScheme,
1830
+ from: { memberSet: [concept] },
1831
+ toScheme: targetScheme,
1832
+ to: { memberSet: [result] },
1833
+ type: ["http://www.w3.org/2004/02/skos/core#mappingRelation"]
1834
+ }));
1835
+ if (swap) {
1836
+ mappings = mappings.map((mapping) => Object.assign(mapping, {
1837
+ fromScheme: mapping.toScheme,
1838
+ from: mapping.to,
1839
+ toScheme: mapping.fromScheme,
1840
+ to: mapping.from
1841
+ }));
1842
+ }
1843
+ return mappings;
1844
+ }
1845
+ async _getResults({ label, targetScheme, limit, ...config }) {
1846
+ let resultsFromCache = (this._cache[targetScheme.uri] || {})[label];
1847
+ if (resultsFromCache && resultsFromCache._limit >= limit) {
1848
+ return resultsFromCache;
1849
+ }
1850
+ const registry = import_lodash_es.get(targetScheme, "_registry");
1851
+ if (!registry || !registry.has.search) {
1852
+ return [];
1853
+ }
1854
+ const data = await registry.search({
1855
+ ...config,
1856
+ search: label,
1857
+ scheme: targetScheme,
1858
+ limit
1859
+ });
1860
+ if (!this._cache[targetScheme.uri]) {
1861
+ this._cache[targetScheme.uri] = {};
1862
+ }
1863
+ this._cache[targetScheme.uri][label] = data;
1864
+ this._cache[targetScheme.uri][label]._limit = limit;
1865
+ return data;
1866
+ }
1867
+ };
1868
+ LabelSearchSuggestionProvider.providerName = "LabelSearchSuggestion";
1869
+ LabelSearchSuggestionProvider.stored = false;
1870
+
1871
+ // src/providers/skosmos-api-provider.js
1872
+ var import_jskos_tools8 = __toModule(require("jskos-tools"));
1873
+ var SkosmosApiProvider = class extends BaseProvider {
1874
+ _setup() {
1875
+ this.has.schemes = true;
1876
+ this.has.top = false;
1877
+ this.has.data = true;
1878
+ this.has.concepts = true;
1879
+ this.has.narrower = true;
1880
+ this.has.ancestors = true;
1881
+ this.has.types = true;
1882
+ this.has.suggest = true;
1883
+ this.has.search = true;
1884
+ for (let scheme of this.schemes) {
1885
+ scheme.concepts = [null];
1886
+ scheme.topConcepts = [];
1887
+ }
1888
+ }
1889
+ static _registryConfigForBartocApiConfig({ url, scheme } = {}) {
1890
+ if (!url || !scheme) {
1891
+ return null;
1892
+ }
1893
+ const config = {};
1894
+ const match = url.match(/(.+\/)([^/]+)\/$/);
1895
+ if (!match) {
1896
+ return null;
1897
+ }
1898
+ config.api = match[1] + "rest/v1/";
1899
+ scheme.VOCID = match[2];
1900
+ config.schemes = [scheme];
1901
+ return config;
1902
+ }
1903
+ get _language() {
1904
+ return this.languages[0] || this._defaultLanguages[0] || "en";
1905
+ }
1906
+ _getApiUrl(scheme, endpoint, params) {
1907
+ if (!scheme || !scheme.VOCID) {
1908
+ throw new InvalidOrMissingParameterError({ parameter: "scheme", message: "Missing scheme or VOCID property on scheme" });
1909
+ }
1910
+ endpoint = endpoint || "";
1911
+ params = params || {};
1912
+ if (!params.lang) {
1913
+ params.lang = this._language;
1914
+ }
1915
+ const paramString = Object.keys(params).map((k) => `${k}=${encodeURIComponent(params[k])}`).join("&");
1916
+ return `${this._api.api}${scheme.VOCID}${endpoint}${paramString ? "?" + paramString : ""}`;
1917
+ }
1918
+ _getDataUrl(concept, { addFormatParameter = true } = {}) {
1919
+ const scheme = import_lodash_es.get(concept, "inScheme[0]");
1920
+ if (!concept || !concept.uri) {
1921
+ throw new InvalidOrMissingParameterError({ parameter: "concept", message: "Missing concept URI" });
1922
+ }
1923
+ return this._getApiUrl(scheme, "/data", addFormatParameter ? { format: "application/json" } : {});
1924
+ }
1925
+ async _getSchemeUri(scheme) {
1926
+ this._approvedSchemes = this._approvedSchemes || [];
1927
+ this._rejectedSchemes = this._rejectedSchemes || [];
1928
+ let _scheme = this._approvedSchemes.find((s) => import_jskos_tools8.default.compare(scheme, s));
1929
+ if (_scheme) {
1930
+ return _scheme.uri;
1931
+ }
1932
+ if (this._rejectedSchemes.find((s) => import_jskos_tools8.default.compare(scheme, s))) {
1933
+ return null;
1934
+ }
1935
+ const url = this._getApiUrl(scheme, "/");
1936
+ const data = await this.axios({
1937
+ method: "get",
1938
+ url
1939
+ });
1940
+ const resultScheme = data.conceptschemes.find((s) => import_jskos_tools8.default.compare(s, scheme));
1941
+ if (resultScheme) {
1942
+ this._approvedSchemes.push({
1943
+ uri: resultScheme.uri,
1944
+ identifier: import_jskos_tools8.default.getAllUris(scheme)
1945
+ });
1946
+ return resultScheme.uri;
1947
+ } else {
1948
+ this._rejectedSchemes.push({
1949
+ uri: scheme.uri,
1950
+ identifier: scheme.identifier
1951
+ });
1952
+ return null;
1953
+ }
1954
+ }
1955
+ _toJskosConcept(skosmosConcept, { concept, scheme, result, language } = {}) {
1956
+ if (!skosmosConcept) {
1957
+ return null;
1958
+ }
1959
+ concept = import_jskos_tools8.default.deepCopy(concept || {});
1960
+ language = language || skosmosConcept.lang || "en";
1961
+ concept.uri = skosmosConcept.uri;
1962
+ if (scheme) {
1963
+ concept.inScheme = [scheme];
1964
+ }
1965
+ let prefLabel = skosmosConcept.matchedPrefLabel || skosmosConcept.prefLabel || skosmosConcept.label;
1966
+ if (import_lodash_es.isString(prefLabel)) {
1967
+ import_lodash_es.set(concept, `prefLabel.${language}`, prefLabel);
1968
+ } else {
1969
+ if (prefLabel && !import_lodash_es.isArray(prefLabel)) {
1970
+ prefLabel = [prefLabel];
1971
+ }
1972
+ for (let label of prefLabel || []) {
1973
+ import_lodash_es.set(concept, `prefLabel.${label.lang}`, label.value);
1974
+ }
1975
+ }
1976
+ let altLabel = skosmosConcept.altLabel;
1977
+ if (import_lodash_es.isString(altLabel)) {
1978
+ import_lodash_es.set(concept, `altLabel.${language}`, [altLabel]);
1979
+ } else {
1980
+ if (altLabel && !import_lodash_es.isArray(altLabel)) {
1981
+ altLabel = [altLabel];
1982
+ }
1983
+ for (let label of altLabel || []) {
1984
+ if (import_lodash_es.get(concept, `altLabel.${label.lang}`)) {
1985
+ concept.altLabel[label.lang].push(label.value);
1986
+ concept.altLabel[label.lang] = import_lodash_es.uniq(concept.altLabel[label.lang]);
1987
+ } else {
1988
+ import_lodash_es.set(concept, `altLabel.${label.lang}`, [label.value]);
1989
+ }
1990
+ }
1991
+ }
1992
+ const notation = skosmosConcept.notation || skosmosConcept["skos:notation"] || import_jskos_tools8.default.notation(concept);
1993
+ if (notation) {
1994
+ concept.notation = [notation.value || notation];
1995
+ }
1996
+ if (skosmosConcept.broader) {
1997
+ if (!import_lodash_es.isArray(skosmosConcept.broader)) {
1998
+ skosmosConcept.broader = [skosmosConcept.broader];
1999
+ }
2000
+ concept.broader = skosmosConcept.broader.map((concept2) => import_lodash_es.isString(concept2) ? { uri: concept2 } : concept2);
2001
+ }
2002
+ if (skosmosConcept.hasChildren === true) {
2003
+ concept.narrower = [null];
2004
+ } else if (skosmosConcept.hasChildren === false) {
2005
+ concept.narrower = [];
2006
+ }
2007
+ if (skosmosConcept.type && !import_lodash_es.isArray(skosmosConcept.type)) {
2008
+ skosmosConcept.type = [skosmosConcept.type];
2009
+ }
2010
+ concept.type = concept.type || [];
2011
+ for (let type of skosmosConcept.type || []) {
2012
+ if (!import_jskos_tools8.default.isValidUri(type)) {
2013
+ continue;
2014
+ }
2015
+ const uriScheme = type.slice(0, type.indexOf(":"));
2016
+ if (result && result["@context"] && result["@context"][uriScheme]) {
2017
+ type = type.replace(uriScheme + ":", result["@context"][uriScheme]);
2018
+ }
2019
+ concept.type.push(type);
2020
+ }
2021
+ concept.type = import_lodash_es.uniq(concept.type);
2022
+ if (!concept.type.length) {
2023
+ concept.type = ["http://www.w3.org/2004/02/skos/core#Concept"];
2024
+ }
2025
+ return concept;
2026
+ }
2027
+ async getSchemes({ ...config }) {
2028
+ const schemes = [];
2029
+ for (let scheme of this.schemes || []) {
2030
+ const url = this._getApiUrl(scheme, "/");
2031
+ const data = await this.axios({
2032
+ ...config,
2033
+ method: "get",
2034
+ url
2035
+ });
2036
+ const resultScheme = data.conceptschemes.find((s) => import_jskos_tools8.default.compare(s, scheme));
2037
+ const label = resultScheme && (resultScheme.prefLabel || resultScheme.label || resultScheme.title);
2038
+ if (label) {
2039
+ import_lodash_es.set(scheme, `prefLabel.${this._language}`, label);
2040
+ }
2041
+ schemes.push(scheme);
2042
+ this._approvedSchemes = this._approvedSchemes || [];
2043
+ if (!this._approvedSchemes.find((s) => import_jskos_tools8.default.compare(scheme, s))) {
2044
+ this._approvedSchemes.push({
2045
+ uri: resultScheme.uri,
2046
+ identifier: import_jskos_tools8.default.getAllUris(scheme)
2047
+ });
2048
+ }
2049
+ }
2050
+ return schemes;
2051
+ }
2052
+ async getTop({ scheme, ...config }) {
2053
+ const url = this._getApiUrl(scheme, "/topConcepts");
2054
+ const schemeUri = await this._getSchemeUri(scheme);
2055
+ if (!schemeUri) {
2056
+ throw new InvalidOrMissingParameterError({ parameter: "scheme", message: "Missing or unsupported scheme or VOCID property on scheme" });
2057
+ }
2058
+ import_lodash_es.set(config, "params.scheme", schemeUri);
2059
+ const response = await this.axios({
2060
+ ...config,
2061
+ method: "get",
2062
+ url
2063
+ });
2064
+ const concepts = [];
2065
+ for (let concept of response.topconcepts || []) {
2066
+ const newConcept = this._toJskosConcept(concept, {
2067
+ scheme,
2068
+ language: this._language
2069
+ });
2070
+ newConcept.topConceptOf = [scheme];
2071
+ concepts.push(newConcept);
2072
+ }
2073
+ return concepts;
2074
+ }
2075
+ async getConcepts({ concepts, ...config }) {
2076
+ if (!import_lodash_es.isArray(concepts)) {
2077
+ concepts = [concepts];
2078
+ }
2079
+ concepts = concepts.map((c) => ({ uri: c.uri, inScheme: c.inScheme }));
2080
+ const newConcepts = [];
2081
+ for (let concept of concepts) {
2082
+ const url = this._getDataUrl(concept, { addFormatParameter: false });
2083
+ if (!url) {
2084
+ continue;
2085
+ }
2086
+ const result = await this.axios({
2087
+ ...config,
2088
+ method: "get",
2089
+ url,
2090
+ params: {
2091
+ uri: concept.uri,
2092
+ format: "application/json"
2093
+ }
2094
+ });
2095
+ const resultConcept = result && result.graph && result.graph.find((c) => import_jskos_tools8.default.compare(c, concept));
2096
+ if (resultConcept) {
2097
+ const newConcept = this._toJskosConcept(resultConcept, { concept, result });
2098
+ for (let type of ["broader", "narrower"]) {
2099
+ let relatives = resultConcept[type] || newConcept[type];
2100
+ if (relatives && !import_lodash_es.isArray(relatives)) {
2101
+ relatives = [relatives];
2102
+ }
2103
+ if (!relatives) {
2104
+ relatives = [];
2105
+ }
2106
+ newConcept[type] = relatives.map((r) => this._toJskosConcept(result.graph.find((c) => import_jskos_tools8.default.compare(c, r)), { scheme: concept.inScheme[0], result }));
2107
+ }
2108
+ newConcept.ancestors = [];
2109
+ newConcepts.push(newConcept);
2110
+ }
2111
+ }
2112
+ return newConcepts;
2113
+ }
2114
+ async getNarrower({ concept, ...config }) {
2115
+ if (!concept || !concept.uri) {
2116
+ throw new InvalidOrMissingParameterError({ parameter: "concept" });
2117
+ }
2118
+ const scheme = concept.inScheme[0];
2119
+ const url = this._getApiUrl(scheme, "/children");
2120
+ import_lodash_es.set(config, "params.uri", concept.uri);
2121
+ const response = await this.axios({
2122
+ ...config,
2123
+ method: "get",
2124
+ url
2125
+ });
2126
+ const concepts = (response.narrower || []).map((c) => this._toJskosConcept(c, { scheme }));
2127
+ return concepts;
2128
+ }
2129
+ async getAncestors({ concept, ...config }) {
2130
+ if (!concept || !concept.uri) {
2131
+ throw new InvalidOrMissingParameterError({ parameter: "concept" });
2132
+ }
2133
+ const scheme = concept.inScheme[0];
2134
+ const url = this._getApiUrl(scheme, "/broaderTransitive");
2135
+ import_lodash_es.set(config, "params.uri", concept.uri);
2136
+ const response = await this.axios({
2137
+ ...config,
2138
+ method: "get",
2139
+ url
2140
+ });
2141
+ let ancestors = [];
2142
+ let uri = concept.uri;
2143
+ while (uri) {
2144
+ if (uri != concept.uri) {
2145
+ const ancestor = import_lodash_es.get(response, `broaderTransitive["${uri}"]`);
2146
+ ancestors = [ancestor].concat(ancestors);
2147
+ }
2148
+ uri = import_lodash_es.get(response, `broaderTransitive["${uri}"].broader[0]`);
2149
+ }
2150
+ const concepts = ancestors.map((c) => this._toJskosConcept(c, { scheme })).filter((c) => c.uri != concept.uri);
2151
+ return concepts;
2152
+ }
2153
+ async suggest(config) {
2154
+ config._raw = true;
2155
+ const concepts = await this.search(config);
2156
+ const result = [config.search, [], [], []];
2157
+ for (let concept of concepts) {
2158
+ const notation = import_jskos_tools8.default.notation(concept);
2159
+ const label = import_jskos_tools8.default.prefLabel(concept);
2160
+ result[1].push((notation ? notation + " " : "") + label);
2161
+ result[2].push("");
2162
+ result[3].push(concept.uri);
2163
+ }
2164
+ if (concepts._totalCount != void 0) {
2165
+ result._totalCount = concepts._totalCount;
2166
+ } else {
2167
+ result._totalCount = concepts.length;
2168
+ }
2169
+ return result;
2170
+ }
2171
+ async search({ search, scheme, limit, types = [], ...config }) {
2172
+ const url = this._getApiUrl(scheme, "/search");
2173
+ import_lodash_es.set(config, "params.query", `${search}*`);
2174
+ import_lodash_es.set(config, "params.unique", 1);
2175
+ import_lodash_es.set(config, "params.maxhits", limit || 100);
2176
+ import_lodash_es.set(config, "params.type", types.join(" "));
2177
+ const response = await this.axios({
2178
+ ...config,
2179
+ method: "get",
2180
+ url
2181
+ });
2182
+ const concepts = (response.results || []).map((c) => this._toJskosConcept(c, { scheme }));
2183
+ return concepts;
2184
+ }
2185
+ async getTypes({ scheme, ...config }) {
2186
+ const url = this._getApiUrl(scheme, "/types");
2187
+ const types = [];
2188
+ const response = await this.axios({
2189
+ ...config,
2190
+ method: "get",
2191
+ url
2192
+ });
2193
+ for (let type of response && response.types || []) {
2194
+ if (type.uri == "http://www.w3.org/2004/02/skos/core#Concept") {
2195
+ continue;
2196
+ }
2197
+ if (type.label) {
2198
+ type.prefLabel = {
2199
+ [response["@context"]["@language"]]: type.label
2200
+ };
2201
+ delete type.label;
2202
+ }
2203
+ types.push(type);
2204
+ }
2205
+ types._url = url;
2206
+ return types;
2207
+ }
2208
+ };
2209
+ SkosmosApiProvider.providerName = "SkosmosApi";
2210
+ SkosmosApiProvider.providerType = "http://bartoc.org/api-type/skosmos";
2211
+
2212
+ // src/providers/loc-api-provider.js
2213
+ var import_jskos_tools9 = __toModule(require("jskos-tools"));
2214
+ var import_axios2 = __toModule(require("axios"));
2215
+ var locUriPrefix = "http://id.loc.gov/authorities/";
2216
+ var supportedSchemes = [
2217
+ {
2218
+ uri: `${locUriPrefix}subjects`,
2219
+ identifier: [
2220
+ "http://bartoc.org/en/node/454"
2221
+ ],
2222
+ notation: ["LCSH"],
2223
+ concepts: [null],
2224
+ topConcepts: []
2225
+ },
2226
+ {
2227
+ uri: `${locUriPrefix}names`,
2228
+ identifier: [
2229
+ "http://bartoc.org/en/node/18536"
2230
+ ],
2231
+ notation: ["LCNAF"],
2232
+ concepts: [null],
2233
+ topConcepts: []
2234
+ }
2235
+ ];
2236
+ var lccUri = `${locUriPrefix}classification`;
2237
+ function madsToJskosItem(data) {
2238
+ const item = {};
2239
+ item.uri = data["@id"];
2240
+ item.notation = (data["http://www.loc.gov/mads/rdf/v1#code"] || []).map((n) => n["@value"]);
2241
+ const prefLabelArray = data["http://www.loc.gov/mads/rdf/v1#authoritativeLabel"] || data["http://www.w3.org/2000/01/rdf-schema#label"] || [];
2242
+ if (prefLabelArray.length) {
2243
+ item.prefLabel = {};
2244
+ item.prefLabel[prefLabelArray[0]["@language"] || "en"] = prefLabelArray[0]["@value"];
2245
+ }
2246
+ const altLabelArray = data["http://www.w3.org/2004/02/skos/core#altLabel"] || [];
2247
+ if (altLabelArray.length) {
2248
+ item.altLabel = { en: altLabelArray.map((l) => l["@value"]) };
2249
+ }
2250
+ for (let definition of data["http://www.w3.org/2000/01/rdf-schema#comment"] || []) {
2251
+ item.definition = item.definition || {};
2252
+ item.definition.en = item.definition.en || [];
2253
+ item.definition.en.push(definition["@value"]);
2254
+ }
2255
+ return item;
2256
+ }
2257
+ function madsToJskosScheme(data) {
2258
+ const scheme = madsToJskosItem(data);
2259
+ scheme.namespace = scheme.uri + "/";
2260
+ scheme.type = ["http://www.w3.org/2004/02/skos/core#ConceptScheme"];
2261
+ return scheme;
2262
+ }
2263
+ var schemeNamespaceFilter = (scheme) => (c) => {
2264
+ if (!c || !scheme || !scheme.namespace) {
2265
+ return true;
2266
+ }
2267
+ return c.uri.startsWith(scheme.namespace);
2268
+ };
2269
+ function madsToJskosConcept(data, { scheme }) {
2270
+ const concept = madsToJskosItem(data);
2271
+ concept.type = ["http://www.w3.org/2004/02/skos/core#Concept"];
2272
+ concept.inScheme = scheme ? [scheme] : (data["http://www.loc.gov/mads/rdf/v1#isMemberOfMADSScheme"] || []).map((s) => supportedSchemes.find((s2) => s2.uri === s["@id"]));
2273
+ if (!concept.inScheme.length || !concept.inScheme[0]) {
2274
+ delete concept.inScheme;
2275
+ }
2276
+ const narrower = data["http://www.loc.gov/mads/rdf/v1#hasNarrowerAuthority"] || import_jskos_tools9.default.compare(concept.inScheme[0], { uri: lccUri }) && data["http://www.loc.gov/mads/rdf/v1#hasMADSCollectionMember"] || [];
2277
+ concept.narrower = narrower.map((n) => ({ uri: n["@id"] })).filter(schemeNamespaceFilter(concept.inScheme && concept.inScheme[0]));
2278
+ const broader = data["http://www.loc.gov/mads/rdf/v1#hasBroaderAuthority"] || import_jskos_tools9.default.compare(concept.inScheme[0], { uri: lccUri }) && data["http://www.loc.gov/mads/rdf/v1#isMemberOfMADSCollection"] || [];
2279
+ concept.broader = broader.map((n) => ({ uri: n["@id"] })).filter(schemeNamespaceFilter(concept.inScheme && concept.inScheme[0]));
2280
+ return concept;
2281
+ }
2282
+ var LocApiProvider = class extends BaseProvider {
2283
+ _setup() {
2284
+ this.has.schemes = true;
2285
+ this.has.top = false;
2286
+ this.has.data = true;
2287
+ this.has.concepts = true;
2288
+ this.has.narrower = true;
2289
+ this.has.ancestors = false;
2290
+ this.has.suggest = true;
2291
+ this.has.search = true;
2292
+ }
2293
+ static _registryConfigForBartocApiConfig({ scheme } = {}) {
2294
+ if (!scheme || !supportedSchemes.find((s) => import_jskos_tools9.default.compare(s, scheme))) {
2295
+ return null;
2296
+ }
2297
+ return {
2298
+ schemes: [scheme]
2299
+ };
2300
+ }
2301
+ async getSchemes() {
2302
+ const schemes = [];
2303
+ for (let scheme of await Promise.all(supportedSchemes.filter((s) => !this.schemes || !this.schemes.length || this.schemes.find((s2) => import_jskos_tools9.default.compare(s, s2))).map((s) => (0, import_axios2.default)({
2304
+ method: "get",
2305
+ url: `${s.uri.replace("http:", "https:")}.json`
2306
+ }).then(({ status, data }) => {
2307
+ if (status === 200) {
2308
+ let scheme2 = data.find((d) => s.uri === d["@id"]);
2309
+ if (scheme2) {
2310
+ scheme2 = import_jskos_tools9.default.merge(madsToJskosScheme(scheme2), s);
2311
+ scheme2.topConcepts = (scheme2.topConcepts || []).filter((c) => c);
2312
+ return scheme2;
2313
+ }
2314
+ }
2315
+ return null;
2316
+ })))) {
2317
+ if (scheme) {
2318
+ schemes.push(scheme);
2319
+ }
2320
+ }
2321
+ return schemes;
2322
+ }
2323
+ async getConcepts({ concepts }) {
2324
+ if (!Array.isArray(concepts)) {
2325
+ concepts = [concepts];
2326
+ }
2327
+ const resultConcepts = [];
2328
+ for (let concept of await Promise.all(concepts.map((c) => (0, import_axios2.default)({
2329
+ method: "get",
2330
+ url: `${c.uri.replace("http:", "https:")}.json`
2331
+ }).then(({ status, data }) => {
2332
+ if (status === 200) {
2333
+ let concept2 = data.find((d) => c.uri === d["@id"]);
2334
+ if (concept2) {
2335
+ return madsToJskosConcept(concept2, { scheme: c.inScheme && c.inScheme[0] });
2336
+ }
2337
+ return null;
2338
+ }
2339
+ })))) {
2340
+ if (concept) {
2341
+ resultConcepts.push(concept);
2342
+ }
2343
+ }
2344
+ return resultConcepts;
2345
+ }
2346
+ async suggest(config) {
2347
+ const results = await this.search(config);
2348
+ return [
2349
+ config.search,
2350
+ results.map((c) => {
2351
+ let string = "";
2352
+ const notation = import_jskos_tools9.default.notation(c);
2353
+ if (notation) {
2354
+ string += notation + " ";
2355
+ }
2356
+ string += import_jskos_tools9.default.prefLabel(c, { fallbackToUri: string === "" });
2357
+ return string;
2358
+ }),
2359
+ [],
2360
+ results.map((c) => c.uri)
2361
+ ];
2362
+ }
2363
+ async search({ search, scheme, limit, offset }) {
2364
+ const schemeUri = import_jskos_tools9.default.getAllUris(scheme).find((uri) => uri.startsWith(locUriPrefix));
2365
+ if (!schemeUri || !supportedSchemes.find((s) => import_jskos_tools9.default.compare(s, { uri: schemeUri }))) {
2366
+ throw new InvalidOrMissingParameterError({ parameter: "scheme", message: "provided scheme is not supported (yet)" });
2367
+ }
2368
+ if (!search) {
2369
+ throw new InvalidOrMissingParameterError({ parameter: "search", message: "parameter is empty or missing" });
2370
+ }
2371
+ limit = limit || this._jskos.suggestResultLimit || 100;
2372
+ offset = offset || 0;
2373
+ const { data } = await (0, import_axios2.default)({
2374
+ method: "get",
2375
+ url: `${schemeUri}/suggest2`.replace("http:", "https:"),
2376
+ params: {
2377
+ q: search,
2378
+ count: limit || 100,
2379
+ offset,
2380
+ searchtype: "keyword"
2381
+ }
2382
+ });
2383
+ return (data.hits || []).map((d) => ({
2384
+ uri: d.uri,
2385
+ notation: [d.token],
2386
+ prefLabel: { en: d.aLabel },
2387
+ inScheme: [scheme]
2388
+ })).filter(schemeNamespaceFilter(scheme));
2389
+ }
2390
+ };
2391
+ LocApiProvider.providerName = "LocApi";
2392
+ LocApiProvider.providerType = "http://bartoc.org/api-type/loc";
2393
+
2394
+ // src/lib/CocodaSDK.js
2395
+ var providers = {
2396
+ [BaseProvider.providerName]: BaseProvider,
2397
+ init(registry) {
2398
+ if (this[registry.provider]) {
2399
+ return new this[registry.provider](registry);
2400
+ }
2401
+ throw new InvalidProviderError();
2402
+ },
2403
+ addProvider(provider) {
2404
+ if (provider.prototype instanceof BaseProvider || provider === BaseProvider) {
2405
+ this[provider.providerName] = provider;
2406
+ } else {
2407
+ throw new InvalidProviderError();
2408
+ }
2409
+ }
2410
+ };
2411
+ providers.addProvider(ConceptApiProvider);
2412
+ providers.addProvider(MappingsApiProvider);
2413
+ var CocodaSDK = class {
2414
+ constructor(config) {
2415
+ this.config = config;
2416
+ this.axios = import_axios3.default.create();
2417
+ }
2418
+ setConfig(config) {
2419
+ this.config = config;
2420
+ }
2421
+ get config() {
2422
+ return this._config;
2423
+ }
2424
+ set config(config) {
2425
+ config = config || {};
2426
+ config.registries = config.registries || [];
2427
+ config.registries = config.registries.map((registry) => providers.init(registry)).filter((r) => r);
2428
+ config.registries.forEach((registry) => {
2429
+ registry.cdk = this;
2430
+ });
2431
+ this._config = config;
2432
+ }
2433
+ get providers() {
2434
+ return providers;
2435
+ }
2436
+ createInstance(config) {
2437
+ return new CocodaSDK(config);
2438
+ }
2439
+ async loadConfig(url) {
2440
+ const response = await this.axios.get(url);
2441
+ this.config = response.data;
2442
+ }
2443
+ loadBuildInfo({ url, buildInfo = null, interval = 6e4, callback, ...config }) {
2444
+ if (!url && !this.config.cocodaBaseUrl) {
2445
+ throw new CDKError({ message: "Could not determine URL to load build config." });
2446
+ }
2447
+ if (!url) {
2448
+ url = `${this.config.cocodaBaseUrl}build-info.json`;
2449
+ }
2450
+ return this.repeat({
2451
+ ...config,
2452
+ function: async () => {
2453
+ return (await this.axios.get(url, {
2454
+ headers: {
2455
+ "Cache-Control": "no-cache"
2456
+ }
2457
+ })).data;
2458
+ },
2459
+ interval,
2460
+ callback: (error, result, previousResult) => {
2461
+ if (error) {
2462
+ callback(error);
2463
+ } else if (previousResult || !previousResult && buildInfo && !import_lodash_es.isEqual(result, buildInfo)) {
2464
+ callback(null, result, previousResult || buildInfo);
2465
+ }
2466
+ }
2467
+ });
2468
+ }
2469
+ getRegistryForUri(uri) {
2470
+ return this.config.registries.find((r) => r.uri == uri);
2471
+ }
2472
+ initializeRegistry(registry) {
2473
+ registry = providers.init(registry);
2474
+ registry.cdk = this;
2475
+ return registry;
2476
+ }
2477
+ addProvider(provider) {
2478
+ providers.addProvider(provider);
2479
+ }
2480
+ static addProvider(provider) {
2481
+ providers.addProvider(provider);
2482
+ }
2483
+ repeat({ function: func, interval = 15e3, callback, callImmediately = true } = {}) {
2484
+ if (!func) {
2485
+ throw new InvalidOrMissingParameterError({ parameter: "function" });
2486
+ }
2487
+ if (typeof func != "function") {
2488
+ throw new InvalidOrMissingParameterError({ parameter: "function", message: "function needs to be a function" });
2489
+ }
2490
+ const asyncFunc = async () => func();
2491
+ interval = parseInt(interval);
2492
+ if (isNaN(interval)) {
2493
+ throw new InvalidOrMissingParameterError({ parameter: "interval" });
2494
+ }
2495
+ if (!callback) {
2496
+ throw new InvalidOrMissingParameterError({ parameter: "callback" });
2497
+ }
2498
+ if (typeof callback != "function") {
2499
+ throw new InvalidOrMissingParameterError({ parameter: "callback", message: "callback needs to be a function" });
2500
+ }
2501
+ let repeat = {
2502
+ timer: null,
2503
+ result: null,
2504
+ error: null,
2505
+ isPaused: false
2506
+ };
2507
+ const handleResult = (result) => {
2508
+ const previousResult = repeat.result;
2509
+ if (!import_lodash_es.isEqual(previousResult, result)) {
2510
+ repeat.result = result;
2511
+ repeat.error = null;
2512
+ callback(null, result, previousResult);
2513
+ }
2514
+ };
2515
+ const handleError = (error) => {
2516
+ repeat.error = error;
2517
+ callback(error);
2518
+ };
2519
+ const repeatIfNecessary = (toCall) => {
2520
+ if (repeat.isPaused) {
2521
+ return;
2522
+ }
2523
+ repeat.timer = setTimeout(() => {
2524
+ toCall();
2525
+ }, interval);
2526
+ };
2527
+ const call = () => asyncFunc().then(handleResult).catch(handleError).then(() => repeatIfNecessary(call));
2528
+ const setup = (_callImmediately = callImmediately) => {
2529
+ if (_callImmediately) {
2530
+ call();
2531
+ } else {
2532
+ repeatIfNecessary(call);
2533
+ }
2534
+ };
2535
+ setup();
2536
+ return {
2537
+ start: (...params) => {
2538
+ repeat.isPaused = false;
2539
+ setup(...params);
2540
+ },
2541
+ stop: () => {
2542
+ repeat.isPaused = true;
2543
+ if (repeat.timer) {
2544
+ clearTimeout(repeat.timer);
2545
+ } else {
2546
+ setTimeout(() => {
2547
+ repeat.timer && clearTimeout(repeat.timer);
2548
+ }, interval);
2549
+ }
2550
+ },
2551
+ get isPaused() {
2552
+ return repeat.isPaused;
2553
+ },
2554
+ get lastResult() {
2555
+ return repeat.result;
2556
+ },
2557
+ get hasErrored() {
2558
+ return !!repeat.error;
2559
+ }
2560
+ };
2561
+ }
2562
+ async getSchemes(config = {}) {
2563
+ let schemes = [], promises = [];
2564
+ for (let registry of this.config.registries) {
2565
+ if (registry.has.schemes) {
2566
+ let promise = registry.getSchemes(config).then((results) => {
2567
+ for (let scheme of results) {
2568
+ scheme.__DETAILSLOADED__ = 1;
2569
+ scheme.type = scheme.type || ["http://www.w3.org/2004/02/skos/core#ConceptScheme"];
2570
+ let otherScheme = schemes.find((s) => import_jskos_tools10.default.compare(s, scheme)), prio, otherPrio, override = false;
2571
+ if (otherScheme) {
2572
+ prio = this.config.registries.indexOf(registry);
2573
+ if (prio != -1) {
2574
+ prio = this.config.registries.length - prio;
2575
+ }
2576
+ otherPrio = this.config.registries.indexOf(import_lodash_es.get(otherScheme, "_registry"));
2577
+ if (otherPrio != -1) {
2578
+ otherPrio = this.config.registries.length - otherPrio;
2579
+ }
2580
+ let currentHasConcepts = !scheme.concepts ? 0 : scheme.concepts.length == 0 ? -1 : 1;
2581
+ let otherHasConcepts = !otherScheme.concepts ? 0 : otherScheme.concepts.length == 0 ? -1 : 1;
2582
+ if (currentHasConcepts > otherHasConcepts) {
2583
+ override = true;
2584
+ } else if (currentHasConcepts < otherHasConcepts) {
2585
+ override = false;
2586
+ } else {
2587
+ override = otherPrio < prio;
2588
+ }
2589
+ }
2590
+ if (!otherScheme || override) {
2591
+ if (override) {
2592
+ let otherSchemeIndex = schemes.findIndex((s) => import_jskos_tools10.default.compare(s, otherScheme));
2593
+ if (otherSchemeIndex != -1) {
2594
+ schemes.splice(otherSchemeIndex, 1);
2595
+ }
2596
+ scheme = import_jskos_tools10.default.merge(scheme, otherScheme, { mergeUris: true, skipPaths: ["_registry"] });
2597
+ }
2598
+ scheme._registry = registry;
2599
+ schemes.push(scheme);
2600
+ } else {
2601
+ let index = schemes.findIndex((s) => import_jskos_tools10.default.compare(s, scheme));
2602
+ if (index != -1) {
2603
+ let registry2 = schemes[index]._registry;
2604
+ schemes[index] = import_jskos_tools10.default.merge(schemes[index], import_lodash_es.omit(scheme, ["concepts", "topConcepts"]), { mergeUris: true, skipPaths: ["_registry"] });
2605
+ schemes[index]._registry = registry2;
2606
+ }
2607
+ }
2608
+ }
2609
+ }).catch((error) => {
2610
+ console.warn("Couldn't load schemes for registry", registry.uri, error);
2611
+ });
2612
+ promises.push(promise);
2613
+ }
2614
+ }
2615
+ return Promise.all(promises).then(() => {
2616
+ for (let scheme of schemes) {
2617
+ if (scheme.concepts && scheme.concepts.length == 0) {
2618
+ delete scheme.concepts;
2619
+ }
2620
+ if (scheme.topConcepts && scheme.topConcepts.length == 0) {
2621
+ delete scheme.topConcepts;
2622
+ }
2623
+ }
2624
+ schemes = schemes.filter((scheme) => scheme != null);
2625
+ schemes = import_jskos_tools10.default.sortSchemes(schemes);
2626
+ return schemes;
2627
+ });
2628
+ }
2629
+ registryForScheme(scheme) {
2630
+ let registry = scheme._registry;
2631
+ if (registry) {
2632
+ return registry;
2633
+ }
2634
+ for (let { type, ...config } of scheme.API || []) {
2635
+ const provider = Object.values(providers).find((p) => p.providerType === type);
2636
+ if (!provider || !provider._registryConfigForBartocApiConfig) {
2637
+ continue;
2638
+ }
2639
+ const providerName = provider.providerName;
2640
+ config.scheme = scheme;
2641
+ config = providers[providerName]._registryConfigForBartocApiConfig(config);
2642
+ if (!config) {
2643
+ continue;
2644
+ }
2645
+ config.provider = providerName;
2646
+ try {
2647
+ registry = this.initializeRegistry(config);
2648
+ return registry;
2649
+ } catch (error) {
2650
+ continue;
2651
+ }
2652
+ }
2653
+ return null;
2654
+ }
2655
+ };
2656
+
2657
+ // src/index.js
2658
+ var cdk = new CocodaSDK();
2659
+ // Annotate the CommonJS export names for ESM import in node:
2660
+ 0 && (module.exports = {
2661
+ BaseProvider,
2662
+ CocodaSDK,
2663
+ ConceptApiProvider,
2664
+ LabelSearchSuggestionProvider,
2665
+ LocApiProvider,
2666
+ LocalMappingsProvider,
2667
+ MappingsApiProvider,
2668
+ OccurrencesApiProvider,
2669
+ ReconciliationApiProvider,
2670
+ SkosmosApiProvider,
2671
+ cdk,
2672
+ errors
2673
+ });