@pie-qti/ims-cp-core 0.1.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.
@@ -0,0 +1,410 @@
1
+ /**
2
+ * Localized Resource Utilities for IMS Content Packages
3
+ *
4
+ * Provides generic locale-aware utilities for QTI content packages. Resources can optionally
5
+ * use locale-suffixed identifiers (e.g., "item.en-US", "item.es-ES") and IMS LOM language
6
+ * metadata for multilingual support.
7
+ *
8
+ * **Works with both single-locale and multilingual packages:**
9
+ * - Non-localized packages: Resources without locale suffixes are treated as the default locale
10
+ * - Multilingual packages: Resources with locale suffixes enable per-locale selection
11
+ *
12
+ * **Generic fallback system:**
13
+ * When requesting a locale variant, the system tries:
14
+ * 1. Exact match (es-ES)
15
+ * 2. Language-only match (es)
16
+ * 3. Default locale (typically en-US)
17
+ * 4. First available variant
18
+ *
19
+ * This means requesting "es-ES" from a non-localized English package will gracefully
20
+ * fall back to the English content - no special handling needed.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * // Works with any manifest (single or multilingual)
25
+ * const manifest = parseManifest(xml);
26
+ * const localized = buildLocalizedManifest(manifest, 'en-US');
27
+ *
28
+ * // Get item with automatic fallback
29
+ * const item = getLocalizedItem(localized, 'simple-choice', 'es-ES');
30
+ * // → Returns Spanish variant if available, otherwise falls back to English
31
+ * ```
32
+ */
33
+ /**
34
+ * Locale identifier pattern - supports dot, dash, or underscore separators
35
+ * Matches patterns like:
36
+ * - "item.en-US"
37
+ * - "item-en-US"
38
+ * - "item_en_US"
39
+ * - "item.en"
40
+ */
41
+ const LOCALE_PATTERN = /[._-]([a-z]{2}(?:[_-][A-Z]{2})?)$/;
42
+ /**
43
+ * Extract locale code from a resource identifier.
44
+ *
45
+ * Supports multiple separator styles:
46
+ * - Dot: "item.en-US"
47
+ * - Dash: "item-en-US"
48
+ * - Underscore: "item_en_US"
49
+ *
50
+ * @param identifier Resource identifier (e.g., "simple-choice.en-US")
51
+ * @returns Locale code if found, undefined otherwise
52
+ *
53
+ * @example
54
+ * extractLocaleFromIdentifier("simple-choice.en-US") // "en-US"
55
+ * extractLocaleFromIdentifier("simple-choice-es-ES") // "es-ES"
56
+ * extractLocaleFromIdentifier("simple-choice_fr_FR") // "fr-FR"
57
+ * extractLocaleFromIdentifier("simple-choice") // undefined
58
+ */
59
+ export function extractLocaleFromIdentifier(identifier) {
60
+ const match = identifier.match(LOCALE_PATTERN);
61
+ if (!match)
62
+ return undefined;
63
+ // Normalize underscore separators to hyphens (en_US -> en-US)
64
+ return match[1].replace('_', '-');
65
+ }
66
+ /**
67
+ * Extract base identifier by removing locale suffix.
68
+ *
69
+ * @param identifier Resource identifier
70
+ * @returns Base identifier without locale suffix
71
+ *
72
+ * @example
73
+ * extractBaseIdentifier("simple-choice.en-US") // "simple-choice"
74
+ * extractBaseIdentifier("simple-choice") // "simple-choice"
75
+ */
76
+ export function extractBaseIdentifier(identifier) {
77
+ const match = identifier.match(LOCALE_PATTERN);
78
+ if (!match)
79
+ return identifier;
80
+ return identifier.slice(0, match.index);
81
+ }
82
+ /**
83
+ * Extract language code from IMS LOM metadata.
84
+ *
85
+ * Looks for language information in the metadata object, typically
86
+ * from <imsmd:language> elements in the manifest.
87
+ *
88
+ * @param metadata Resource metadata object
89
+ * @returns Locale code if found, undefined otherwise
90
+ *
91
+ * @example
92
+ * extractLanguageFromMetadata({ language: "en-US" }) // "en-US"
93
+ * extractLanguageFromMetadata({ title: "Test" }) // undefined
94
+ */
95
+ export function extractLanguageFromMetadata(metadata) {
96
+ return metadata?.language;
97
+ }
98
+ /**
99
+ * Determine the locale for a resource using multiple detection methods.
100
+ *
101
+ * This is the core function that enables the generic locale system to work with both
102
+ * localized and non-localized packages. Resources without locale information are
103
+ * simply assigned the default locale - no special handling needed.
104
+ *
105
+ * Priority order:
106
+ * 1. Identifier suffix (e.g., "item.en-US") - most explicit
107
+ * 2. IMS LOM language metadata - explicit metadata
108
+ * 3. Default locale - implicit for non-localized content
109
+ *
110
+ * @param resource Manifest resource
111
+ * @param defaultLocale Default locale to use as fallback
112
+ * @returns Detected locale code
113
+ *
114
+ * @example
115
+ * determineResourceLocale({ identifier: "item.es-ES", ... }, "en-US") // "es-ES"
116
+ * determineResourceLocale({ identifier: "item", metadata: { language: "fr" } }, "en-US") // "fr"
117
+ * determineResourceLocale({ identifier: "item" }, "en-US") // "en-US" (non-localized → default)
118
+ */
119
+ export function determineResourceLocale(resource, defaultLocale) {
120
+ // Try identifier first (most explicit)
121
+ const fromId = extractLocaleFromIdentifier(resource.identifier);
122
+ if (fromId)
123
+ return fromId;
124
+ // Try metadata
125
+ const fromMetadata = extractLanguageFromMetadata(resource.metadata);
126
+ if (fromMetadata)
127
+ return fromMetadata;
128
+ // Fall back to default
129
+ return defaultLocale;
130
+ }
131
+ /**
132
+ * Generate locale fallback chain for resource selection.
133
+ *
134
+ * Creates a prioritized list of locales to try when selecting a resource variant.
135
+ *
136
+ * Fallback logic:
137
+ * 1. Exact match (es-ES)
138
+ * 2. Language-only (es)
139
+ * 3. Default locale (en-US)
140
+ * 4. Default language-only (en)
141
+ *
142
+ * @param requestedLocale User's requested locale
143
+ * @param defaultLocale Default/fallback locale
144
+ * @returns Array of locale codes in priority order
145
+ *
146
+ * @example
147
+ * getLocaleFallbackChain("es-MX", "en-US")
148
+ * // ["es-MX", "es", "en-US", "en"]
149
+ *
150
+ * getLocaleFallbackChain("fr-CA", "en-US")
151
+ * // ["fr-CA", "fr", "en-US", "en"]
152
+ */
153
+ export function getLocaleFallbackChain(requestedLocale, defaultLocale) {
154
+ const chain = [];
155
+ // 1. Exact requested locale
156
+ chain.push(requestedLocale);
157
+ // 2. Language-only from requested locale (es-ES -> es)
158
+ const requestedLang = requestedLocale.split(/[-_]/)[0];
159
+ if (requestedLang !== requestedLocale) {
160
+ chain.push(requestedLang);
161
+ }
162
+ // 3. Default locale (if different from requested)
163
+ if (defaultLocale !== requestedLocale) {
164
+ chain.push(defaultLocale);
165
+ }
166
+ // 4. Language-only from default locale (en-US -> en)
167
+ const defaultLang = defaultLocale.split(/[-_]/)[0];
168
+ if (defaultLang !== defaultLocale && defaultLang !== requestedLang) {
169
+ chain.push(defaultLang);
170
+ }
171
+ return chain;
172
+ }
173
+ /**
174
+ * Select the best matching resource variant from a group.
175
+ *
176
+ * Uses fallback chain to find the most appropriate variant:
177
+ * 1. Try exact locale match
178
+ * 2. Try language-only match
179
+ * 3. Try default locale
180
+ * 4. Use first available variant
181
+ *
182
+ * @param group Resource group with multiple locale variants
183
+ * @param requestedLocale User's requested locale
184
+ * @param defaultLocale Default/fallback locale
185
+ * @returns Best matching resource, or undefined if group is empty
186
+ *
187
+ * @example
188
+ * const group = {
189
+ * baseId: "simple-choice",
190
+ * availableLocales: ["en-US", "es-ES"],
191
+ * variants: new Map([
192
+ * ["en-US", enResource],
193
+ * ["es-ES", esResource]
194
+ * ]),
195
+ * defaultLocale: "en-US"
196
+ * };
197
+ *
198
+ * selectLocalizedResource(group, "es-MX", "en-US") // esResource (fallback es-ES -> es)
199
+ * selectLocalizedResource(group, "fr-FR", "en-US") // enResource (fallback to default)
200
+ */
201
+ export function selectLocalizedResource(group, requestedLocale, defaultLocale) {
202
+ if (group.variants.size === 0)
203
+ return undefined;
204
+ const fallbackChain = getLocaleFallbackChain(requestedLocale, defaultLocale);
205
+ // Try each locale in fallback chain
206
+ for (const locale of fallbackChain) {
207
+ const resource = group.variants.get(locale);
208
+ if (resource)
209
+ return resource;
210
+ }
211
+ // Last resort: return first available variant
212
+ return group.variants.values().next().value;
213
+ }
214
+ /**
215
+ * Group resources by base identifier and locale.
216
+ *
217
+ * Takes a flat array of resources and organizes them into groups where
218
+ * each group contains all locale variants of the same base content.
219
+ *
220
+ * @param resources Array of manifest resources
221
+ * @param defaultLocale Default locale to assign to resources without locale info
222
+ * @returns Map of base identifier to resource group
223
+ *
224
+ * @example
225
+ * const resources = [
226
+ * { identifier: "item.en-US", ... },
227
+ * { identifier: "item.es-ES", ... },
228
+ * { identifier: "other.en-US", ... }
229
+ * ];
230
+ *
231
+ * const groups = groupResourcesByLocale(resources, "en-US");
232
+ * // Map {
233
+ * // "item" => { baseId: "item", availableLocales: ["en-US", "es-ES"], ... },
234
+ * // "other" => { baseId: "other", availableLocales: ["en-US"], ... }
235
+ * // }
236
+ */
237
+ export function groupResourcesByLocale(resources, defaultLocale) {
238
+ const groups = new Map();
239
+ for (const resource of resources) {
240
+ const locale = determineResourceLocale(resource, defaultLocale);
241
+ const baseId = extractBaseIdentifier(resource.identifier);
242
+ const localizedResource = {
243
+ ...resource,
244
+ baseId,
245
+ locale,
246
+ };
247
+ let group = groups.get(baseId);
248
+ if (!group) {
249
+ group = {
250
+ baseId,
251
+ availableLocales: [],
252
+ variants: new Map(),
253
+ defaultLocale,
254
+ };
255
+ groups.set(baseId, group);
256
+ }
257
+ group.variants.set(locale, localizedResource);
258
+ if (!group.availableLocales.includes(locale)) {
259
+ group.availableLocales.push(locale);
260
+ }
261
+ }
262
+ return groups;
263
+ }
264
+ /**
265
+ * Build a localized manifest structure from a parsed manifest.
266
+ *
267
+ * Organizes all resources (items, passages, tests) by base identifier and locale,
268
+ * enabling easy lookup and locale-aware resource selection.
269
+ *
270
+ * @param manifest Parsed manifest
271
+ * @param defaultLocale Default locale for resources without locale info
272
+ * @returns Localized manifest with grouped resources
273
+ *
274
+ * @example
275
+ * const manifest = parseManifest(manifestXml);
276
+ * const localized = buildLocalizedManifest(manifest, "en-US");
277
+ *
278
+ * console.log(localized.availableLocales); // Set { "en-US", "es-ES", "fr-FR" }
279
+ * console.log(localized.itemGroups.get("simple-choice")); // Group with all locale variants
280
+ */
281
+ export function buildLocalizedManifest(manifest, defaultLocale = 'en-US') {
282
+ const itemGroups = groupResourcesByLocale(manifest.items, defaultLocale);
283
+ const passageGroups = groupResourcesByLocale(manifest.passages, defaultLocale);
284
+ const testGroups = groupResourcesByLocale(manifest.tests, defaultLocale);
285
+ // Collect all unique locales
286
+ const availableLocales = new Set();
287
+ for (const group of [
288
+ ...itemGroups.values(),
289
+ ...passageGroups.values(),
290
+ ...testGroups.values(),
291
+ ]) {
292
+ for (const locale of group.availableLocales) {
293
+ availableLocales.add(locale);
294
+ }
295
+ }
296
+ return {
297
+ manifest,
298
+ itemGroups,
299
+ passageGroups,
300
+ testGroups,
301
+ availableLocales,
302
+ };
303
+ }
304
+ /**
305
+ * Get a specific item resource in the requested locale.
306
+ *
307
+ * Uses fallback chain to find the best matching locale variant.
308
+ *
309
+ * @param localizedManifest Localized manifest
310
+ * @param baseId Base identifier of the item
311
+ * @param requestedLocale User's requested locale
312
+ * @returns Localized resource, or undefined if item not found
313
+ *
314
+ * @example
315
+ * const item = getLocalizedItem(manifest, "simple-choice", "es-MX");
316
+ * // Returns Spanish variant (es-ES) if available, otherwise falls back
317
+ */
318
+ export function getLocalizedItem(localizedManifest, baseId, requestedLocale) {
319
+ const group = localizedManifest.itemGroups.get(baseId);
320
+ if (!group)
321
+ return undefined;
322
+ return selectLocalizedResource(group, requestedLocale, group.defaultLocale);
323
+ }
324
+ /**
325
+ * Get a specific passage resource in the requested locale.
326
+ *
327
+ * @param localizedManifest Localized manifest
328
+ * @param baseId Base identifier of the passage
329
+ * @param requestedLocale User's requested locale
330
+ * @returns Localized resource, or undefined if passage not found
331
+ */
332
+ export function getLocalizedPassage(localizedManifest, baseId, requestedLocale) {
333
+ const group = localizedManifest.passageGroups.get(baseId);
334
+ if (!group)
335
+ return undefined;
336
+ return selectLocalizedResource(group, requestedLocale, group.defaultLocale);
337
+ }
338
+ /**
339
+ * Get a specific test resource in the requested locale.
340
+ *
341
+ * @param localizedManifest Localized manifest
342
+ * @param baseId Base identifier of the test
343
+ * @param requestedLocale User's requested locale
344
+ * @returns Localized resource, or undefined if test not found
345
+ */
346
+ export function getLocalizedTest(localizedManifest, baseId, requestedLocale) {
347
+ const group = localizedManifest.testGroups.get(baseId);
348
+ if (!group)
349
+ return undefined;
350
+ return selectLocalizedResource(group, requestedLocale, group.defaultLocale);
351
+ }
352
+ /**
353
+ * Get all items available in the requested locale.
354
+ *
355
+ * Returns all items, using fallback chain to select the best variant
356
+ * for each item when exact locale match is not available.
357
+ *
358
+ * @param localizedManifest Localized manifest
359
+ * @param requestedLocale User's requested locale
360
+ * @returns Array of localized resources
361
+ *
362
+ * @example
363
+ * const items = getAllItemsForLocale(manifest, "es-ES");
364
+ * // Returns Spanish variants where available, falls back to default for others
365
+ */
366
+ export function getAllItemsForLocale(localizedManifest, requestedLocale) {
367
+ const items = [];
368
+ for (const group of localizedManifest.itemGroups.values()) {
369
+ const resource = selectLocalizedResource(group, requestedLocale, group.defaultLocale);
370
+ if (resource) {
371
+ items.push(resource);
372
+ }
373
+ }
374
+ return items;
375
+ }
376
+ /**
377
+ * Get all passages available in the requested locale.
378
+ *
379
+ * @param localizedManifest Localized manifest
380
+ * @param requestedLocale User's requested locale
381
+ * @returns Array of localized resources
382
+ */
383
+ export function getAllPassagesForLocale(localizedManifest, requestedLocale) {
384
+ const passages = [];
385
+ for (const group of localizedManifest.passageGroups.values()) {
386
+ const resource = selectLocalizedResource(group, requestedLocale, group.defaultLocale);
387
+ if (resource) {
388
+ passages.push(resource);
389
+ }
390
+ }
391
+ return passages;
392
+ }
393
+ /**
394
+ * Get all tests available in the requested locale.
395
+ *
396
+ * @param localizedManifest Localized manifest
397
+ * @param requestedLocale User's requested locale
398
+ * @returns Array of localized resources
399
+ */
400
+ export function getAllTestsForLocale(localizedManifest, requestedLocale) {
401
+ const tests = [];
402
+ for (const group of localizedManifest.testGroups.values()) {
403
+ const resource = selectLocalizedResource(group, requestedLocale, group.defaultLocale);
404
+ if (resource) {
405
+ tests.push(resource);
406
+ }
407
+ }
408
+ return tests;
409
+ }
410
+ //# sourceMappingURL=localized-resources.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localized-resources.js","sourceRoot":"","sources":["../src/localized-resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AA0DH;;;;;;;GAOG;AAC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AK,IAAI,iBAAiB,CAAC,UAAU,CAAC,MAAM,EAAE,EAAE,CAAC;QAC1D,MAAM,QAAQ,GAAG,uBAAuB,CAAC,KAAK,EAAE,eAAe,EAAE,KAAK,CAAC,aAAa,CAAC,CAAC;QACtF,IAAI,QAAQ,EAAE,CAAC;YACb,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,83 @@
1
+ /**
2
+ * QTI Manifest (imsmanifest.xml) parser
3
+ *
4
+ * Parses IMS Content Package manifests to extract:
5
+ * - Resource definitions (items, passages, assessments)
6
+ * - Dependencies between resources
7
+ * - File locations and types
8
+ */
9
+ import { PassageRegistry } from './passage-reusability.js';
10
+ /**
11
+ * QTI resource type
12
+ */
13
+ export type ResourceType = 'imsqti_item_xmlv2p1' | 'imsqti_item_xmlv2p2' | 'imsqti_test_xmlv2p1' | 'imsqti_test_xmlv2p2' | 'imsqti_assessment_xmlv2p1' | 'imsqti_apip_xmlv2p2' | 'webcontent' | 'associatedcontent/imsqti_item_xmlv2p1' | string;
14
+ /**
15
+ * Manifest resource entry
16
+ */
17
+ export interface ManifestResource {
18
+ /** Resource identifier */
19
+ identifier: string;
20
+ /** Resource type */
21
+ type: ResourceType;
22
+ /**
23
+ * Optional xml:base for this resource element.
24
+ * Used by IMS CP to resolve relative hrefs when packages use nested bases.
25
+ */
26
+ xmlBase?: string;
27
+ /** Main file href */
28
+ href?: string;
29
+ /** All files in this resource */
30
+ files: string[];
31
+ /** Dependencies (identifierrefs) */
32
+ dependencies: string[];
33
+ /** Metadata */
34
+ metadata?: {
35
+ title?: string;
36
+ description?: string;
37
+ /** IMS LOM language code (e.g., "en-US", "es-ES") */
38
+ language?: string;
39
+ };
40
+ }
41
+ /**
42
+ * Parsed manifest structure
43
+ */
44
+ export interface ParsedManifest {
45
+ /** Manifest identifier */
46
+ identifier?: string;
47
+ /**
48
+ * Optional xml:base at the manifest element level.
49
+ * Used by IMS CP to resolve relative hrefs.
50
+ */
51
+ xmlBase?: string;
52
+ /** All resources */
53
+ resources: Map<string, ManifestResource>;
54
+ /** Item resources */
55
+ items: ManifestResource[];
56
+ /** Passage/stimulus resources */
57
+ passages: ManifestResource[];
58
+ /** Test/assessment resources */
59
+ tests: ManifestResource[];
60
+ /** Base path for resolving relative paths */
61
+ basePath?: string;
62
+ }
63
+ /**
64
+ * Parse QTI manifest XML
65
+ */
66
+ export declare function parseManifest(manifestXml: string, basePath?: string): ParsedManifest;
67
+ /**
68
+ * Build passage registry from manifest
69
+ *
70
+ * Analyzes manifest to identify:
71
+ * - Which passages are referenced by items
72
+ * - Which passages are reusable (multiple items reference them)
73
+ */
74
+ export declare function buildPassageRegistryFromManifest(manifest: ParsedManifest): PassageRegistry;
75
+ /**
76
+ * Get passage content file path from manifest
77
+ */
78
+ export declare function getPassageFilePath(manifest: ParsedManifest, passageId: string): string | undefined;
79
+ /**
80
+ * Get all items that depend on a passage
81
+ */
82
+ export declare function getItemsReferencingPassage(manifest: ParsedManifest, passageId: string): ManifestResource[];
83
+ //# sourceMappingURL=manifest-parser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest-parser.d.ts","sourceRoot":"","sources":["../src/manifest-parser.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAE3D;;GAEG;AACH,MAAM,MAAM,YAAY,GACpB,qBAAqB,GACrB,qBAAqB,GACrB,qBAAqB,GACrB,qBAAqB,GACrB,2BAA2B,GAC3B,qBAAqB,GACrB,YAAY,GACZ,uCAAuC,GACvC,MAAM,CAAC;AAEX;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,0BAA0B;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,oBAAoB;IACpB,IAAI,EAAE,YAAY,CAAC;IACnB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,C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imsmanifest.xml) parser
3
+ *
4
+ * Parses IMS Content Package manifests to extract:
5
+ * - Resource definitions (items, passages, assessments)
6
+ * - Dependencies between resources
7
+ * - File locations and types
8
+ */
9
+ import { parse } from 'node-html-parser';
10
+ import { PassageRegistry } from './passage-reusability.js';
11
+ /**
12
+ * Parse QTI manifest XML
13
+ */
14
+ export function parseManifest(manifestXml, basePath) {
15
+ const doc = parse(manifestXml, {
16
+ lowerCaseTagName: false,
17
+ comment: false,
18
+ });
19
+ const manifest = doc.querySelector('manifest') || doc.getElementsByTagName('manifest')[0];
20
+ if (!manifest) {
21
+ throw new Error('No manifest element found in XML');
22
+ }
23
+ const manifestId = manifest.getAttribute('identifier');
24
+ const manifestXmlBase = manifest.getAttribute('xml:base') || undefined;
25
+ // Parse all resources
26
+ const resourcesElement = manifest.querySelector('resources') ||
27
+ manifest.getElementsByTagName('resources')[0];
28
+ if (!resourcesElement) {
29
+ return {
30
+ identifier: manifestId,
31
+ resources: new Map(),
32
+ items: [],
33
+ passages: [],
34
+ tests: [],
35
+ basePath,
36
+ };
37
+ }
38
+ const resourceElements = resourcesElement.getElementsByTagName('resource');
39
+ const resources = new Map();
40
+ const items = [];
41
+ const passages = [];
42
+ const tests = [];
43
+ for (const resourceEl of Array.from(resourceElements)) {
44
+ const resource = parseResource(resourceEl);
45
+ resources.set(resource.identifier, resource);
46
+ // Categorize by type
47
+ if (isItemType(resource.type)) {
48
+ items.push(resource);
49
+ }
50
+ else if (isPassageType(resource.type)) {
51
+ passages.push(resource);
52
+ }
53
+ else if (isTestType(resource.type)) {
54
+ tests.push(resource);
55
+ }
56
+ }
57
+ return {
58
+ identifier: manifestId,
59
+ xmlBase: manifestXmlBase,
60
+ resources,
61
+ items,
62
+ passages,
63
+ tests,
64
+ basePath,
65
+ };
66
+ }
67
+ /**
68
+ * Parse individual resource element
69
+ */
70
+ function parseResource(resourceEl) {
71
+ const identifier = resourceEl.getAttribute('identifier') || '';
72
+ const type = resourceEl.getAttribute('type') || '';
73
+ const href = resourceEl.getAttribute('href') || undefined;
74
+ const xmlBase = resourceEl.getAttribute('xml:base') || undefined;
75
+ // Extract all file elements
76
+ const fileElements = resourceEl.getElementsByTagName('file');
77
+ const files = Array.from(fileElements)
78
+ .map(f => f.getAttribute('href'))
79
+ .filter((h) => !!h);
80
+ // If href not specified but files exist, use first file as href
81
+ const mainHref = href || (files.length > 0 ? files[0] : undefined);
82
+ // Extract dependencies
83
+ const depElements = resourceEl.getElementsByTagName('dependency');
84
+ const dependencies = Array.from(depElements)
85
+ .map(d => d.getAttribute('identifierref'))
86
+ .filter((id) => !!id);
87
+ // Extract metadata if present
88
+ let metadata;
89
+ const metadataEl = resourceEl.querySelector('metadata');
90
+ if (metadataEl) {
91
+ const title = metadataEl.querySelector('title')?.textContent?.trim();
92
+ const description = metadataEl.querySelector('description')?.textContent?.trim();
93
+ // Extract IMS LOM language (supports multiple selector patterns)
94
+ const languageEl = metadataEl.querySelector('language, [\\:language]') ||
95
+ metadataEl.querySelector('[name="language"]');
96
+ const language = languageEl?.textContent?.trim();
97
+ if (title || description || language) {
98
+ metadata = { title, description, language };
99
+ }
100
+ }
101
+ return {
102
+ identifier,
103
+ type,
104
+ xmlBase,
105
+ href: mainHref,
106
+ files,
107
+ dependencies,
108
+ metadata,
109
+ };
110
+ }
111
+ /**
112
+ * Check if resource type is an item
113
+ */
114
+ function isItemType(type) {
115
+ return type.includes('imsqti_item') ||
116
+ type.includes('qti_item') ||
117
+ type === 'associatedcontent/imsqti_item_xmlv2p1';
118
+ }
119
+ /**
120
+ * Check if resource type is a passage/stimulus
121
+ */
122
+ function isPassageType(type) {
123
+ return type === 'webcontent' ||
124
+ type.includes('passage') ||
125
+ type.includes('stimulus') ||
126
+ type.includes('apip');
127
+ }
128
+ /**
129
+ * Check if resource type is a test/assessment
130
+ */
131
+ function isTestType(type) {
132
+ return type.includes('test') || type.includes('assessment');
133
+ }
134
+ /**
135
+ * Build passage registry from manifest
136
+ *
137
+ * Analyzes manifest to identify:
138
+ * - Which passages are referenced by items
139
+ * - Which passages are reusable (multiple items reference them)
140
+ */
141
+ export function buildPassageRegistryFromManifest(manifest) {
142
+ const registry = new PassageRegistry();
143
+ // Register all passage resources
144
+ for (const passage of manifest.passages) {
145
+ // Find all items that depend on this passage
146
+ for (const item of manifest.items) {
147
+ if (item.dependencies.includes(passage.identifier)) {
148
+ registry.registerReference(item.identifier, {
149
+ id: passage.identifier, // Use QTI identifier directly
150
+ source: 'manifest',
151
+ qtiIdentifier: passage.identifier,
152
+ filePath: passage.href,
153
+ isReusable: false, // Will be updated by registry
154
+ });
155
+ }
156
+ }
157
+ }
158
+ return registry;
159
+ }
160
+ /**
161
+ * Get passage content file path from manifest
162
+ */
163
+ export function getPassageFilePath(manifest, passageId) {
164
+ const passage = manifest.resources.get(passageId);
165
+ return passage?.href;
166
+ }
167
+ /**
168
+ * Get all items that depend on a passage
169
+ */
170
+ export function getItemsReferencingPassage(manifest, passageId) {
171
+ return manifest.items.filter(item => item.dependencies.includes(passageId));
172
+ }
173
+ //# sourceMappingURL=manifest-parser.js.map