@aboutgeo/pdiiif 0.0.0-stage → 0.2.7

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 (69) hide show
  1. package/README.md +169 -2
  2. package/dist/__tests__/parser.test.d.ts +1 -0
  3. package/dist/__tests__/pdf.spec.d.ts +1 -0
  4. package/dist/__tests__/region.test.d.ts +1 -0
  5. package/dist/__tests__/setupJest.d.ts +0 -0
  6. package/dist/assets/optimization.worker-C8u4PFfM.js +886 -0
  7. package/dist/assets/optimization.worker-C8u4PFfM.js.map +1 -0
  8. package/dist/convert.d.ts +223 -0
  9. package/dist/download.d.ts +115 -0
  10. package/dist/iiif.d.ts +110 -0
  11. package/dist/index.cjs +65 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.mjs +11137 -0
  15. package/dist/index.mjs.map +1 -0
  16. package/dist/io.d.ts +75 -0
  17. package/dist/log.d.ts +21 -0
  18. package/dist/metrics.d.ts +10 -0
  19. package/dist/ocr.d.ts +36 -0
  20. package/dist/optimization.d.ts +48 -0
  21. package/dist/optimization.worker.d.ts +1 -0
  22. package/dist/pdf/annos-text.d.ts +19 -0
  23. package/dist/pdf/annos.d.ts +4 -0
  24. package/dist/pdf/common.d.ts +48 -0
  25. package/dist/pdf/generator.d.ts +197 -0
  26. package/dist/pdf/image.d.ts +34 -0
  27. package/dist/pdf/parser.d.ts +131 -0
  28. package/dist/pdf/pkzip.d.ts +23 -0
  29. package/dist/pdf/png.d.ts +34 -0
  30. package/dist/pdf/util.d.ts +18 -0
  31. package/dist/res/licenses.d.ts +7 -0
  32. package/dist/res/srgbColorspace.d.ts +2 -0
  33. package/dist/util.d.ts +8 -0
  34. package/dist/version.d.ts +2 -0
  35. package/package.json +149 -4
  36. package/src/__tests__/fixtures/deep_toc.json +2953 -0
  37. package/src/__tests__/fixtures/flat_toc.json +2917 -0
  38. package/src/__tests__/fixtures/physdim.json +294 -0
  39. package/src/__tests__/fixtures/region_target.json +58 -0
  40. package/src/__tests__/fixtures/wunder.jpg +0 -0
  41. package/src/__tests__/parser.test.ts +42 -0
  42. package/src/__tests__/pdf.spec.ts +216 -0
  43. package/src/__tests__/region.test.ts +194 -0
  44. package/src/__tests__/setupJest.ts +2 -0
  45. package/src/convert.ts +1098 -0
  46. package/src/download.ts +703 -0
  47. package/src/global.d.ts +10 -0
  48. package/src/iiif.ts +605 -0
  49. package/src/index.ts +7 -0
  50. package/src/io.ts +243 -0
  51. package/src/log.ts +51 -0
  52. package/src/metrics.ts +47 -0
  53. package/src/ocr.ts +176 -0
  54. package/src/optimization.ts +201 -0
  55. package/src/optimization.worker.ts +118 -0
  56. package/src/pdf/annos-text.ts +382 -0
  57. package/src/pdf/annos.ts +240 -0
  58. package/src/pdf/common.ts +158 -0
  59. package/src/pdf/generator.ts +1665 -0
  60. package/src/pdf/image.ts +340 -0
  61. package/src/pdf/parser.ts +811 -0
  62. package/src/pdf/pkzip.ts +228 -0
  63. package/src/pdf/png.ts +397 -0
  64. package/src/pdf/util.ts +111 -0
  65. package/src/res/licenses.ts +266 -0
  66. package/src/res/srgbColorspace.ts +405 -0
  67. package/src/types.d.ts +6 -0
  68. package/src/util.ts +55 -0
  69. package/src/version.ts +1 -0
