@pie-qti/ims-cp-core 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,7 @@
1
1
  import { parseManifest } from './manifest-parser.js';
2
- import { dirnamePackagePath, isExternalPackageHref, joinPackagePath, resolvePackagePath, } from './package-path.js';
2
+ import { buildPackageFileIndex, resolvePackageReference, } from './package-file-resolver.js';
3
+ import { dirnamePackagePath, isExternalPackageHref, joinPackagePath, resolveCheckedPackagePath, resolvePackagePath, } from './package-path.js';
4
+ import { decodeXmlAttribute, parseSrcsetCandidates } from './security-parsing.js';
3
5
  const ASSET_EXTENSIONS = {
4
6
  '.apng': 'image',
5
7
  '.avif': 'image',
@@ -21,7 +23,7 @@ const ASSET_EXTENSIONS = {
21
23
  '.htm': 'html',
22
24
  '.xml': 'source-qti',
23
25
  };
24
- export async function analyzeContentPackage({ packageId, manifestXml, basePath, fileAccess, }) {
26
+ export async function analyzeContentPackage({ packageId, manifestXml, basePath, fileAccess, heuristicsConfig, }) {
25
27
  const manifest = parseManifest(manifestXml, basePath);
26
28
  const diagnostics = [];
27
29
  const resources = new Map();
@@ -29,6 +31,7 @@ export async function analyzeContentPackage({ packageId, manifestXml, basePath,
29
31
  const assets = new Map();
30
32
  const files = fileAccess?.listFiles ? await fileAccess.listFiles() : [];
31
33
  const listedFiles = fileAccess?.listFiles ? new Set(files) : undefined;
34
+ const fileIndexPaths = new Set(files);
32
35
  const versionSignals = [
33
36
  ...detectManifestVersionSignals(manifestXml),
34
37
  ...detectResourceTypeVersionSignals(manifest.resources.values()),
@@ -36,7 +39,12 @@ export async function analyzeContentPackage({ packageId, manifestXml, basePath,
36
39
  for (const resource of manifest.resources.values()) {
37
40
  const node = toResourceNode(resource, manifest);
38
41
  resources.set(node.identifier, node);
42
+ diagnostics.push(...unsafeManifestPathDiagnostics(resource, manifest));
43
+ if (node.resolvedHref) {
44
+ fileIndexPaths.add(node.resolvedHref);
45
+ }
39
46
  for (const filePath of node.resolvedFiles) {
47
+ fileIndexPaths.add(filePath);
40
48
  maybeRegisterAsset(assets, filePath, {
41
49
  ownerResourceId: node.identifier,
42
50
  sourcePath: node.resolvedHref,
@@ -53,6 +61,12 @@ export async function analyzeContentPackage({ packageId, manifestXml, basePath,
53
61
  }
54
62
  }
55
63
  }
64
+ const fileIndex = buildPackageFileIndex([...fileIndexPaths]);
65
+ diagnostics.push(...fileIndex.diagnostics);
66
+ const manifestEvidencePaths = new Set([...resources.values()].flatMap((resource) => [
67
+ ...(resource.resolvedHref ? [resource.resolvedHref] : []),
68
+ ...resource.resolvedFiles,
69
+ ]));
56
70
  for (const node of resources.values()) {
57
71
  const resourceReferences = [];
58
72
  for (const dependency of node.dependencies) {
@@ -77,18 +91,22 @@ export async function analyzeContentPackage({ packageId, manifestXml, basePath,
77
91
  const xml = await fileAccess.readText(node.resolvedHref);
78
92
  if (xml) {
79
93
  versionSignals.push(...detectQtiXmlVersionSignals(xml, node));
80
- const discovered = discoverReferences(xml, node);
94
+ const discovered = discoverReferences(xml, node, fileIndex, manifestEvidencePaths, heuristicsConfig);
95
+ diagnostics.push(...discovered.diagnostics.map((diagnostic) => ({
96
+ ...diagnostic,
97
+ resourceId: node.identifier,
98
+ })));
81
99
  for (const reference of discovered.references) {
82
- if (reference.kind === 'assessment-item-ref' && reference.resolvedPath) {
100
+ if ((reference.kind === 'assessment-item-ref' || reference.kind === 'stimulus') && reference.resolvedPath) {
83
101
  const target = findResourceByResolvedHref(resources, reference.resolvedPath);
84
102
  if (target) {
85
103
  reference.targetResourceId = target.identifier;
86
104
  }
87
- else {
105
+ else if (!(await packagePathExists(reference.resolvedPath, fileAccess, listedFiles))) {
88
106
  diagnostics.push({
89
107
  severity: 'warning',
90
- code: 'IMS_CP_DANGLING_ITEM_REF',
91
- message: `Resource ${node.identifier} references missing assessment item ${reference.rawHref}.`,
108
+ code: reference.kind === 'stimulus' ? 'IMS_CP_DANGLING_STIMULUS_REF' : 'IMS_CP_DANGLING_ITEM_REF',
109
+ message: `Resource ${node.identifier} references missing ${reference.kind === 'stimulus' ? 'assessment stimulus' : 'assessment item'} ${reference.rawHref}.`,
92
110
  resourceId: node.identifier,
93
111
  sourcePath: node.resolvedHref,
94
112
  reference: reference.rawHref,
@@ -195,19 +213,45 @@ export function serializeContentPackageEvidence(packageGraph) {
195
213
  }
196
214
  function toResourceNode(resource, manifest) {
197
215
  const base = joinPackagePath(manifest.xmlBase, resource.xmlBase);
216
+ const resolvedHref = resource.href ? resolveCheckedPackagePath(base, resource.href) ?? undefined : undefined;
198
217
  return {
199
218
  identifier: resource.identifier,
200
219
  type: resource.type,
201
220
  kind: classifyResource(resource),
202
221
  href: resource.href,
203
- resolvedHref: resource.href ? resolvePackagePath(base, resource.href) : undefined,
222
+ resolvedHref,
204
223
  xmlBase: resource.xmlBase,
205
224
  files: resource.files,
206
- resolvedFiles: resource.files.map((file) => resolvePackagePath(base, file)),
225
+ resolvedFiles: resource.files.flatMap((file) => {
226
+ const resolved = resolveCheckedPackagePath(base, file);
227
+ return resolved ? [resolved] : [];
228
+ }),
207
229
  dependencies: resource.dependencies,
208
230
  metadata: resource.metadata,
209
231
  };
210
232
  }
233
+ function unsafeManifestPathDiagnostics(resource, manifest) {
234
+ const base = joinPackagePath(manifest.xmlBase, resource.xmlBase);
235
+ const diagnostics = [];
236
+ const candidates = [
237
+ ...(manifest.xmlBase ? [{ href: manifest.xmlBase, kind: 'manifest xml:base', basePath: undefined }] : []),
238
+ ...(resource.xmlBase ? [{ href: resource.xmlBase, kind: 'resource xml:base', basePath: manifest.xmlBase }] : []),
239
+ ...(resource.href ? [{ href: resource.href, kind: 'resource href' }] : []),
240
+ ...resource.files.map((href) => ({ href, kind: 'file href' })),
241
+ ];
242
+ for (const candidate of candidates) {
243
+ if (resolveCheckedPackagePath(candidate.basePath ?? base, candidate.href))
244
+ continue;
245
+ diagnostics.push({
246
+ severity: 'error',
247
+ code: 'IMS_CP_UNSAFE_MANIFEST_PATH',
248
+ message: `Resource ${resource.identifier} declares unsafe manifest ${candidate.kind} ${candidate.href}.`,
249
+ resourceId: resource.identifier,
250
+ reference: candidate.href,
251
+ });
252
+ }
253
+ return diagnostics;
254
+ }
211
255
  function toEntrypoint(resource, kind) {
212
256
  return {
213
257
  resourceId: resource.identifier,
@@ -228,12 +272,30 @@ function classifyResource(resource) {
228
272
  return 'asset';
229
273
  return 'other';
230
274
  }
231
- function discoverReferences(xml, owner) {
275
+ function discoverReferences(xml, owner, fileIndex, manifestEvidencePaths, heuristicsConfig) {
232
276
  const references = [];
233
277
  const assets = [];
278
+ const diagnostics = [];
234
279
  const basePath = owner.resolvedHref ? dirnamePackagePath(owner.resolvedHref) : '';
235
280
  for (const match of findAttributeReferences(xml)) {
236
- const resolvedPath = resolvePackagePath(basePath, match.rawHref);
281
+ const resolution = resolvePackageReference({
282
+ fileIndex,
283
+ sourcePath: owner.resolvedHref,
284
+ rawHref: match.rawHref,
285
+ referenceKind: referenceKindForMatch(match.kind),
286
+ manifestEvidencePaths,
287
+ heuristicsConfig,
288
+ });
289
+ diagnostics.push(...resolution.diagnostics);
290
+ if (resolution.status === 'skipped') {
291
+ continue;
292
+ }
293
+ if (resolution.status === 'unsafe' || resolution.status === 'ambiguous') {
294
+ continue;
295
+ }
296
+ const resolvedPath = resolution.status === 'resolved'
297
+ ? resolution.resolvedPath
298
+ : resolvePackagePath(basePath, match.rawHref);
237
299
  const reference = {
238
300
  kind: match.kind,
239
301
  rawHref: match.rawHref,
@@ -241,9 +303,16 @@ function discoverReferences(xml, owner) {
241
303
  sourcePath: owner.resolvedHref,
242
304
  sourceElement: match.element,
243
305
  sourceAttribute: match.attribute,
306
+ ...(resolution.status === 'resolved'
307
+ ? {
308
+ resolutionStrategy: resolution.strategy,
309
+ heuristic: resolution.heuristic,
310
+ renderHref: resolution.renderHref,
311
+ }
312
+ : {}),
244
313
  };
245
314
  references.push(reference);
246
- if (match.kind !== 'assessment-item-ref') {
315
+ if (match.kind !== 'assessment-item-ref' && match.kind !== 'stimulus') {
247
316
  assets.push({
248
317
  rawHref: match.rawHref,
249
318
  resolvedPath,
@@ -252,43 +321,126 @@ function discoverReferences(xml, owner) {
252
321
  sourcePath: owner.resolvedHref,
253
322
  sourceElement: match.element,
254
323
  sourceAttribute: match.attribute,
324
+ ...(resolution.status === 'resolved'
325
+ ? {
326
+ resolutionStrategy: resolution.strategy,
327
+ heuristic: resolution.heuristic,
328
+ renderHref: resolution.renderHref,
329
+ }
330
+ : {}),
255
331
  });
256
332
  }
257
333
  }
258
- return { references, assets };
334
+ return { references, assets, diagnostics };
259
335
  }
260
336
  function findAttributeReferences(xml) {
261
337
  const refs = [];
262
- const pattern = /<(?<element>assessmentItemRef|img|object|audio|video|source|stylesheet|link|file)\b(?<attrs>[^>]*)>/gi;
338
+ const pattern = /<(?<element>assessmentItemRef|qti-assessment-item-ref|assessmentStimulusRef|qti-assessment-stimulus-ref|img|object|audio|video|source|track|embed|stylesheet|qti-stylesheet|link|file|fileHref|qti-file-href)\b(?<attrs>(?:[^>"']+|"[^"]*"|'[^']*')*)>/gi;
263
339
  for (const match of xml.matchAll(pattern)) {
264
340
  const element = match.groups?.element ?? '';
265
341
  const attrs = match.groups?.attrs ?? '';
266
- const attribute = element === 'object' ? 'data' : element === 'img' ? 'src' : 'href';
267
- const rawHref = readAttribute(attrs, attribute) ?? readAttribute(attrs, 'src') ?? readAttribute(attrs, 'href');
342
+ for (const attribute of referenceAttributesForElement(element)) {
343
+ const rawValue = readAttribute(attrs, attribute);
344
+ if (!rawValue)
345
+ continue;
346
+ const hrefs = attribute === 'srcset' ? parseSrcsetHrefs(rawValue) : [rawValue];
347
+ for (const rawHref of hrefs) {
348
+ const decodedHref = decodeXmlAttribute(rawHref);
349
+ if (!decodedHref || isExternalPackageHref(decodedHref))
350
+ continue;
351
+ refs.push({
352
+ kind: kindFromElement(element),
353
+ element,
354
+ attribute,
355
+ rawHref: decodedHref,
356
+ });
357
+ }
358
+ }
359
+ }
360
+ const catalogTextPattern = /<(?<element>fileHref|filehref|qti-file-href)\b[^>]*>(?<rawHref>[^<]+)<\/(?:fileHref|filehref|qti-file-href)>/gi;
361
+ for (const match of xml.matchAll(catalogTextPattern)) {
362
+ const element = match.groups?.element ?? '';
363
+ const rawHref = decodeXmlAttribute(match.groups?.rawHref?.trim() ?? '');
268
364
  if (!rawHref || isExternalPackageHref(rawHref))
269
365
  continue;
270
366
  refs.push({
271
- kind: kindFromElement(element),
367
+ kind: 'catalog',
272
368
  element,
273
- attribute: rawHref === readAttribute(attrs, 'data') ? 'data' : rawHref === readAttribute(attrs, 'src') ? 'src' : 'href',
369
+ attribute: 'text',
274
370
  rawHref,
275
371
  });
276
372
  }
277
373
  return refs;
278
374
  }
375
+ function referenceAttributesForElement(element) {
376
+ switch (element.toLowerCase()) {
377
+ case 'object':
378
+ return ['data'];
379
+ case 'img':
380
+ return ['src', 'srcset'];
381
+ case 'video':
382
+ return ['src', 'poster'];
383
+ case 'audio':
384
+ case 'source':
385
+ case 'track':
386
+ case 'embed':
387
+ return ['src'];
388
+ case 'assessmentitemref':
389
+ case 'qti-assessment-item-ref':
390
+ case 'assessmentstimulusref':
391
+ case 'qti-assessment-stimulus-ref':
392
+ case 'stylesheet':
393
+ case 'qti-stylesheet':
394
+ case 'link':
395
+ case 'file':
396
+ return ['href', 'src'];
397
+ case 'filehref':
398
+ case 'qti-file-href':
399
+ return ['src', 'href'];
400
+ default:
401
+ return ['href', 'src', 'poster'];
402
+ }
403
+ }
404
+ function parseSrcsetHrefs(value) {
405
+ return parseSrcsetCandidates(value).map((candidate) => candidate.url);
406
+ }
279
407
  function kindFromElement(element) {
280
- switch (element) {
281
- case 'assessmentItemRef':
408
+ switch (element.toLowerCase()) {
409
+ case 'assessmentitemref':
410
+ case 'qti-assessment-item-ref':
282
411
  return 'assessment-item-ref';
283
412
  case 'stylesheet':
413
+ case 'qti-stylesheet':
284
414
  case 'link':
285
415
  return 'stylesheet';
416
+ case 'assessmentstimulusref':
417
+ case 'qti-assessment-stimulus-ref':
418
+ return 'stimulus';
419
+ case 'filehref':
420
+ case 'qti-file-href':
421
+ return 'catalog';
286
422
  case 'object':
287
423
  return 'object';
288
424
  default:
289
425
  return 'asset';
290
426
  }
291
427
  }
428
+ function referenceKindForMatch(kind) {
429
+ switch (kind) {
430
+ case 'assessment-item-ref':
431
+ case 'stimulus':
432
+ return 'source-xml';
433
+ case 'stylesheet':
434
+ return 'stylesheet';
435
+ case 'catalog':
436
+ return 'catalog-file';
437
+ case 'asset':
438
+ case 'object':
439
+ return 'media-asset';
440
+ default:
441
+ return 'other-asset';
442
+ }
443
+ }
292
444
  function usageFromReference(kind, path) {
293
445
  if (kind === 'stylesheet')
294
446
  return 'stylesheet';
@@ -326,19 +478,26 @@ function buildClosure(resourceId, resources, references, packageDiagnostics) {
326
478
  for (const reference of references.get(id) ?? []) {
327
479
  if (reference.targetResourceId)
328
480
  visit(reference.targetResourceId);
329
- if (reference.resolvedPath && reference.kind !== 'assessment-item-ref') {
481
+ if (reference.resolvedPath && reference.kind !== 'assessment-item-ref' && reference.kind !== 'stimulus') {
330
482
  assetPaths.add(reference.resolvedPath);
331
483
  filePaths.add(reference.resolvedPath);
332
484
  }
485
+ else if (reference.resolvedPath && !reference.targetResourceId) {
486
+ filePaths.add(reference.resolvedPath);
487
+ }
333
488
  }
334
489
  }
335
490
  visit(resourceId);
491
+ const visitedResourceIds = new Set(visited);
336
492
  return {
337
493
  resourceId,
338
494
  resourceIds: [...visited],
339
495
  filePaths: [...filePaths],
340
496
  assetPaths: [...assetPaths],
341
- diagnostics: [...diagnostics, ...packageDiagnostics.filter((diagnostic) => diagnostic.resourceId === resourceId)],
497
+ diagnostics: [
498
+ ...diagnostics,
499
+ ...packageDiagnostics.filter((diagnostic) => diagnostic.resourceId && visitedResourceIds.has(diagnostic.resourceId)),
500
+ ],
342
501
  };
343
502
  }
344
503
  function maybeRegisterAsset(assets, path, context) {
@@ -380,6 +539,9 @@ function registerAsset(assets, asset) {
380
539
  sourcePaths: [...sourcePaths],
381
540
  sourceElement: existing.sourceElement ?? asset.sourceElement,
382
541
  sourceAttribute: existing.sourceAttribute ?? asset.sourceAttribute,
542
+ resolutionStrategy: existing.resolutionStrategy ?? asset.resolutionStrategy,
543
+ heuristic: existing.heuristic ?? asset.heuristic,
544
+ renderHref: existing.renderHref ?? asset.renderHref,
383
545
  });
384
546
  }
385
547
  function findResourceByResolvedHref(resources, resolvedHref) {
@@ -558,10 +720,13 @@ function dedupeVersionSignals(signals) {
558
720
  function buildRelationshipHints(references, assets) {
559
721
  const hints = [];
560
722
  for (const reference of references) {
561
- if (reference.kind !== 'manifest-dependency' && reference.kind !== 'assessment-item-ref')
723
+ if (reference.kind !== 'manifest-dependency' &&
724
+ reference.kind !== 'assessment-item-ref' &&
725
+ reference.kind !== 'stimulus') {
562
726
  continue;
727
+ }
563
728
  hints.push({
564
- kind: reference.kind,
729
+ kind: reference.kind === 'stimulus' ? 'assessment-stimulus-ref' : reference.kind,
565
730
  sourceResourceId: reference.resourceId,
566
731
  targetResourceId: reference.targetResourceId,
567
732
  targetPath: reference.resolvedPath,