@iqb/metadata-resolver 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ ## 0.2.2
4
+
5
+ - With `cache: false`, the getters retain the last successfully loaded
6
+ vocabulary for each URL. Loads in this mode still call `fetch`.
7
+ - Share `@iqbspecs/metadata-profile` with consuming projects through a peer
8
+ dependency supporting `^0.11.1` and `^0.12.0`.
9
+ - Generate the generic `dist/index.d.ts` with a platform-independent Node.js
10
+ build step and include the changelog in the npm package.
11
+ - Cover cache behaviour, HTTP and JSON errors, timeouts, redirects and
12
+ fallbacks with automated tests. CI checks Node.js 22.18.0 and a Node.js 22.x
13
+ release, runs dependency audits and uses the updated lint and test tooling.
14
+ - Document releases from `main` and verify the remote tag before publishing to npm.
15
+
16
+ ## 0.2.1 (2026-06-29)
17
+
18
+ - Add the generic `dist/index.d.ts` declaration.
19
+ - [Source commit recorded by npm](https://github.com/iqb-berlin/metadata-resolver/commit/4dbc8357f3c7c6fd312becce1d6cbf825ce3e246).
20
+
21
+ ## 0.2.0 (2026-03-23)
22
+
23
+ - Migrate the resolver to the IQB metadata profile specification.
24
+ - [Source commit recorded by npm](https://github.com/iqb-berlin/metadata-resolver/commit/bccc967ceed78a2fd2a2f3d5a3e08888bd80ba07).
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @iqb/metadata-resolver
2
2
 
3
- Framework-agnostic TypeScript library for loading metadata profiles and vocabularies.
3
+ TypeScript library for loading metadata profiles and vocabularies.
4
4
 
5
5
  ## Installation
6
6
  ```bash
@@ -24,10 +24,110 @@ console.log(data.vocabularies);
24
24
 
25
25
  See [GETTING_STARTED.md](./GETTING_STARTED.md) for detailed usage guide.
26
26
 
27
- ## Version
27
+ ## Versions
28
28
 
29
- **0.1.0** - Testing phase
29
+ The [npm package](https://www.npmjs.com/package/@iqb/metadata-resolver) lists the
30
+ latest published version. The version in [package.json](./package.json) is the
31
+ version prepared on this branch. See the [changelog](./CHANGELOG.md) for release
32
+ notes and the source commits of older npm releases.
33
+
34
+ ## Development
35
+
36
+ ### Setup
37
+
38
+ ```bash
39
+ # Use Node.js 22.18.0 or later in the Node.js 22 LTS line.
40
+ npm ci
41
+ ```
42
+
43
+ ### Quality Checks
44
+
45
+ We use **ESLint** and **Prettier** to ensure code quality.
46
+
47
+ ```bash
48
+ # Run linting
49
+ npm run lint
50
+
51
+ # Run type check
52
+ npm run typecheck
53
+
54
+ # Run tests
55
+ npm run test
56
+
57
+ # Report dependency vulnerabilities
58
+ npm audit --omit=dev
59
+ npm audit
60
+
61
+ # Format code
62
+ npm run format
63
+ ```
64
+
65
+ CI runs both audits. The scoped `minimatch` override for
66
+ `eslint-plugin-sonarjs` follows the [IQB ESLint dependency guidance](https://github.com/iqb-berlin/eslint-config/blob/master/docs/security.md).
67
+ When updating the lint stack, check whether its declared dependency range
68
+ includes the fixed major before removing the override. The advisory is
69
+ [GHSA-g3hv-75wg-m249](https://github.com/advisories/GHSA-g3hv-75wg-m249).
70
+
71
+ ### Build
72
+
73
+ ```bash
74
+ npm run build
75
+ ```
76
+
77
+ ## Release
78
+
79
+ Releases are cut from `main`. Before merging a release PR, update the changelog
80
+ and set the intended version in both npm manifests, for example with
81
+ `npm version patch --no-git-tag-version` when a bump is needed.
82
+
83
+ After CI passes on the merged commit, use a clean checkout of that exact commit
84
+ from `origin/main`. Confirm that the version has yet to be published to npm.
85
+
86
+ ```bash
87
+ (
88
+ set -euo pipefail
89
+
90
+ git fetch origin main
91
+ commit=$(git rev-parse HEAD)
92
+ main_commit=$(git rev-parse FETCH_HEAD)
93
+ working_tree=$(git status --porcelain)
94
+ if [[ "$commit" != "$main_commit" || -n "$working_tree" ]]; then
95
+ echo 'Release requires a clean checkout of origin/main.' >&2
96
+ exit 1
97
+ fi
98
+
99
+ npm ci --engine-strict
100
+ npm run typecheck
101
+ npm run lint
102
+ npm test
103
+ npm run build
104
+ npm pack --dry-run
105
+
106
+ version=$(node -p 'require("./package.json").version')
107
+ tag="v$version"
108
+ tag_ref="refs/tags/$tag"
109
+ if ! git show-ref --verify --quiet "$tag_ref"; then
110
+ git tag -a "$tag" -m "Release $tag" "$commit"
111
+ fi
112
+ test "$(git rev-parse "$tag_ref^{commit}")" = "$commit"
113
+ git push origin "$tag_ref"
114
+
115
+ remote_commit=$(git ls-remote --exit-code --tags origin "$tag_ref^{}" | cut -f1)
116
+ if [[ "$remote_commit" != "$commit" ]]; then
117
+ echo "Remote tag $tag does not point to $commit." >&2
118
+ exit 1
119
+ fi
120
+
121
+ npm run release
122
+ test "$(npm view "@iqb/metadata-resolver@$version" gitHead)" = "$commit"
123
+ )
124
+ ```
125
+
126
+ After the registry commit check passes, create a GitHub release from the tag
127
+ using the corresponding changelog entry. For a prerelease, use an explicit
128
+ prerelease version and replace the publish command in the block with
129
+ `npm run release -- --tag beta`.
30
130
 
31
131
  ## License
32
132
 
33
- MIT © IQB Berlin
133
+ MIT © IQB Berlin
package/dist/index.cjs CHANGED
@@ -1,3 +1,4 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1
2
 
2
3
  //#region src/metadata-resolver.ts
3
4
  var MetadataResolver = class {
@@ -13,21 +14,29 @@ var MetadataResolver = class {
13
14
  this.preferredLanguage = options?.preferredLanguage || "de";
14
15
  this.requestTimeout = options?.requestTimeout || 1e4;
15
16
  }
17
+ setCorsProxy(proxy) {
18
+ this.corsProxy = proxy;
19
+ }
16
20
  /**
17
21
  * Load a profile from a URL
18
22
  */
19
23
  async loadProfile(url) {
20
24
  const cacheKey = `profile:${url}`;
21
25
  if (this.useCache && this.cache.has(cacheKey)) return this.cache.get(cacheKey);
26
+ const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(url)}` : url;
27
+ let response;
28
+ try {
29
+ response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
30
+ } catch (error) {
31
+ throw new Error(`Error loading profile from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
32
+ }
33
+ if (!response.ok) throw new Error(`Error loading profile from ${url}: ${response.status} ${response.statusText}`);
22
34
  try {
23
- const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(url)}` : url;
24
- const response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
25
- if (!response.ok) throw new Error(`Failed to load profile: ${response.status} ${response.statusText}`);
26
35
  const profile = await response.json();
27
36
  if (this.useCache) this.cache.set(cacheKey, profile);
28
37
  return profile;
29
38
  } catch (error) {
30
- throw new Error(`Error loading profile from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
39
+ throw new Error(`Error parsing profile from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
31
40
  }
32
41
  }
33
42
  /**
@@ -36,15 +45,20 @@ var MetadataResolver = class {
36
45
  async loadMetadata(url) {
37
46
  const cacheKey = `metadata:${url}`;
38
47
  if (this.useCache && this.cache.has(cacheKey)) return this.cache.get(cacheKey);
48
+ const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(url)}` : url;
49
+ let response;
50
+ try {
51
+ response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
52
+ } catch (error) {
53
+ throw new Error(`Error loading metadata from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
54
+ }
55
+ if (!response.ok) throw new Error(`Error loading metadata from ${url}: ${response.status} ${response.statusText}`);
39
56
  try {
40
- const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(url)}` : url;
41
- const response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
42
- if (!response.ok) throw new Error(`Failed to load metadata: ${response.status} ${response.statusText}`);
43
57
  const metadata = await response.json();
44
58
  if (this.useCache) this.cache.set(cacheKey, metadata);
45
59
  return metadata;
46
60
  } catch (error) {
47
- throw new Error(`Error loading metadata from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
61
+ throw new Error(`Error parsing metadata from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
48
62
  }
49
63
  }
50
64
  /**
@@ -64,7 +78,7 @@ var MetadataResolver = class {
64
78
  }
65
79
  /**
66
80
  * Load a single vocabulary from URL
67
- * Uses vocabulariesStore as the cache
81
+ * Records the latest successful result and reuses it when caching is enabled
68
82
  */
69
83
  async loadVocabulary(url) {
70
84
  if (this.useCache && this.vocabulariesStore.has(url)) return this.vocabulariesStore.get(url);
@@ -73,18 +87,60 @@ var MetadataResolver = class {
73
87
  const jsonLdUrl = await this.resolveJsonLdUrl(url);
74
88
  if (jsonLdUrl !== url) console.log(` Resolved to: ${jsonLdUrl}`);
75
89
  const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(jsonLdUrl)}` : jsonLdUrl;
76
- if (this.corsProxy) console.log(` Using CORS proxy`);
77
- const response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
78
- if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
79
- const data = await response.json();
80
- if (!data.hasTopConcept || !Array.isArray(data.hasTopConcept)) throw new Error("Invalid structure: missing hasTopConcept");
90
+ if (this.corsProxy) console.log(" Using CORS proxy");
91
+ let response;
92
+ try {
93
+ response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
94
+ } catch (error) {
95
+ const errorMsg = error instanceof Error ? error.message : String(error);
96
+ console.error(` Failed to load vocabulary: ${errorMsg}`);
97
+ return {
98
+ url,
99
+ data: { hasTopConcept: [] },
100
+ dictionary: {},
101
+ error: errorMsg
102
+ };
103
+ }
104
+ if (!response.ok) {
105
+ const errorMsg = `HTTP ${response.status}: ${response.statusText}`;
106
+ console.error(` Failed to load vocabulary: ${errorMsg}`);
107
+ return {
108
+ url,
109
+ data: { hasTopConcept: [] },
110
+ dictionary: {},
111
+ error: errorMsg
112
+ };
113
+ }
114
+ let data;
115
+ try {
116
+ data = await response.json();
117
+ } catch (error) {
118
+ const errorMsg = error instanceof Error ? error.message : String(error);
119
+ console.error(` Failed to parse vocabulary JSON: ${errorMsg}`);
120
+ return {
121
+ url,
122
+ data: { hasTopConcept: [] },
123
+ dictionary: {},
124
+ error: errorMsg
125
+ };
126
+ }
127
+ if (!data.hasTopConcept || !Array.isArray(data.hasTopConcept)) {
128
+ const errorMsg = "Invalid structure: missing hasTopConcept";
129
+ console.error(` Failed to load vocabulary: ${errorMsg}`);
130
+ return {
131
+ url,
132
+ data: { hasTopConcept: [] },
133
+ dictionary: {},
134
+ error: errorMsg
135
+ };
136
+ }
81
137
  const dictionary = this.buildVocabularyDictionary(data);
82
138
  const resolved = {
83
139
  url,
84
140
  data,
85
141
  dictionary
86
142
  };
87
- if (this.useCache) this.vocabulariesStore.set(url, resolved);
143
+ this.vocabulariesStore.set(url, resolved);
88
144
  console.log(` Loaded: ${data.hasTopConcept.length} concepts, ${Object.keys(dictionary).length} entries`);
89
145
  return resolved;
90
146
  } catch (error) {
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { LanguageCodedText, LanguageCodedText as LanguageCodedText$1, MDProfile, MDProfile as MDProfile$1 } from "@iqbspecs/metadata-profile";
1
+ import { LanguageCodedText, MDProfile, MDProfile as MDProfile$1 } from "@iqbspecs/metadata-profile";
2
2
 
3
3
  //#region src/types.d.ts
4
4
  interface LoaderOptions {
@@ -29,7 +29,7 @@ interface VocabularyEntry {
29
29
  name: string;
30
30
  notation: string[];
31
31
  description?: string;
32
- text: LanguageCodedText$1[];
32
+ text: LanguageCodedText[];
33
33
  }
34
34
  interface ResolvedVocabulary {
35
35
  url: string;
@@ -43,19 +43,19 @@ interface ProfileWithVocabularies {
43
43
  }
44
44
  interface MetadataWithProfile {
45
45
  profile: MDProfile$1;
46
- metadata: any;
46
+ metadata: unknown;
47
47
  vocabularies: ResolvedVocabulary[];
48
48
  }
49
49
  /**
50
50
  * @deprecated Use LanguageCodedText instead.
51
51
  */
52
- type TextWithLanguage = LanguageCodedText$1;
52
+ type TextWithLanguage = LanguageCodedText;
53
53
  /**
54
54
  * @deprecated Will be removed when values spec is adopted.
55
55
  */
56
56
  interface TextWithLanguageAndId {
57
57
  id: string;
58
- text: LanguageCodedText$1[];
58
+ text: LanguageCodedText[];
59
59
  }
60
60
  //#endregion
61
61
  //#region src/metadata-resolver.d.ts
@@ -67,6 +67,7 @@ declare class MetadataResolver {
67
67
  private preferredLanguage;
68
68
  private requestTimeout;
69
69
  constructor(options?: LoaderOptions);
70
+ setCorsProxy(proxy: string | undefined): void;
70
71
  /**
71
72
  * Load a profile from a URL
72
73
  */
@@ -74,14 +75,14 @@ declare class MetadataResolver {
74
75
  /**
75
76
  * Load metadata from a URL
76
77
  */
77
- loadMetadata(url: string): Promise<any>;
78
+ loadMetadata(url: string): Promise<unknown>;
78
79
  /**
79
80
  * Extract vocabulary URLs from a profile
80
81
  */
81
82
  extractVocabularyUrls(profile: MDProfile): string[];
82
83
  /**
83
84
  * Load a single vocabulary from URL
84
- * Uses vocabulariesStore as the cache
85
+ * Records the latest successful result and reuses it when caching is enabled
85
86
  */
86
87
  loadVocabulary(url: string): Promise<ResolvedVocabulary>;
87
88
  /**
@@ -107,7 +108,10 @@ declare class MetadataResolver {
107
108
  /**
108
109
  * Extract text from a label (string or multilingual array)
109
110
  */
110
- static extractLabelText(label: string | LanguageCodedText[], preferredLanguage?: string): string;
111
+ static extractLabelText(label: string | Array<{
112
+ lang: string;
113
+ value: string;
114
+ }>, preferredLanguage?: string): string;
111
115
  /**
112
116
  * Clear all caches (profiles, metadata, and vocabularies)
113
117
  */
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { LanguageCodedText, LanguageCodedText as LanguageCodedText$1, MDProfile, MDProfile as MDProfile$1 } from "@iqbspecs/metadata-profile";
1
+ import { LanguageCodedText, MDProfile, MDProfile as MDProfile$1 } from "@iqbspecs/metadata-profile";
2
2
 
3
3
  //#region src/types.d.ts
4
4
  interface LoaderOptions {
@@ -29,7 +29,7 @@ interface VocabularyEntry {
29
29
  name: string;
30
30
  notation: string[];
31
31
  description?: string;
32
- text: LanguageCodedText$1[];
32
+ text: LanguageCodedText[];
33
33
  }
34
34
  interface ResolvedVocabulary {
35
35
  url: string;
@@ -43,19 +43,19 @@ interface ProfileWithVocabularies {
43
43
  }
44
44
  interface MetadataWithProfile {
45
45
  profile: MDProfile$1;
46
- metadata: any;
46
+ metadata: unknown;
47
47
  vocabularies: ResolvedVocabulary[];
48
48
  }
49
49
  /**
50
50
  * @deprecated Use LanguageCodedText instead.
51
51
  */
52
- type TextWithLanguage = LanguageCodedText$1;
52
+ type TextWithLanguage = LanguageCodedText;
53
53
  /**
54
54
  * @deprecated Will be removed when values spec is adopted.
55
55
  */
56
56
  interface TextWithLanguageAndId {
57
57
  id: string;
58
- text: LanguageCodedText$1[];
58
+ text: LanguageCodedText[];
59
59
  }
60
60
  //#endregion
61
61
  //#region src/metadata-resolver.d.ts
@@ -67,6 +67,7 @@ declare class MetadataResolver {
67
67
  private preferredLanguage;
68
68
  private requestTimeout;
69
69
  constructor(options?: LoaderOptions);
70
+ setCorsProxy(proxy: string | undefined): void;
70
71
  /**
71
72
  * Load a profile from a URL
72
73
  */
@@ -74,14 +75,14 @@ declare class MetadataResolver {
74
75
  /**
75
76
  * Load metadata from a URL
76
77
  */
77
- loadMetadata(url: string): Promise<any>;
78
+ loadMetadata(url: string): Promise<unknown>;
78
79
  /**
79
80
  * Extract vocabulary URLs from a profile
80
81
  */
81
82
  extractVocabularyUrls(profile: MDProfile): string[];
82
83
  /**
83
84
  * Load a single vocabulary from URL
84
- * Uses vocabulariesStore as the cache
85
+ * Records the latest successful result and reuses it when caching is enabled
85
86
  */
86
87
  loadVocabulary(url: string): Promise<ResolvedVocabulary>;
87
88
  /**
@@ -107,7 +108,10 @@ declare class MetadataResolver {
107
108
  /**
108
109
  * Extract text from a label (string or multilingual array)
109
110
  */
110
- static extractLabelText(label: string | LanguageCodedText[], preferredLanguage?: string): string;
111
+ static extractLabelText(label: string | Array<{
112
+ lang: string;
113
+ value: string;
114
+ }>, preferredLanguage?: string): string;
111
115
  /**
112
116
  * Clear all caches (profiles, metadata, and vocabularies)
113
117
  */
@@ -0,0 +1,133 @@
1
+ import { LanguageCodedText, MDProfile, MDProfile as MDProfile$1 } from "@iqbspecs/metadata-profile";
2
+
3
+ //#region src/types.d.ts
4
+ interface LoaderOptions {
5
+ corsProxy?: string;
6
+ cache?: boolean;
7
+ preferredLanguage?: string;
8
+ requestTimeout?: number;
9
+ }
10
+ interface VocabConcept {
11
+ id: string;
12
+ notation?: string[];
13
+ prefLabel?: {
14
+ de?: string;
15
+ en?: string;
16
+ [key: string]: string | undefined;
17
+ };
18
+ description?: string;
19
+ narrower?: VocabConcept[];
20
+ }
21
+ interface VocabularyData {
22
+ id?: string;
23
+ type?: string;
24
+ title?: Record<string, string>;
25
+ hasTopConcept?: VocabConcept[];
26
+ }
27
+ interface VocabularyEntry {
28
+ id: string;
29
+ name: string;
30
+ notation: string[];
31
+ description?: string;
32
+ text: LanguageCodedText[];
33
+ }
34
+ interface ResolvedVocabulary {
35
+ url: string;
36
+ data: VocabularyData;
37
+ dictionary: Record<string, VocabularyEntry>;
38
+ error?: string;
39
+ }
40
+ interface ProfileWithVocabularies {
41
+ profile: MDProfile$1;
42
+ vocabularies: ResolvedVocabulary[];
43
+ }
44
+ interface MetadataWithProfile {
45
+ profile: MDProfile$1;
46
+ metadata: unknown;
47
+ vocabularies: ResolvedVocabulary[];
48
+ }
49
+ /**
50
+ * @deprecated Use LanguageCodedText instead.
51
+ */
52
+ type TextWithLanguage = LanguageCodedText;
53
+ /**
54
+ * @deprecated Will be removed when values spec is adopted.
55
+ */
56
+ interface TextWithLanguageAndId {
57
+ id: string;
58
+ text: LanguageCodedText[];
59
+ }
60
+ //#endregion
61
+ //#region src/metadata-resolver.d.ts
62
+ declare class MetadataResolver {
63
+ private corsProxy;
64
+ private cache;
65
+ private vocabulariesStore;
66
+ private useCache;
67
+ private preferredLanguage;
68
+ private requestTimeout;
69
+ constructor(options?: LoaderOptions);
70
+ setCorsProxy(proxy: string | undefined): void;
71
+ /**
72
+ * Load a profile from a URL
73
+ */
74
+ loadProfile(url: string): Promise<MDProfile>;
75
+ /**
76
+ * Load metadata from a URL
77
+ */
78
+ loadMetadata(url: string): Promise<unknown>;
79
+ /**
80
+ * Extract vocabulary URLs from a profile
81
+ */
82
+ extractVocabularyUrls(profile: MDProfile): string[];
83
+ /**
84
+ * Load a single vocabulary from URL
85
+ * Records the latest successful result and reuses it when caching is enabled
86
+ */
87
+ loadVocabulary(url: string): Promise<ResolvedVocabulary>;
88
+ /**
89
+ * Load all vocabularies referenced in a profile
90
+ */
91
+ loadVocabularies(profile: MDProfile): Promise<ResolvedVocabulary[]>;
92
+ /**
93
+ * Build a dictionary from vocabulary data
94
+ */
95
+ private buildVocabularyDictionary;
96
+ /**
97
+ * Load a profile and all its vocabularies
98
+ */
99
+ loadProfileWithVocabularies(profileUrl: string): Promise<ProfileWithVocabularies>;
100
+ /**
101
+ * Resolve a URL to its JSON-LD representation
102
+ */
103
+ private resolveJsonLdUrl;
104
+ /**
105
+ * Load both profile with vocabularies and metadata
106
+ */
107
+ loadAll(profileUrl: string, metadataUrl: string): Promise<MetadataWithProfile>;
108
+ /**
109
+ * Extract text from a label (string or multilingual array)
110
+ */
111
+ static extractLabelText(label: string | Array<{
112
+ lang: string;
113
+ value: string;
114
+ }>, preferredLanguage?: string): string;
115
+ /**
116
+ * Clear all caches (profiles, metadata, and vocabularies)
117
+ */
118
+ clearCache(): void;
119
+ /**
120
+ * Get all loaded vocabularies
121
+ */
122
+ getVocabularies(): ResolvedVocabulary[];
123
+ /**
124
+ * Get a specific vocabulary by URL
125
+ */
126
+ getVocabulary(url: string): ResolvedVocabulary | undefined;
127
+ /**
128
+ * Get combined dictionary of all vocabulary entries
129
+ */
130
+ getVocabularyDictionary(): Record<string, VocabularyEntry>;
131
+ }
132
+ //#endregion
133
+ export { type LoaderOptions, MetadataResolver, type MetadataWithProfile, type ProfileWithVocabularies, type ResolvedVocabulary, type TextWithLanguage, type TextWithLanguageAndId, type VocabConcept, type VocabularyData, type VocabularyEntry };
package/dist/index.mjs CHANGED
@@ -12,21 +12,29 @@ var MetadataResolver = class {
12
12
  this.preferredLanguage = options?.preferredLanguage || "de";
13
13
  this.requestTimeout = options?.requestTimeout || 1e4;
14
14
  }
15
+ setCorsProxy(proxy) {
16
+ this.corsProxy = proxy;
17
+ }
15
18
  /**
16
19
  * Load a profile from a URL
17
20
  */
18
21
  async loadProfile(url) {
19
22
  const cacheKey = `profile:${url}`;
20
23
  if (this.useCache && this.cache.has(cacheKey)) return this.cache.get(cacheKey);
24
+ const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(url)}` : url;
25
+ let response;
26
+ try {
27
+ response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
28
+ } catch (error) {
29
+ throw new Error(`Error loading profile from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
30
+ }
31
+ if (!response.ok) throw new Error(`Error loading profile from ${url}: ${response.status} ${response.statusText}`);
21
32
  try {
22
- const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(url)}` : url;
23
- const response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
24
- if (!response.ok) throw new Error(`Failed to load profile: ${response.status} ${response.statusText}`);
25
33
  const profile = await response.json();
26
34
  if (this.useCache) this.cache.set(cacheKey, profile);
27
35
  return profile;
28
36
  } catch (error) {
29
- throw new Error(`Error loading profile from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
37
+ throw new Error(`Error parsing profile from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
30
38
  }
31
39
  }
32
40
  /**
@@ -35,15 +43,20 @@ var MetadataResolver = class {
35
43
  async loadMetadata(url) {
36
44
  const cacheKey = `metadata:${url}`;
37
45
  if (this.useCache && this.cache.has(cacheKey)) return this.cache.get(cacheKey);
46
+ const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(url)}` : url;
47
+ let response;
48
+ try {
49
+ response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
50
+ } catch (error) {
51
+ throw new Error(`Error loading metadata from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
52
+ }
53
+ if (!response.ok) throw new Error(`Error loading metadata from ${url}: ${response.status} ${response.statusText}`);
38
54
  try {
39
- const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(url)}` : url;
40
- const response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
41
- if (!response.ok) throw new Error(`Failed to load metadata: ${response.status} ${response.statusText}`);
42
55
  const metadata = await response.json();
43
56
  if (this.useCache) this.cache.set(cacheKey, metadata);
44
57
  return metadata;
45
58
  } catch (error) {
46
- throw new Error(`Error loading metadata from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
59
+ throw new Error(`Error parsing metadata from ${url}: ${error instanceof Error ? error.message : "Unknown error"}`);
47
60
  }
48
61
  }
49
62
  /**
@@ -63,7 +76,7 @@ var MetadataResolver = class {
63
76
  }
64
77
  /**
65
78
  * Load a single vocabulary from URL
66
- * Uses vocabulariesStore as the cache
79
+ * Records the latest successful result and reuses it when caching is enabled
67
80
  */
68
81
  async loadVocabulary(url) {
69
82
  if (this.useCache && this.vocabulariesStore.has(url)) return this.vocabulariesStore.get(url);
@@ -72,18 +85,60 @@ var MetadataResolver = class {
72
85
  const jsonLdUrl = await this.resolveJsonLdUrl(url);
73
86
  if (jsonLdUrl !== url) console.log(` Resolved to: ${jsonLdUrl}`);
74
87
  const fetchUrl = this.corsProxy ? `${this.corsProxy}${encodeURIComponent(jsonLdUrl)}` : jsonLdUrl;
75
- if (this.corsProxy) console.log(` Using CORS proxy`);
76
- const response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
77
- if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
78
- const data = await response.json();
79
- if (!data.hasTopConcept || !Array.isArray(data.hasTopConcept)) throw new Error("Invalid structure: missing hasTopConcept");
88
+ if (this.corsProxy) console.log(" Using CORS proxy");
89
+ let response;
90
+ try {
91
+ response = await fetch(fetchUrl, { signal: AbortSignal.timeout(this.requestTimeout) });
92
+ } catch (error) {
93
+ const errorMsg = error instanceof Error ? error.message : String(error);
94
+ console.error(` Failed to load vocabulary: ${errorMsg}`);
95
+ return {
96
+ url,
97
+ data: { hasTopConcept: [] },
98
+ dictionary: {},
99
+ error: errorMsg
100
+ };
101
+ }
102
+ if (!response.ok) {
103
+ const errorMsg = `HTTP ${response.status}: ${response.statusText}`;
104
+ console.error(` Failed to load vocabulary: ${errorMsg}`);
105
+ return {
106
+ url,
107
+ data: { hasTopConcept: [] },
108
+ dictionary: {},
109
+ error: errorMsg
110
+ };
111
+ }
112
+ let data;
113
+ try {
114
+ data = await response.json();
115
+ } catch (error) {
116
+ const errorMsg = error instanceof Error ? error.message : String(error);
117
+ console.error(` Failed to parse vocabulary JSON: ${errorMsg}`);
118
+ return {
119
+ url,
120
+ data: { hasTopConcept: [] },
121
+ dictionary: {},
122
+ error: errorMsg
123
+ };
124
+ }
125
+ if (!data.hasTopConcept || !Array.isArray(data.hasTopConcept)) {
126
+ const errorMsg = "Invalid structure: missing hasTopConcept";
127
+ console.error(` Failed to load vocabulary: ${errorMsg}`);
128
+ return {
129
+ url,
130
+ data: { hasTopConcept: [] },
131
+ dictionary: {},
132
+ error: errorMsg
133
+ };
134
+ }
80
135
  const dictionary = this.buildVocabularyDictionary(data);
81
136
  const resolved = {
82
137
  url,
83
138
  data,
84
139
  dictionary
85
140
  };
86
- if (this.useCache) this.vocabulariesStore.set(url, resolved);
141
+ this.vocabulariesStore.set(url, resolved);
87
142
  console.log(` Loaded: ${data.hasTopConcept.length} concepts, ${Object.keys(dictionary).length} entries`);
88
143
  return resolved;
89
144
  } catch (error) {
package/package.json CHANGED
@@ -1,16 +1,23 @@
1
1
  {
2
2
  "name": "@iqb/metadata-resolver",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Framework-agnostic metadata and vocabulary resolver for IQB metadata profiles",
5
- "main": "dist/index.js",
5
+ "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
7
- "types": "dist/index.d.ts",
7
+ "types": "dist/index.d.cts",
8
8
  "files": [
9
- "dist"
9
+ "dist",
10
+ "CHANGELOG.md"
10
11
  ],
11
12
  "scripts": {
12
- "build": "tsdown src/index.ts --format cjs,esm --dts --clean",
13
- "dev": "tsdown src/index.ts --format cjs,esm --dts --watch"
13
+ "build": "tsdown src/index.ts --format cjs,esm --dts --clean && node -e \"require('node:fs').copyFileSync('dist/index.d.mts', 'dist/index.d.ts')\"",
14
+ "dev": "tsdown src/index.ts --format cjs,esm --dts --watch",
15
+ "test": "vitest run",
16
+ "lint": "eslint src",
17
+ "format": "prettier --write \"src/**/*.{ts,json}\"",
18
+ "typecheck": "tsc --noEmit",
19
+ "prepublishOnly": "npm run typecheck && npm run lint && npm run test && npm run build",
20
+ "release": "npm publish"
14
21
  },
15
22
  "keywords": [
16
23
  "metadata",
@@ -20,21 +27,38 @@
20
27
  ],
21
28
  "author": "IQB",
22
29
  "license": "MIT",
23
- "dependencies": {
24
- "@iqbspecs/metadata-profile": "^0.11.1"
25
- },
26
30
  "devDependencies": {
27
- "tsdown": "^0.20.0-beta.2",
28
- "typescript": "^5.3.0"
31
+ "@eslint/js": "^10.0.1",
32
+ "@iqb/eslint-config": "^3.0.0",
33
+ "@iqbspecs/metadata-profile": "^0.12.0",
34
+ "@types/node": "^22.0.0",
35
+ "eslint": "^10.15.0",
36
+ "prettier": "^3.8.1",
37
+ "tsdown": "^0.20.1",
38
+ "typescript": "~5.9.3",
39
+ "vitest": "^4.1.12"
29
40
  },
30
41
  "exports": {
31
42
  ".": {
32
- "types": "./dist/index.d.ts",
33
- "import": "./dist/index.mjs",
34
- "require": "./dist/index.js"
43
+ "import": {
44
+ "types": "./dist/index.d.mts",
45
+ "default": "./dist/index.mjs"
46
+ },
47
+ "require": {
48
+ "types": "./dist/index.d.cts",
49
+ "default": "./dist/index.cjs"
50
+ }
35
51
  }
36
52
  },
37
53
  "publishConfig": {
38
54
  "access": "public"
55
+ },
56
+ "overrides": {
57
+ "eslint-plugin-sonarjs": {
58
+ "minimatch": "^11.0.4"
59
+ }
60
+ },
61
+ "peerDependencies": {
62
+ "@iqbspecs/metadata-profile": "^0.11.1 || ^0.12.0"
39
63
  }
40
64
  }