package/src/iiif.ts ADDED
@@ -0,0 +1,605 @@
1
+ import {
2
+ InternationalString,
3
+ ExternalWebResource,
4
+ IIIFExternalWebResource,
5
+ ContentResource,
6
+ ImageProfile,
7
+ ImageService,
8
+ Reference,
9
+ Creator,
10
+ Agent,
11
+ W3CAnnotationTarget,
12
+ } from '@iiif/presentation-3';
13
+ import {
14
+ ManifestNormalized,
15
+ CanvasNormalized,
16
+ AnnotationPageNormalized,
17
+ AnnotationNormalized,
18
+ } from '@iiif/presentation-3-normalized';
19
+ import {
20
+ globalVault, Vault,
21
+ buildLocaleString,
22
+ createPaintingAnnotationsHelper,
23
+ createThumbnailHelper,
24
+ expandTarget,
25
+ SupportedTarget,
26
+ } from '@iiif/helpers';
27
+ import { ImageServiceLoader as ImageServiceLoader_ } from '@atlas-viewer/iiif-image-api';
28
+
29
+ import { getOcrReferences } from './ocr.js';
30
+ import log from './log.js';
31
+
32
+ const PURPOSE_ORDER = ['commenting', 'describing', 'tagging', 'no-purpose'];
33
+ const PURPOSE_LABELS: { [purpose: string]: string } = {
34
+ commenting: 'Comment',
35
+ describing: 'Description',
36
+ tagging: 'Tags',
37
+ };
38
+
39
+ export const vault = globalVault() as Vault;
40
+
41
+ /** Given a language preference in descending order,
42
+ * determine the best set of strings from the
43
+ * internationalized string.
44
+ */
45
+ export function getI18nValue(
46
+ val: string | InternationalString,
47
+ languagePreference: readonly string[]
48
+ ): string[];
49
+ export function getI18nValue(
50
+ val: string | InternationalString,
51
+ languagePreference: readonly string[],
52
+ separator: string
53
+ ): string;
54
+ export function getI18nValue(
55
+ val: string | InternationalString,
56
+ languagePreference: readonly string[],
57
+ separator?: string
58
+ ): string | string[] {
59
+ let splitAfter = false;
60
+ if (!separator) {
61
+ separator = '<<<SNIP>>>';
62
+ splitAfter = true;
63
+ }
64
+ const localized = buildLocaleString(val, languagePreference[0] ?? 'none', {
65
+ defaultText: '',
66
+ fallbackLanguages: languagePreference.slice(1),
67
+ separator,
68
+ });
69
+ if (splitAfter) {
70
+ return localized.split(separator).filter((s) => s.length > 0);
71
+ } else {
72
+ return localized;
73
+ }
74
+ }
75
+
76
+ /** Custom image loader to deal with browser + node intercompatibility.
77
+ *
78
+ * Used for the thumbnail helper.
79
+ */
80
+ class ImageServiceLoader extends ImageServiceLoader_ {
81
+ async fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
82
+ return fetch(input as any, init as any) as any;
83
+ }
84
+ }
85
+
86
+ const thumbHelper = createThumbnailHelper(vault, {
87
+ imageServiceLoader: new ImageServiceLoader(),
88
+ });
89
+
90
+ // A few helpers to deal with painting annotations
91
+ export const { getPaintables, getAllPaintingAnnotations, extractChoices } =
92
+ createPaintingAnnotationsHelper(vault);
93
+
94
+ /** Determine best thumbnail image for the manifest. */
95
+ export async function getThumbnail(
96
+ manifest: ManifestNormalized,
97
+ maxDimension: number
98
+ ): Promise<string | undefined> {
99
+ const thumb = await thumbHelper.getBestThumbnailAtSize(manifest, {
100
+ maxWidth: maxDimension,
101
+ maxHeight: maxDimension,
102
+ });
103
+ return thumb.best?.id;
104
+ }
105
+
106
+ /** Like a regular external web resource, but with an associated
107
+ profile URI, needed for OCR discovery */
108
+ export interface ExternalWebResourceWithProfile extends ExternalWebResource {
109
+ profile: string;
110
+ }
111
+
112
+ /** Check if a resource is an external resource with an
113
+ * associated profile. */
114
+ export function isExternalWebResourceWithProfile(
115
+ res: ContentResource
116
+ ): res is ExternalWebResourceWithProfile {
117
+ return (
118
+ res.type !== undefined &&
119
+ ['Dataset', 'Image', 'Video', 'Sound', 'Text', 'unknown'].indexOf(
120
+ res.type
121
+ ) >= 0 &&
122
+ (res as ExternalWebResourceWithProfile).profile !== undefined
123
+ );
124
+ }
125
+
126
+ /** See https://iiif.io/api/annex/services/#physical-dimensions */
127
+ export interface PhysicalDimensionService {
128
+ '@context': 'http://iiif.io/api/annex/services/physdim/1/context.json';
129
+ profile: 'http://iiif.io/api/annex/services/physdim';
130
+ '@id': string;
131
+ physicalScale: number;
132
+ physicalUnits: 'in' | 'cm' | 'mm';
133
+ }
134
+
135
+ /** Check if a service is a IIIF Physical Dimensions service */
136
+ export function isPhysicalDimensionService(
137
+ service: any // eslint-disable-line @typescript-eslint/explicit-module-boundary-types
138
+ ): service is PhysicalDimensionService {
139
+ return (
140
+ typeof service.profile === 'string' &&
141
+ service.profile === 'http://iiif.io/api/annex/services/physdim'
142
+ );
143
+ }
144
+
145
+ /** Check if a IIIF Image endpoint supports arbitrary downscaling. */
146
+ export function supportsScaling(profile: ImageProfile): boolean {
147
+ if (typeof profile === 'string') {
148
+ return profile.indexOf('level2') >= 0;
149
+ } else {
150
+ return (profile.supports?.indexOf('sizeByWh') ?? -1) >= 0;
151
+ }
152
+ }
153
+
154
+ /** Fetch the full IIIF Image service definition from
155
+ * its info.json endpoint. */
156
+ export async function fetchFullImageService(
157
+ serviceRef: ImageService
158
+ ): Promise<ImageService> {
159
+ const serviceUrl = `${serviceRef['@id'] ?? serviceRef.id}/info.json`;
160
+ const resp = await fetch(serviceUrl);
161
+ const res = await resp.json();
162
+ return res as ImageService;
163
+ }
164
+
165
+ export type ImageInfo = {
166
+ // The 'Image' content resource
167
+ resource: (ExternalWebResource | IIIFExternalWebResource) & { type: 'Image' };
168
+ // Where to draw on the corresponding canvas
169
+ x: number;
170
+ y: number;
171
+ // At what size to draw on the canvas?
172
+ width: number;
173
+ height: number;
174
+ // What is the image's size, if available?
175
+ nativeWidth?: number;
176
+ nativeHeight?: number;
177
+ // Only a part of the image is painted on the canvas, given as an IIIF Image API
178
+ // region (`x,y,w,h`, `pct:x,y,w,h` or `square`), see https://iiif.io/api/cookbook/recipe/0299-region/
179
+ region?: string;
180
+ ppi?: number;
181
+ format?: 'jpeg' | 'png' | 'unsupported';
182
+ choiceInfo?: {
183
+ enabled: boolean;
184
+ optional: boolean;
185
+ visibleByDefault: boolean;
186
+ label?: InternationalString;
187
+ };
188
+ };
189
+
190
+ /** Information about a canvas that can be obtained without
191
+ * fetching any external resources */
192
+ export type CanvasInfo = {
193
+ canvas: Reference<'Canvas'>;
194
+ ocr?: {
195
+ id: string;
196
+ };
197
+ images: ImageInfo[];
198
+ numAnnotations: number;
199
+ };
200
+
201
+ /** Extract all non-painting annotations that are of interest for PDF generation
202
+ * from a canvas */
203
+ export function getCanvasAnnotations(canvas: CanvasNormalized): Annotation[] {
204
+ return vault
205
+ .get<AnnotationPageNormalized>(canvas.annotations)
206
+ .flatMap((p) => vault.get<AnnotationNormalized>(p.items))
207
+ .filter((a) =>
208
+ Array.isArray(a.motivation)
209
+ ? a.motivation.find((m) => PURPOSE_LABELS[m] !== undefined) !==
210
+ undefined
211
+ : PURPOSE_LABELS[a.motivation ?? 'invalid'] !== undefined
212
+ )
213
+ .map((a) => parseAnnotation(a, []))
214
+ .filter((a): a is Annotation => a !== undefined);
215
+ }
216
+
217
+ /** Obtain all information about a canvas and its images
218
+ * without hitting any external endpoints.
219
+ */
220
+ export function getCanvasInfo(canvas: CanvasNormalized): CanvasInfo {
221
+ const imageInfos = getImageInfos(canvas);
222
+ const text = getOcrReferences(canvas);
223
+ return {
224
+ canvas: { id: canvas.id, type: 'Canvas' },
225
+ images: imageInfos,
226
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
227
+ ocr: text ? { id: text.id! } : undefined,
228
+ numAnnotations: getCanvasAnnotations(canvas).length,
229
+ };
230
+ }
231
+
232
+ /** A annotation prepared for rendering to PDF. */
233
+ export interface Annotation {
234
+ id: string;
235
+ target: SupportedTarget;
236
+ markup: string;
237
+ lastModified?: Date;
238
+ author?: string;
239
+ }
240
+
241
+ /** Format an annotation agent to a human readable string. */
242
+ function agentToString(agent: Agent): string {
243
+ let name = Array.isArray(agent.name) ? agent.name.join('; ') : agent.name;
244
+ if (!name) {
245
+ name = agent.nickname ?? 'unknown';
246
+ }
247
+ if (agent.email) {
248
+ return `${name} <${agent.email}>`;
249
+ }
250
+ return name;
251
+ }
252
+
253
+ /** Format a annotation creator definition to a human readable
254
+ * string. */
255
+ function creatorToString(creator: Creator): string {
256
+ if (Array.isArray(creator)) {
257
+ if (typeof creator[0] === 'string') {
258
+ return creator.join('; ');
259
+ } else {
260
+ return creator.map((a) => agentToString(a as Agent)).join('; ');
261
+ }
262
+ }
263
+ if (typeof creator === 'string') {
264
+ return creator;
265
+ }
266
+ return agentToString(creator);
267
+ }
268
+
269
+ /** Parse a IIIF annotation into a format that is more
270
+ * suitable for rendering to a PDF. */
271
+ export function parseAnnotation(
272
+ anno: Omit<AnnotationNormalized, 'target'> & {
273
+ target: string | W3CAnnotationTarget | Array<Reference<'ContentResource'>>;
274
+ },
275
+ langPrefs: readonly string[]
276
+ ): Annotation | undefined {
277
+ if (!anno.target) {
278
+ return;
279
+ }
280
+ // TODO: i18n?
281
+ const annoBody = anno.body.map((bodyRef) =>
282
+ vault.get<ContentResource>(bodyRef.id)
283
+ );
284
+ const creatorNames: Array<string> = annoBody
285
+ .map((body) => body.creator)
286
+ .filter((v: Creator | undefined): v is Creator => v !== undefined)
287
+ .map(creatorToString);
288
+ const modifiedDates: Array<number> = annoBody
289
+ .map((body) => body.modified)
290
+ .filter((v: string | undefined): v is string => v !== undefined)
291
+ .map((v: string) => new Date(v).getTime());
292
+ if (typeof anno.target === 'string') {
293
+ return;
294
+ }
295
+ const targets = Array.isArray(anno.target)
296
+ ? vault.get<Exclude<W3CAnnotationTarget, string>>(
297
+ anno.target.map((t) => t.id)
298
+ )
299
+ : anno.target;
300
+ const target = expandTarget(targets);
301
+ const markup = buildAnnotationMarkup(annoBody);
302
+ if (!markup) {
303
+ // TODO: Log?
304
+ throw `No valid textual content in annotation.`;
305
+ }
306
+ return {
307
+ id: anno.id,
308
+ target,
309
+ markup,
310
+ lastModified:
311
+ modifiedDates.length > 0
312
+ ? new Date(Math.max(...modifiedDates))
313
+ : undefined,
314
+ author: creatorNames.length > 0 ? creatorNames.join('; ') : undefined,
315
+ };
316
+ }
317
+
318
+ /** Convert Annotation HTML to PDF Markup */
319
+ function buildAnnotationMarkup(
320
+ bodies: Array<ContentResource>
321
+ ): string | undefined {
322
+ const parts: { [purpose: string]: Array<string> } = {};
323
+ for (const body of bodies) {
324
+ if (
325
+ body.type !== 'TextualBody' ||
326
+ (body.format !== 'text/plain' && body.format !== 'text/html') ||
327
+ body.value === undefined
328
+ ) {
329
+ continue;
330
+ }
331
+ let { purpose } = body;
332
+ if (Array.isArray(purpose)) {
333
+ purpose = purpose[0];
334
+ } else if (!purpose) {
335
+ purpose = 'no-purpose';
336
+ }
337
+ if (!parts[purpose]) {
338
+ parts[purpose] = [];
339
+ }
340
+ const value =
341
+ body.format === 'text/plain'
342
+ ? body.value
343
+ .replace(/&/g, '&amp;')
344
+ .replace(/</g, '&lt;')
345
+ .replace(/>/g, '&gt;')
346
+ : body.value;
347
+ parts[purpose].push(value);
348
+ }
349
+ if (Object.keys(parts).length === 0) {
350
+ return undefined;
351
+ }
352
+ const out: Array<string> = [];
353
+ for (const purpose of PURPOSE_ORDER) {
354
+ const purposeLabel = PURPOSE_LABELS[purpose];
355
+ if (!parts[purpose]) {
356
+ continue;
357
+ }
358
+ if (parts[purpose].length > 1) {
359
+ if (purposeLabel) {
360
+ out.push(`<p><b>${purposeLabel}:</b></p>`);
361
+ }
362
+ for (const part of parts[purpose]) {
363
+ // TODO: Convert HTML to PDF rich text
364
+ out.push(`<p>${part}</p>`);
365
+ }
366
+ } else {
367
+ out.push('<p>');
368
+ if (purposeLabel) {
369
+ out.push(`<b>${purposeLabel}:</b> `);
370
+ }
371
+ out.push(`${parts[purpose][0]}</p>`);
372
+ }
373
+ }
374
+ if (out.length === 0) {
375
+ return undefined;
376
+ }
377
+ return out.join('\n');
378
+ }
379
+
380
+ export interface CompatibilityReport {
381
+ compatibility: 'compatible' | 'incompatible' | 'degraded';
382
+ incompatibleElements: {
383
+ [canvasId: string]: Set<
384
+ | 'no-jpeg' // At least one image doesn't have a JPEG representation
385
+ | 'no-image' // Canvas does not have a single image annotation
386
+ | 'annotations' // Canvas has non-painting annotations
387
+ | 'unsupported-painting'
388
+ >;
389
+ };
390
+ }
391
+
392
+ export function checkCompatibility(
393
+ manifest: ManifestNormalized
394
+ ): CompatibilityReport | undefined {
395
+ const report = {
396
+ compatibility: 'compatible',
397
+ incompatibleElements: {},
398
+ };
399
+ for (const canvas of vault.get<CanvasNormalized>(manifest.items)) {
400
+ const paintingResources = vault
401
+ .get<AnnotationPageNormalized>(canvas.items)
402
+ .flatMap((ap) => vault.get<AnnotationNormalized>(ap.items))
403
+ .flatMap((a) => vault.get<ContentResource>(a.body.map(b => b.id)));
404
+ const nonPaintingAnnos = manifest.annotations;
405
+ // TODO: Check if canvas has an image
406
+ // TODO: Check if every painting annotation is an image with a JPEG available
407
+ // TODO: Check for the presence of non-painting annotations
408
+ }
409
+ return undefined;
410
+ }
411
+
412
+ /** Parse a IIIF target specification */
413
+ export function parseTarget(targetStr: string): {
414
+ x: number;
415
+ y: number;
416
+ width: number;
417
+ height: number;
418
+ } {
419
+ const [canvasId, fragment] = targetStr.split('#xywh=');
420
+ if (fragment) {
421
+ const [x, y, width, height] = fragment
422
+ .split(',')
423
+ .map((x) => parseInt(x, 10));
424
+ return { x, y, width, height };
425
+ } else {
426
+ const canvas = vault.get<CanvasNormalized>(canvasId);
427
+ // Draw to fit canvas
428
+ return { x: 0, y: 0, width: canvas.width, height: canvas.height };
429
+ }
430
+ }
431
+
432
+ export function getImageFormat(
433
+ image: ExternalWebResource | IIIFExternalWebResource
434
+ ): 'jpeg' | 'png' | 'unsupported' | undefined {
435
+ if (image.format === 'image/jpeg') {
436
+ return 'jpeg';
437
+ } else if (image.format === 'image/png') {
438
+ return 'png';
439
+ } else if (image.format === undefined) {
440
+ if (image.id?.endsWith('.jpg') || image.id?.endsWith('.jpeg')) {
441
+ return 'jpeg';
442
+ } else if (image.id?.endsWith('.png')) {
443
+ return 'png';
444
+ }
445
+ } else {
446
+ return 'unsupported';
447
+ }
448
+ }
449
+
450
+ type ImageResource = (ExternalWebResource | IIIFExternalWebResource) & {
451
+ type: 'Image';
452
+ };
453
+
454
+ /** Extract the image region from the selector(s) of a `SpecificResource`.
455
+ *
456
+ * Supports the `ImageApiSelector` and, for plain image resources, a media
457
+ * fragment `FragmentSelector` (`xywh=`). Returns an IIIF Image API region string.
458
+ */
459
+ export function getRegionFromSelector(
460
+ selector: any // eslint-disable-line @typescript-eslint/explicit-module-boundary-types
461
+ ): string | undefined {
462
+ const selectors: any[] = Array.isArray(selector) ? selector : [selector];
463
+ for (const sel of selectors) {
464
+ if (!sel || typeof sel !== 'object') {
465
+ continue;
466
+ }
467
+ if (sel.type === 'ImageApiSelector') {
468
+ if (sel.rotation || sel.size || sel.quality || sel.format) {
469
+ log.warn(
470
+ 'Only the region of an ImageApiSelector is supported, ignoring size, rotation, quality and format.'
471
+ );
472
+ }
473
+ if (typeof sel.region === 'string' && sel.region !== 'full') {
474
+ return sel.region;
475
+ }
476
+ } else if (
477
+ sel.type === 'FragmentSelector' &&
478
+ typeof sel.value === 'string' &&
479
+ sel.value.startsWith('xywh=')
480
+ ) {
481
+ // Media fragments: `xywh=[pixel:|percent:]x,y,w,h`, pixels are the default
482
+ const [, unit, coords] = sel.value.match(/^xywh=(?:(pixel|percent):)?(.+)$/) ?? [];
483
+ if (coords) {
484
+ return unit === 'percent' ? `pct:${coords}` : coords;
485
+ }
486
+ } else {
487
+ log.warn(`Unsupported selector type '${sel.type}', painting the whole image.`);
488
+ }
489
+ }
490
+ return undefined;
491
+ }
492
+
493
+ /** Resolve a painting annotation body to an image and the region painted from it.
494
+ *
495
+ * Handles both plain image bodies and `SpecificResource`s that select a part of an image.
496
+ * Bodies that are not images are ignored.
497
+ */
498
+ function resolveImageBody(
499
+ bodyRef: any
500
+ ): { resource: ImageResource; region?: string } | undefined {
501
+ if (bodyRef?.type === 'SpecificResource') {
502
+ // Normalized specific resources are not in the vault, they stay inline
503
+ // and only reference their source.
504
+ const sourceId =
505
+ typeof bodyRef.source === 'string' ? bodyRef.source : bodyRef.source?.id;
506
+ const resource = sourceId ? vault.get<ContentResource>(sourceId) : null;
507
+ if (resource?.type !== 'Image') {
508
+ return;
509
+ }
510
+ return {
511
+ resource: resource as ImageResource,
512
+ region: getRegionFromSelector(bodyRef.selector),
513
+ };
514
+ }
515
+ const resource = bodyRef?.id ? vault.get<ContentResource>(bodyRef.id) : null;
516
+ if (resource?.type !== 'Image') {
517
+ return;
518
+ }
519
+ return { resource: resource as ImageResource };
520
+ }
521
+
522
+ /** Get information about images on a Canvas. */
523
+ export function getImageInfos(canvas: CanvasNormalized): ImageInfo[] {
524
+ const imageInfos: ImageInfo[] = [];
525
+ const paintingAnnos = vault.get<AnnotationPageNormalized>(canvas.items)
526
+ .flatMap((ap) => vault.get<AnnotationNormalized>(ap.items));
527
+ for (const anno of paintingAnnos) {
528
+ const annoTarget = anno.target as any;
529
+ let target;
530
+ if (typeof annoTarget === 'string') {
531
+ target = parseTarget(annoTarget);
532
+ } else if (annoTarget.type === 'SpecificResource') {
533
+ // The parser normalizes `canvas#xywh=...` to a SpecificResource with a
534
+ // FragmentSelector, so the fragment has to be put back together.
535
+ const source = annoTarget.source;
536
+ const sourceId = typeof source === 'string' ? source : source.id;
537
+ const selectors: any[] = Array.isArray(annoTarget.selector)
538
+ ? annoTarget.selector
539
+ : [annoTarget.selector];
540
+ const fragment = selectors.find(
541
+ (s) => s?.type === 'FragmentSelector' && s.value?.startsWith('xywh=')
542
+ )?.value as string | undefined;
543
+ target = parseTarget(
544
+ fragment ? `${sourceId}#${fragment.replace('xywh=pixel:', 'xywh=')}` : sourceId
545
+ );
546
+ } else {
547
+ console.error(`Unsupported target type for annotation on canvas ${canvas.id}: '${annoTarget.type}'`);
548
+ continue;
549
+ }
550
+
551
+
552
+ for (const bodyRef of anno.body) {
553
+ const resolved = resolveImageBody(bodyRef);
554
+ if (!resolved) {
555
+ continue;
556
+ }
557
+ const { resource, region } = resolved;
558
+ imageInfos.push({
559
+ resource: resource as (
560
+ | ExternalWebResource
561
+ | IIIFExternalWebResource
562
+ ) & { type: 'Image' },
563
+ ...target,
564
+ ...(region ? { region } : {}),
565
+ format: getImageFormat(resource),
566
+ nativeWidth: (resource as any).width as number | undefined,
567
+ nativeHeight: (resource as any).height as number | undefined,
568
+ });
569
+ }
570
+ }
571
+
572
+ const choice = extractChoices(paintingAnnos);
573
+ if (choice?.type !== 'single-choice') {
574
+ // Return early if there are no choices available
575
+ return imageInfos;
576
+ }
577
+
578
+ for (const choiceItem of choice.items) {
579
+ const resource = vault.get<ContentResource>(choiceItem.id);
580
+ if (resource.type !== 'Image') {
581
+ continue;
582
+ }
583
+ imageInfos.push({
584
+ resource: resource as (ExternalWebResource | IIIFExternalWebResource) & {
585
+ type: 'Image';
586
+ },
587
+ // FIXME: Can't choice images have a location and rendering dimensions?
588
+ x: 0,
589
+ y: 0,
590
+ width: canvas.width,
591
+ height: canvas.height,
592
+ nativeWidth: (resource as any).width as number | undefined,
593
+ nativeHeight: (resource as any).height as number | undefined,
594
+ format: getImageFormat(resource),
595
+ choiceInfo: {
596
+ enabled: choiceItem.selected ?? false,
597
+ optional: true,
598
+ label: (resource as any).label,
599
+ visibleByDefault: choiceItem.selected ?? false,
600
+ },
601
+ });
602
+ }
603
+
604
+ return imageInfos;
605
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export type { Logger } from './log.js';
2
+ export { setLogger, ConsoleLogger } from './log.js';
3
+ export { fetchManifestJson } from './download.js';
4
+ export * from './convert.js';
5
+ export { vault } from './iiif.js';
6
+ export type { OptimizationParams } from './optimization.js'
7
+ export { default as version } from './version.js';