pdf-mapview 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,697 @@
1
+ #!/usr/bin/env node
2
+ import { resolve, join, extname, basename, dirname } from 'path';
3
+ import { cac } from 'cac';
4
+ import { randomUUID } from 'crypto';
5
+ import { writeFile, readFile, rm, mkdir } from 'fs/promises';
6
+ import sharp2 from 'sharp';
7
+ import { z } from 'zod';
8
+ import { createCanvas, DOMMatrix, ImageData, Path2D } from '@napi-rs/canvas';
9
+
10
+ // src/ingest/storage/memory.ts
11
+ function memoryStorageAdapter() {
12
+ const artifacts = [];
13
+ const record = (kind, path, contentType, bytes) => {
14
+ const artifact = {
15
+ kind,
16
+ path,
17
+ contentType,
18
+ size: bytes.byteLength
19
+ };
20
+ artifacts.push(artifact);
21
+ return artifact;
22
+ };
23
+ return {
24
+ async writeTile(args) {
25
+ return record("tile", `tiles/${args.z}/${args.x}/${args.y}.${args.ext}`, args.contentType, args.bytes);
26
+ },
27
+ async writeManifest(args) {
28
+ return record("manifest", args.path, args.contentType, args.bytes);
29
+ },
30
+ async writeAsset(args) {
31
+ return record(args.kind, args.path, args.contentType, args.bytes);
32
+ },
33
+ async finalize(_args) {
34
+ return {
35
+ artifacts: [...artifacts]
36
+ };
37
+ }
38
+ };
39
+ }
40
+
41
+ // src/shared/bytes.ts
42
+ function toUint8Array(input) {
43
+ if (input instanceof ArrayBuffer) {
44
+ return new Uint8Array(input);
45
+ }
46
+ return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
47
+ }
48
+
49
+ // src/ingest/pipeline/inspectInput.ts
50
+ async function inspectInput(input) {
51
+ if (typeof input === "string") {
52
+ const bytes = await readFile(input);
53
+ return {
54
+ bytes: toUint8Array(bytes),
55
+ originalFilename: basename(input),
56
+ ext: extname(input).slice(1).toLowerCase() || void 0
57
+ };
58
+ }
59
+ return {
60
+ bytes: toUint8Array(input)
61
+ };
62
+ }
63
+ async function normalizeImage(options) {
64
+ const { data, info } = await sharp2(options.bytes, { failOn: "none" }).rotate().resize({
65
+ width: options.maxDimension,
66
+ height: options.maxDimension,
67
+ fit: "inside",
68
+ withoutEnlargement: true
69
+ }).flatten({
70
+ background: options.background
71
+ }).png().toBuffer({ resolveWithObject: true });
72
+ return {
73
+ bytes: new Uint8Array(data),
74
+ width: info.width,
75
+ height: info.height,
76
+ mimeType: "image/png"
77
+ };
78
+ }
79
+ async function buildTilePyramid(options) {
80
+ const maxZoom = Math.max(
81
+ 0,
82
+ Math.ceil(Math.log2(Math.max(options.width, options.height) / options.tileSize))
83
+ );
84
+ const levels = [];
85
+ const tiles = [];
86
+ const source = Buffer.from(options.image);
87
+ for (let z3 = 0; z3 <= maxZoom; z3 += 1) {
88
+ const scale = 1 / 2 ** (maxZoom - z3);
89
+ const width = Math.max(1, Math.ceil(options.width * scale));
90
+ const height = Math.max(1, Math.ceil(options.height * scale));
91
+ const columns = Math.max(1, Math.ceil(width / options.tileSize));
92
+ const rows = Math.max(1, Math.ceil(height / options.tileSize));
93
+ levels.push({
94
+ z: z3,
95
+ width,
96
+ height,
97
+ columns,
98
+ rows,
99
+ scale
100
+ });
101
+ const levelBuffer = await sharp2(source, { failOn: "none" }).resize({
102
+ width,
103
+ height,
104
+ fit: "fill"
105
+ }).png().toBuffer();
106
+ for (let y = 0; y < rows; y += 1) {
107
+ for (let x = 0; x < columns; x += 1) {
108
+ const left = x * options.tileSize;
109
+ const top = y * options.tileSize;
110
+ const extractWidth = Math.min(options.tileSize, width - left);
111
+ const extractHeight = Math.min(options.tileSize, height - top);
112
+ const tileBuffer = await sharp2(levelBuffer, { failOn: "none" }).extract({
113
+ left,
114
+ top,
115
+ width: extractWidth,
116
+ height: extractHeight
117
+ }).toFormat(options.format, formatOptions(options.format, options.quality)).toBuffer();
118
+ tiles.push({
119
+ kind: "tile",
120
+ path: `tiles/${z3}/${x}/${y}.${extensionForFormat(options.format)}`,
121
+ contentType: contentTypeForFormat(options.format),
122
+ bytes: new Uint8Array(tileBuffer)
123
+ });
124
+ }
125
+ }
126
+ }
127
+ const previewBuffer = await sharp2(source, { failOn: "none" }).resize({
128
+ width: 1024,
129
+ height: 1024,
130
+ fit: "inside",
131
+ withoutEnlargement: true
132
+ }).webp({ quality: 80 }).toBuffer();
133
+ return {
134
+ levels,
135
+ tiles,
136
+ preview: {
137
+ kind: "preview",
138
+ path: "preview.webp",
139
+ contentType: "image/webp",
140
+ bytes: new Uint8Array(previewBuffer)
141
+ }
142
+ };
143
+ }
144
+ function formatOptions(format, quality) {
145
+ switch (format) {
146
+ case "jpeg":
147
+ return { quality };
148
+ case "png":
149
+ return {};
150
+ case "webp":
151
+ default:
152
+ return { quality };
153
+ }
154
+ }
155
+ function extensionForFormat(format) {
156
+ return format === "jpeg" ? "jpg" : format;
157
+ }
158
+ function contentTypeForFormat(format) {
159
+ switch (format) {
160
+ case "jpeg":
161
+ return "image/jpeg";
162
+ case "png":
163
+ return "image/png";
164
+ case "webp":
165
+ default:
166
+ return "image/webp";
167
+ }
168
+ }
169
+ var normalizedPointSchema = z.object({
170
+ x: z.number().finite().min(0).max(1),
171
+ y: z.number().finite().min(0).max(1)
172
+ });
173
+ var normalizedRectSchema = z.object({
174
+ x: z.number().finite().min(0).max(1),
175
+ y: z.number().finite().min(0).max(1),
176
+ width: z.number().finite().min(0).max(1),
177
+ height: z.number().finite().min(0).max(1)
178
+ });
179
+ var regionFeatureSchema = z.object({
180
+ id: z.string().min(1),
181
+ geometry: z.discriminatedUnion("type", [
182
+ z.object({
183
+ type: z.literal("polygon"),
184
+ points: z.array(normalizedPointSchema).min(3)
185
+ }),
186
+ z.object({
187
+ type: z.literal("rectangle"),
188
+ rect: normalizedRectSchema
189
+ }),
190
+ z.object({
191
+ type: z.literal("point"),
192
+ point: normalizedPointSchema,
193
+ radius: z.number().finite().positive().optional()
194
+ }),
195
+ z.object({
196
+ type: z.literal("label"),
197
+ point: normalizedPointSchema,
198
+ text: z.string().min(1)
199
+ })
200
+ ]),
201
+ label: z.string().optional(),
202
+ metadata: z.record(z.unknown()).optional()
203
+ });
204
+ var regionCollectionSchema = z.object({
205
+ type: z.literal("FeatureCollection"),
206
+ regions: z.array(regionFeatureSchema)
207
+ });
208
+
209
+ // src/shared/manifest.ts
210
+ var tileLevelSchema = z.object({
211
+ z: z.number().int().min(0),
212
+ width: z.number().int().positive(),
213
+ height: z.number().int().positive(),
214
+ columns: z.number().int().positive(),
215
+ rows: z.number().int().positive(),
216
+ scale: z.number().positive()
217
+ });
218
+ var manifestSchema = z.object({
219
+ version: z.literal(1),
220
+ kind: z.literal("pdf-map"),
221
+ id: z.string().min(1),
222
+ source: z.object({
223
+ type: z.union([z.literal("pdf"), z.literal("image")]),
224
+ originalFilename: z.string().optional(),
225
+ page: z.number().int().positive().optional(),
226
+ width: z.number().int().positive(),
227
+ height: z.number().int().positive(),
228
+ mimeType: z.string().optional()
229
+ }),
230
+ coordinateSpace: z.object({
231
+ normalized: z.literal(true),
232
+ width: z.number().int().positive(),
233
+ height: z.number().int().positive()
234
+ }),
235
+ tiles: z.object({
236
+ tileSize: z.number().int().positive(),
237
+ format: z.union([z.literal("webp"), z.literal("jpeg"), z.literal("png")]),
238
+ minZoom: z.number().int().min(0),
239
+ maxZoom: z.number().int().min(0),
240
+ pathTemplate: z.string().min(1),
241
+ levels: z.array(tileLevelSchema)
242
+ }),
243
+ view: z.object({
244
+ defaultCenter: z.tuple([
245
+ z.number().finite().min(0).max(1),
246
+ z.number().finite().min(0).max(1)
247
+ ]),
248
+ defaultZoom: z.number().finite(),
249
+ minZoom: z.number().finite(),
250
+ maxZoom: z.number().finite()
251
+ }),
252
+ overlays: z.object({
253
+ inline: regionCollectionSchema.optional(),
254
+ url: z.string().optional()
255
+ }).optional(),
256
+ assets: z.object({
257
+ preview: z.string().optional()
258
+ }).optional(),
259
+ metadata: z.object({
260
+ title: z.string().optional(),
261
+ createdAt: z.string().optional()
262
+ }).catchall(z.unknown()).optional()
263
+ });
264
+ function createManifest(input) {
265
+ return manifestSchema.parse({
266
+ version: 1,
267
+ kind: "pdf-map",
268
+ ...input
269
+ });
270
+ }
271
+
272
+ // src/ingest/pipeline/manifestBuilder.ts
273
+ function buildManifest(options) {
274
+ const minZoom = options.levels[0]?.z ?? 0;
275
+ const maxZoom = options.levels[options.levels.length - 1]?.z ?? 0;
276
+ return createManifest({
277
+ id: options.id,
278
+ source: {
279
+ type: options.sourceType,
280
+ originalFilename: options.originalFilename,
281
+ page: options.page,
282
+ width: options.width,
283
+ height: options.height,
284
+ mimeType: options.mimeType
285
+ },
286
+ coordinateSpace: {
287
+ normalized: true,
288
+ width: options.width,
289
+ height: options.height
290
+ },
291
+ tiles: {
292
+ tileSize: options.tileSize,
293
+ format: options.tileFormat,
294
+ minZoom,
295
+ maxZoom,
296
+ pathTemplate: withBaseUrl(options.baseUrl, `tiles/{z}/{x}/{y}.${options.tileFormat === "jpeg" ? "jpg" : options.tileFormat}`),
297
+ levels: options.levels
298
+ },
299
+ view: {
300
+ defaultCenter: [0.5, 0.5],
301
+ defaultZoom: 1,
302
+ minZoom: 0,
303
+ maxZoom: Math.max(maxZoom + 2, 6)
304
+ },
305
+ overlays: options.inlineOverlays || options.overlayUrl ? {
306
+ inline: options.inlineOverlays,
307
+ url: options.overlayUrl ? withBaseUrl(options.baseUrl, options.overlayUrl) : void 0
308
+ } : void 0,
309
+ assets: options.previewPath ? {
310
+ preview: withBaseUrl(options.baseUrl, options.previewPath)
311
+ } : void 0,
312
+ metadata: {
313
+ title: options.title,
314
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
315
+ }
316
+ });
317
+ }
318
+ function withBaseUrl(baseUrl, path) {
319
+ if (!baseUrl) {
320
+ return path;
321
+ }
322
+ if (/^https?:\/\//.test(baseUrl)) {
323
+ return new URL(path.replace(/^\//, ""), ensureTrailingSlash(baseUrl)).toString();
324
+ }
325
+ return joinRelativeUrl(baseUrl, path);
326
+ }
327
+ function ensureTrailingSlash(baseUrl) {
328
+ return baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
329
+ }
330
+ function joinRelativeUrl(baseUrl, path) {
331
+ const normalizedBase = ensureLeadingSlash(stripTrailingSlash(baseUrl));
332
+ const normalizedPath = stripLeadingSlash(path);
333
+ if (!normalizedPath) {
334
+ return normalizedBase || "/";
335
+ }
336
+ return normalizedBase ? `${normalizedBase}/${normalizedPath}` : `/${normalizedPath}`;
337
+ }
338
+ function stripLeadingSlash(value) {
339
+ return value.replace(/^\/+/, "");
340
+ }
341
+ function stripTrailingSlash(value) {
342
+ return value.replace(/\/+$/, "");
343
+ }
344
+ function ensureLeadingSlash(value) {
345
+ if (!value) {
346
+ return "";
347
+ }
348
+ return value.startsWith("/") ? value : `/${value}`;
349
+ }
350
+
351
+ // src/ingest/pipeline/writeArtifacts.ts
352
+ async function writeArtifacts(adapter, manifest, files) {
353
+ const uploaded = [];
354
+ for (const file of files) {
355
+ if (file.kind === "tile") {
356
+ const match = file.path.match(/^tiles\/(\d+)\/(\d+)\/(\d+)\.[^.]+$/);
357
+ if (!match) {
358
+ throw new Error(`Invalid tile path: ${file.path}`);
359
+ }
360
+ uploaded.push(
361
+ await adapter.writeTile({
362
+ z: Number(match[1]),
363
+ x: Number(match[2]),
364
+ y: Number(match[3]),
365
+ ext: file.path.split(".").pop() ?? "bin",
366
+ bytes: file.bytes,
367
+ contentType: file.contentType
368
+ })
369
+ );
370
+ continue;
371
+ }
372
+ if (file.kind === "manifest") {
373
+ uploaded.push(
374
+ await adapter.writeManifest({
375
+ path: file.path,
376
+ bytes: file.bytes,
377
+ contentType: "application/json"
378
+ })
379
+ );
380
+ continue;
381
+ }
382
+ if (!adapter.writeAsset) {
383
+ throw new Error(`Storage adapter does not support writing ${file.kind} assets.`);
384
+ }
385
+ uploaded.push(
386
+ await adapter.writeAsset({
387
+ kind: file.kind,
388
+ path: file.path,
389
+ bytes: file.bytes,
390
+ contentType: file.contentType
391
+ })
392
+ );
393
+ }
394
+ const storage = await adapter.finalize({
395
+ manifest,
396
+ artifacts: uploaded
397
+ });
398
+ return {
399
+ uploaded,
400
+ storage
401
+ };
402
+ }
403
+
404
+ // src/ingest/ingestImage.ts
405
+ async function ingestImage(options) {
406
+ const inspected = await inspectInput(options.input);
407
+ const normalized = await normalizeImage({
408
+ bytes: inspected.bytes,
409
+ maxDimension: options.maxDimension ?? 12288,
410
+ background: options.background ?? "#ffffff"
411
+ });
412
+ return ingestRasterizedImage(normalized, {
413
+ common: options,
414
+ id: options.id ?? defaultId(inspected.originalFilename ?? "image"),
415
+ title: options.title,
416
+ sourceType: "image",
417
+ originalFilename: inspected.originalFilename,
418
+ mimeType: normalized.mimeType
419
+ });
420
+ }
421
+ async function ingestRasterizedImage(normalized, input) {
422
+ const tileSize = input.common.tileSize ?? 256;
423
+ const tileFormat = input.common.tileFormat ?? "webp";
424
+ const tileQuality = input.common.tileQuality ?? 92;
425
+ const storage = input.common.storage ?? memoryStorageAdapter();
426
+ const pyramid = await buildTilePyramid({
427
+ image: normalized.bytes,
428
+ width: normalized.width,
429
+ height: normalized.height,
430
+ tileSize,
431
+ format: tileFormat,
432
+ quality: tileQuality
433
+ });
434
+ const overlayPayload = await resolveOverlayPayload(input.common.overlays);
435
+ const manifest = buildManifest({
436
+ id: input.id,
437
+ title: input.title,
438
+ sourceType: input.sourceType,
439
+ originalFilename: input.originalFilename,
440
+ page: input.page,
441
+ width: normalized.width,
442
+ height: normalized.height,
443
+ mimeType: input.mimeType ?? normalized.mimeType,
444
+ tileSize,
445
+ tileFormat,
446
+ levels: pyramid.levels,
447
+ baseUrl: input.common.baseUrl,
448
+ inlineOverlays: overlayPayload.inline,
449
+ overlayUrl: overlayPayload.url,
450
+ previewPath: pyramid.preview.path
451
+ });
452
+ const files = [...pyramid.tiles, pyramid.preview];
453
+ if (overlayPayload.file) {
454
+ files.push(overlayPayload.file);
455
+ }
456
+ files.push({
457
+ kind: "manifest",
458
+ path: "manifest.json",
459
+ contentType: "application/json",
460
+ bytes: new TextEncoder().encode(JSON.stringify(manifest, null, 2))
461
+ });
462
+ const { uploaded, storage: storageResult } = await writeArtifacts(storage, manifest, files);
463
+ return {
464
+ manifest,
465
+ width: normalized.width,
466
+ height: normalized.height,
467
+ tileCount: pyramid.tiles.length,
468
+ files,
469
+ uploaded,
470
+ warnings: [],
471
+ storage: storageResult
472
+ };
473
+ }
474
+ async function resolveOverlayPayload(input) {
475
+ if (!input) {
476
+ return {};
477
+ }
478
+ if (typeof input === "string") {
479
+ return {
480
+ url: input
481
+ };
482
+ }
483
+ const bytes = new TextEncoder().encode(JSON.stringify(input, null, 2));
484
+ if (bytes.byteLength < 64 * 1024) {
485
+ return {
486
+ inline: input
487
+ };
488
+ }
489
+ return {
490
+ url: "regions.json",
491
+ file: {
492
+ kind: "overlay",
493
+ path: "regions.json",
494
+ contentType: "application/json",
495
+ bytes
496
+ }
497
+ };
498
+ }
499
+ function defaultId(seed) {
500
+ const safe = seed.replace(/\.[^.]+$/, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
501
+ return safe || randomUUID();
502
+ }
503
+ async function rasterizePdf(options) {
504
+ installNodeCanvasGlobals();
505
+ const pdfjs = await import('pdfjs-dist/legacy/build/pdf.mjs');
506
+ const loadingTask = pdfjs.getDocument({
507
+ data: options.bytes,
508
+ useSystemFonts: true
509
+ });
510
+ const pdf = await loadingTask.promise;
511
+ const page = await pdf.getPage(options.page);
512
+ const viewport = page.getViewport({ scale: 1 });
513
+ const scale = resolveScale({
514
+ viewportWidth: viewport.width,
515
+ viewportHeight: viewport.height,
516
+ maxDimension: options.maxDimension,
517
+ rasterDpi: options.rasterDpi
518
+ });
519
+ const scaledViewport = page.getViewport({
520
+ scale: scale <= 0 ? 1 : scale
521
+ });
522
+ const canvas = createCanvas(Math.ceil(scaledViewport.width), Math.ceil(scaledViewport.height));
523
+ const context = canvas.getContext("2d");
524
+ context.fillStyle = options.background;
525
+ context.fillRect(0, 0, canvas.width, canvas.height);
526
+ await page.render({
527
+ canvasContext: context,
528
+ viewport: scaledViewport
529
+ }).promise;
530
+ const png = await canvas.encode("png");
531
+ await page.cleanup();
532
+ await pdf.cleanup();
533
+ await pdf.destroy();
534
+ return {
535
+ bytes: new Uint8Array(png),
536
+ width: canvas.width,
537
+ height: canvas.height,
538
+ mimeType: "image/png"
539
+ };
540
+ }
541
+ function installNodeCanvasGlobals() {
542
+ if (!("DOMMatrix" in globalThis)) {
543
+ globalThis.DOMMatrix = DOMMatrix;
544
+ }
545
+ if (!("ImageData" in globalThis)) {
546
+ globalThis.ImageData = ImageData;
547
+ }
548
+ if (!("Path2D" in globalThis)) {
549
+ globalThis.Path2D = Path2D;
550
+ }
551
+ }
552
+ function resolveScale(options) {
553
+ if (options.rasterDpi && Number.isFinite(options.rasterDpi) && options.rasterDpi > 0) {
554
+ return options.rasterDpi / 72;
555
+ }
556
+ return Math.min(
557
+ 1,
558
+ options.maxDimension / Math.max(options.viewportWidth, options.viewportHeight)
559
+ );
560
+ }
561
+
562
+ // src/ingest/ingestPdf.ts
563
+ async function ingestPdf(options) {
564
+ const inspected = await inspectInput(options.input);
565
+ const page = options.page ?? 1;
566
+ const rasterized = await rasterizePdf({
567
+ bytes: inspected.bytes,
568
+ page,
569
+ maxDimension: options.maxDimension ?? 12288,
570
+ rasterDpi: options.rasterDpi,
571
+ background: options.background ?? "#ffffff"
572
+ });
573
+ return ingestRasterizedImage(rasterized, {
574
+ common: options,
575
+ id: options.id ?? defaultId2(inspected.originalFilename ?? "pdf"),
576
+ title: options.title,
577
+ sourceType: "pdf",
578
+ originalFilename: inspected.originalFilename,
579
+ mimeType: "application/pdf",
580
+ page
581
+ });
582
+ }
583
+ function defaultId2(seed) {
584
+ const safe = seed.replace(/\.[^.]+$/, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
585
+ return safe || randomUUID();
586
+ }
587
+ function localStorageAdapter(options) {
588
+ const baseDir = resolve(options.baseDir);
589
+ const manifestName = options.manifestName ?? "manifest.json";
590
+ const artifacts = [];
591
+ let cleaned = false;
592
+ const ensureParent = async (filePath) => {
593
+ await mkdir(dirname(filePath), { recursive: true });
594
+ };
595
+ const ensureClean = async () => {
596
+ if (cleaned) {
597
+ return;
598
+ }
599
+ cleaned = true;
600
+ await rm(baseDir, { recursive: true, force: true });
601
+ };
602
+ const write = async (kind, relativePath, contentType, bytes) => {
603
+ await ensureClean();
604
+ const path = join(baseDir, relativePath);
605
+ await ensureParent(path);
606
+ await writeFile(path, bytes);
607
+ const artifact = {
608
+ kind,
609
+ path,
610
+ contentType,
611
+ size: bytes.byteLength
612
+ };
613
+ artifacts.push(artifact);
614
+ return artifact;
615
+ };
616
+ return {
617
+ async writeTile(args) {
618
+ return write(
619
+ "tile",
620
+ `tiles/${args.z}/${args.x}/${args.y}.${args.ext}`,
621
+ args.contentType,
622
+ args.bytes
623
+ );
624
+ },
625
+ async writeManifest(args) {
626
+ return write("manifest", manifestName, args.contentType, args.bytes);
627
+ },
628
+ async writeAsset(args) {
629
+ return write(args.kind, args.path, args.contentType, args.bytes);
630
+ },
631
+ async finalize(_args) {
632
+ return {
633
+ artifacts: [...artifacts]
634
+ };
635
+ }
636
+ };
637
+ }
638
+
639
+ // src/ingest/cli.ts
640
+ var cli = cac("pdf-mapview");
641
+ cli.command("ingest <input>", "Ingest a PDF or image into a tiled map manifest").option("--page <page>", "PDF page to ingest", {
642
+ default: 1
643
+ }).option("--id <id>", "Manifest id").option("--title <title>", "Manifest title").option("--out-dir <outDir>", "Write output to a local directory").option("--type <type>", "Force source type: pdf or image").option("--base-url <baseUrl>", "Base URL for manifest asset references").option("--adapter <adapter>", "Module path for a custom storage adapter factory").option("--adapter-export <name>", "Named export for the custom storage adapter", {
644
+ default: "default"
645
+ }).option("--tile-size <tileSize>", "Tile size: 256 or 512", {
646
+ default: 256
647
+ }).option("--format <format>", "Tile format: webp, jpeg, or png", {
648
+ default: "webp"
649
+ }).option("--quality <quality>", "Tile quality", {
650
+ default: 92
651
+ }).option("--raster-dpi <rasterDpi>", "Rasterize PDF pages at a fixed DPI").option("--max-dimension <maxDimension>", "Max raster dimension", {
652
+ default: 12288
653
+ }).action(async (input, flags) => {
654
+ const outDir = flags.outDir ? resolve(String(flags.outDir)) : void 0;
655
+ const storage = flags.adapter ? await loadCustomAdapter(String(flags.adapter), String(flags.adapterExport)) : outDir ? localStorageAdapter({
656
+ baseDir: outDir}) : void 0;
657
+ const type = String(flags.type ?? inferType(String(input)));
658
+ const common = {
659
+ id: flags.id ? String(flags.id) : void 0,
660
+ title: flags.title ? String(flags.title) : void 0,
661
+ tileSize: Number(flags.tileSize),
662
+ tileFormat: String(flags.format),
663
+ tileQuality: Number(flags.quality),
664
+ rasterDpi: flags.rasterDpi ? Number(flags.rasterDpi) : void 0,
665
+ maxDimension: Number(flags.maxDimension),
666
+ baseUrl: flags.baseUrl ? String(flags.baseUrl) : void 0,
667
+ storage
668
+ };
669
+ const result = type === "pdf" ? await ingestPdf({
670
+ ...common,
671
+ input: String(input),
672
+ page: Number(flags.page)
673
+ }) : await ingestImage({
674
+ ...common,
675
+ input: String(input)
676
+ });
677
+ process.stdout.write(`${JSON.stringify(result.manifest, null, 2)}
678
+ `);
679
+ });
680
+ cli.help();
681
+ cli.parse();
682
+ function inferType(input) {
683
+ return /\.pdf$/i.test(input) ? "pdf" : "image";
684
+ }
685
+ async function loadCustomAdapter(modulePath, exportName) {
686
+ const mod = await import(resolve(modulePath));
687
+ const candidate = mod[exportName];
688
+ if (typeof candidate === "function") {
689
+ return candidate();
690
+ }
691
+ if (candidate && typeof candidate === "object") {
692
+ return candidate;
693
+ }
694
+ throw new Error(`Unable to load storage adapter export "${exportName}" from ${modulePath}`);
695
+ }
696
+ //# sourceMappingURL=cli.js.map
697
+ //# sourceMappingURL=cli.js.map