@imgly/plugin-print-ready-pdfs-web 1.87.0-nightly.20261113 → 1.87.0-rc.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.
|
Binary file
|
|
Binary file
|
package/dist/index.mjs
CHANGED
|
@@ -83,5 +83,5 @@ ${i}
|
|
|
83
83
|
[ /Creator (${p}) /DOCINFO pdfmark
|
|
84
84
|
[ /CreationDate (${t.pdfDate}) /DOCINFO pdfmark
|
|
85
85
|
[ /ModDate (${t.pdfDate}) /DOCINFO pdfmark
|
|
86
|
-
[ /Trapped /False /DOCINFO pdfmark${i}`}function C(e,t){let n=[`-sOutputFile=${t.outputPath}`,t.pdfxDefPath,t.inputPath,t.postDocinfoPath];if(e.ghostscriptArgs&&e.ghostscriptArgs.length>0)return[...e.ghostscriptArgs,...n];let r=e.outputStandard===`PDF/X-4`,i=[`-dBATCH`,`-dNOPAUSE`,`-sDEVICE=pdfwrite`,r?`-dCompatibilityLevel=1.6`:`-dCompatibilityLevel=1.4`,`-dWriteObjStms=false`,`-dWriteXRefStm=false`,`-dPDFSETTINGS=/prepress`,`-dSetPageSize=false`,`-dAutoRotatePages=/None`];return r&&i.push(`-dCompressStreams=false`),!r&&e.flattenTransparency!==!1&&i.push(`-dHaveTransparency=false`),t.isCMYKProfile?i.push(`-sColorConversionStrategy=CMYK`,`-dProcessColorModel=/DeviceCMYK`,`-dConvertCMYKImagesToRGB=false`):i.push(`-sColorConversionStrategy=RGB`),[...i,...n]}async function w(e,t){let n=t.maxInputSize===void 0?104857600:t.maxInputSize;if(!Number.isSafeInteger(n)||n<=0)throw Error(`maxInputSize must be a positive safe integer in bytes`);let r={outputStandard:`PDF/X-4`,...t,maxInputSize:n};if(Array.isArray(e)){if(e.length===0)return[];let t=[];for(let n=0;n<e.length;n++)try{let i=await D(e[n],r);t.push(i)}catch(t){let r=Error(`Failed to convert PDF ${n+1} of ${e.length}: ${t instanceof Error?t.message:String(t)}`,{cause:t});throw t instanceof Error&&`code`in t&&Object.assign(r,{code:t.code,...`diagnostics`in t&&{diagnostics:t.diagnostics},...`exitCode`in t&&{exitCode:t.exitCode}}),r}return t}return D(e,r)}function T(e){switch(e){case`
|
|
86
|
+
[ /Trapped /False /DOCINFO pdfmark${i}`}function C(e,t){let n=[`-sOutputFile=${t.outputPath}`,t.pdfxDefPath,t.inputPath,t.postDocinfoPath];if(e.ghostscriptArgs&&e.ghostscriptArgs.length>0)return[...e.ghostscriptArgs,...n];let r=e.outputStandard===`PDF/X-4`,i=[`-dBATCH`,`-dNOPAUSE`,`-sDEVICE=pdfwrite`,r?`-dCompatibilityLevel=1.6`:`-dCompatibilityLevel=1.4`,`-dWriteObjStms=false`,`-dWriteXRefStm=false`,`-dPDFSETTINGS=/prepress`,`-dSetPageSize=false`,`-dAutoRotatePages=/None`];return r&&i.push(`-dCompressStreams=false`),!r&&e.flattenTransparency!==!1&&i.push(`-dHaveTransparency=false`),t.isCMYKProfile?i.push(`-sColorConversionStrategy=CMYK`,`-dProcessColorModel=/DeviceCMYK`,`-dConvertCMYKImagesToRGB=false`):i.push(`-sColorConversionStrategy=RGB`),[...i,...n]}async function w(e,t){let n=t.maxInputSize===void 0?104857600:t.maxInputSize;if(!Number.isSafeInteger(n)||n<=0)throw Error(`maxInputSize must be a positive safe integer in bytes`);let r={outputStandard:`PDF/X-4`,...t,maxInputSize:n};if(Array.isArray(e)){if(e.length===0)return[];let t=[];for(let n=0;n<e.length;n++)try{let i=await D(e[n],r);t.push(i)}catch(t){let r=Error(`Failed to convert PDF ${n+1} of ${e.length}: ${t instanceof Error?t.message:String(t)}`,{cause:t});throw t instanceof Error&&`code`in t&&Object.assign(r,{code:t.code,...`diagnostics`in t&&{diagnostics:t.diagnostics},...`exitCode`in t&&{exitCode:t.exitCode}}),r}return t}return D(e,r)}function T(e){switch(e){case`GRACoL2013_CRPC6.icc`:return new URL(`./GRACoL2013_CRPC6.icc`,import.meta.url).href;case`GRACoL2006_Coated1v2.icc`:return new URL(`./GRACoL2006_Coated1v2.icc`,import.meta.url).href;case`sRGB_IEC61966-2-1.icc`:return new URL(`./sRGB_IEC61966-2-1.icc`,import.meta.url).href;default:return new URL(`./ISOcoated_v2_eci.icc`,import.meta.url).href}}function E(e,t){return w(e,{outputStandard:`PDF/X-3`,...t})}async function D(e,t){if(!(e instanceof Blob))throw Error(`Input must be a Blob`);if(e.size===0)throw Error(`Input PDF is empty`);if(e.size>t.maxInputSize)throw Error(`Input PDF too large (${e.size} bytes). Maximum: ${t.maxInputSize} bytes`);if(!t.outputProfile)throw Error(`outputProfile is required. Must be one of: "gracol", "fogra39", "srgb", "custom"`);let n=[`gracol`,`fogra39`,`srgb`,`custom`];if(!n.includes(t.outputProfile))throw Error(`Invalid outputProfile "${t.outputProfile}". Must be one of: ${n.join(`, `)}`);if(t.outputProfile===`custom`&&!t.customProfile)throw Error(`customProfile Blob is required when outputProfile is "custom"`);if(t.customProfile&&!(t.customProfile instanceof Blob))throw Error(`customProfile must be a Blob`);if(!await s.validatePDF(e))throw Error(`Invalid PDF format`);let r=t.runtime??o(),i={signal:t.signal,timeoutMs:t.timeoutMs},{version:a}=await r.preload(i);new f(`PDFXConversion`).info(`Converting PDF in Ghostscript worker`);let c={};if(c[`input.pdf`]=await s.toUint8Array(e),t.outputProfile===`custom`&&t.customProfile)c[`custom.icc`]=await s.toUint8Array(t.customProfile);else if(t.outputProfile!==`custom`){let e=j(t),n=typeof process<`u`&&process.versions?.node!=null,r;if(n){let t=process.env.VITEST===`true`||!1,n=Function(`s`,`return import(s)`),i=t?e=>import(e):n,{readFileSync:a}=await i(`fs`),{fileURLToPath:o}=await i(`url`),{dirname:s,join:c}=await i(`path`),l=a(c(s(o(import.meta.url)),e.file));r=new Blob([l],{type:`application/vnd.iccprofile`})}else{let n=T(e.file),i=await fetch(n,{signal:t.signal});if(!i.ok)throw Error(`Failed to load ICC profile ${e.file}: ${i.statusText}`);r=await i.blob()}c[e.file]=await s.toUint8Array(r)}let l,u,d;if(t.outputProfile===`custom`)l=`/work/custom.icc`,u=t.outputConditionIdentifier||`Custom Profile`,d=t.outputCondition||`Custom ICC Profile`;else{let e=j(t);l=`/work/${e.file}`,u=t.outputConditionIdentifier||e.identifier,d=t.outputCondition||e.info}let p=c[l.slice(6)],m=p.slice(16,20),g=String.fromCharCode(...m).trim()===`CMYK`,_=t.embedICCProfile!==!1,v=_?Array.from(p).map(e=>e.toString(16).padStart(2,`0`)).join(``):``,y=h(/* @__PURE__ */ new Date);if(typeof a!=`string`||a.length===0)throw Error(`Ghostscript module reported no version; cannot mirror the Producer into XMP`);c[`pdfx_def.ps`]=x(t,{iccProfileHex:v,outputConditionIdentifier:u,outputCondition:d,embedICCProfile:_,timestamps:y,docId:O(),producer:`GPL Ghostscript ${a}`}),c[`pdfx_post.ps`]=S(t,y,_);let b=C(t,{isCMYKProfile:g,outputPath:`/work/output.pdf`,pdfxDefPath:`/work/pdfx_def.ps`,inputPath:`/work/input.pdf`,postDocinfoPath:`/work/pdfx_post.ps`}),w=await r.run({files:c,args:b,outputFiles:[`output.pdf`]},{...i,maxOutputBytes:t.maxOutputBytes??2**53-1});return new Blob([new Uint8Array(w.files[`output.pdf`])],{type:`application/pdf`})}function O(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return(e===`x`?t:t&3|8).toString(16)})}const k={gracol:{file:`GRACoL2013_CRPC6.icc`,identifier:`CGATS 21.2`,info:`GRACoL 2013 CRPC6`},fogra39:{file:`ISOcoated_v2_eci.icc`,identifier:`FOGRA39`,info:`ISO Coated v2 (ECI)`},srgb:{file:`sRGB_IEC61966-2-1.icc`,identifier:`sRGB IEC61966-2.1`,info:`sRGB IEC61966-2.1`}},A={file:`GRACoL2006_Coated1v2.icc`,identifier:`CGATS TR 006`,info:`GRACoL 2006 Coated #1`};function j(e){return e.outputProfile===`gracol`&&e.outputStandard===`PDF/X-3`?A:k[e.outputProfile]}export{f as Logger,w as convertToPDFX,E as convertToPDFX3};
|
|
87
87
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["runtime","importRetry","load","isNode","url","module","error","conversionError","message","loadForOperation","options","signal","timeoutMs","started","timeoutError","abort","timer","cancelled","reject","loaded","remaining","adapter","job","previous","getDefaultConversionRuntime","BlobUtils","blob","buffer","reader","resolve","data","pdfHeader","i","_typeof","o","toPrimitive","t","e","r","toPropertyKey","_defineProperty","Logger","component","level","levelOrder","entry","prefix","logMessage","CREATOR_TOOL","resolveTitle","match","formatPDFXTimestamps","date","p","n","y","mo","d","h","mi","escapePSString","value","escapeXML","utf8ToHex","bytes","hex","b","utf16beHex","buildPDFX4XMPPacket","titleX","title","nowX","timestamps","docIdX","docId","producer","generatePDFXDef","ctx","isX4","headerComment","distillerPrologue","xmpReplaceBlock","generatePostDocinfo","x3ConformanceLine","embedICCProfile","buildGhostscriptArgs","trailing","args","convertToPDFX","maxInputSize","resolvedOptions","input","results","converted","convertToPDFXSingle","batchError","bundledProfileURL","profile","convertToPDFX3","inputPDF","validProfiles","operationOptions","files","profileInfo","PROFILE_PRESETS","profileBlob","isTestEnv","indirectImport","dynamicImport","s","profileData","readFileSync","join","dirname","fileURLToPath","profileUrl","profileResponse","iccProfilePath","outputConditionIdentifier","outputCondition","preset","iccData","colorSpaceBytes","isCMYKProfile","iccHex","version","generateDocumentId","gsArgs","result","c"],"sources":["../src/standalone-runtime.ts","../src/utils/blob-utils.ts","../src/utils/logger.ts","../src/pdfx-def.ts","../src/pdfx-args.ts","../src/pdfx.ts"],"sourcesContent":["import type {\n ConversionRuntime,\n OperationOptions,\n ConversionJob,\n RunOptions,\n ConversionErrorCode,\n} from '@imgly/pdf-conversion-utils';\n\nlet runtime: Promise<ConversionRuntime> | undefined;\nlet importRetry = 0;\n\nfunction load(): Promise<ConversionRuntime> {\n if (!runtime) {\n const isNode =\n typeof process !== 'undefined' && process.versions?.node != null;\n const url = new URL(\n isNode ? './pdf-conversion/node.js' : './pdf-conversion/browser.js',\n import.meta.url\n );\n // Browsers cache failed module imports, so only actual load failures get a new URL.\n if (importRetry > 0) {\n url.searchParams.set('retry', String(importRetry));\n }\n runtime = import(/* webpackIgnore: true */ url.href).then(\n (module) => module.getDefaultConversionRuntime() as ConversionRuntime,\n (error) => {\n importRetry += 1;\n runtime = undefined;\n throw error;\n }\n );\n }\n return runtime;\n}\n\nfunction conversionError(message: string, code: ConversionErrorCode): Error {\n // Preserve the runtime error shape without loading its module to cancel.\n return Object.assign(new Error(message), {\n name: 'ConversionError',\n code,\n diagnostics: [],\n });\n}\n\nasync function loadForOperation(\n options: OperationOptions = {}\n): Promise<{ loaded: ConversionRuntime; timeoutMs: number }> {\n const { signal } = options;\n if (signal?.aborted) {\n throw conversionError('Conversion was aborted', 'ABORTED');\n }\n const timeoutMs = options.timeoutMs ?? 30_000;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw conversionError(\n 'timeoutMs must be a positive safe integer',\n 'INVALID_INPUT'\n );\n }\n if (timeoutMs > 2 ** 31 - 1) {\n throw conversionError(\n `timeoutMs must not exceed ${2 ** 31 - 1}`,\n 'INVALID_INPUT'\n );\n }\n\n const started = performance.now();\n const timeoutError = () =>\n conversionError(`Conversion timed out after ${timeoutMs}ms`, 'TIMEOUT');\n let abort!: () => void;\n let timer!: ReturnType<typeof setTimeout>;\n const cancelled = new Promise<never>((_, reject) => {\n abort = () => reject(conversionError('Conversion was aborted', 'ABORTED'));\n signal?.addEventListener('abort', abort, { once: true });\n timer = setTimeout(() => reject(timeoutError()), timeoutMs);\n });\n try {\n // Only stop this caller's wait; other callers still share the module load.\n const loaded = await Promise.race([load(), cancelled]);\n const remaining = Math.ceil(timeoutMs - (performance.now() - started));\n if (remaining <= 0) throw timeoutError();\n return { loaded, timeoutMs: remaining };\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n }\n}\n\n// The standalone CDN entry resolves the same runtime locally without a bare npm import.\nconst adapter: ConversionRuntime = {\n async preload(options?: OperationOptions) {\n const { loaded, timeoutMs } = await loadForOperation(options);\n return loaded.preload({ ...options, timeoutMs });\n },\n async run(job: ConversionJob, options?: RunOptions) {\n const { loaded, timeoutMs } = await loadForOperation(options);\n return loaded.run(job, { ...options, timeoutMs });\n },\n dispose() {\n const previous = runtime;\n runtime = undefined;\n void previous?.then(\n (loaded) => loaded.dispose(),\n () => undefined\n );\n },\n};\n\nexport function getDefaultConversionRuntime(): ConversionRuntime {\n return adapter;\n}\n","export class BlobUtils {\n static async toUint8Array(blob: Blob): Promise<Uint8Array> {\n if (blob.arrayBuffer) {\n const buffer = await blob.arrayBuffer();\n return new Uint8Array(buffer);\n }\n\n // Fallback for older browsers\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => {\n if (reader.result instanceof ArrayBuffer) {\n resolve(new Uint8Array(reader.result));\n } else {\n reject(new Error('Failed to read blob as ArrayBuffer'));\n }\n };\n reader.onerror = () => reject(reader.error);\n reader.readAsArrayBuffer(blob);\n });\n }\n\n static async validatePDF(blob: Blob): Promise<boolean> {\n try {\n const data = await this.toUint8Array(blob);\n\n // Check PDF magic number\n const pdfHeader = new Uint8Array([0x25, 0x50, 0x44, 0x46]); // %PDF\n\n if (data.length < 4) {\n return false;\n }\n\n for (let i = 0; i < 4; i++) {\n if (data[i] !== pdfHeader[i]) {\n return false;\n }\n }\n\n return true;\n } catch {\n return false;\n }\n }\n}\n","/* eslint-disable no-console */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface LogEntry {\n timestamp: number;\n level: LogLevel;\n component: string;\n message: string;\n data?: any;\n}\n\nexport class Logger {\n private static globalLogLevel: LogLevel = 'warn';\n\n private static logs: LogEntry[] = [];\n\n private static maxLogs = 1000;\n\n constructor(private component: string) {}\n\n static setLogLevel(level: LogLevel): void {\n Logger.globalLogLevel = level;\n }\n\n static getLogs(): LogEntry[] {\n return [...Logger.logs];\n }\n\n static clearLogs(): void {\n Logger.logs = [];\n }\n\n debug(message: string, data?: any): void {\n this.log('debug', message, data);\n }\n\n info(message: string, data?: any): void {\n this.log('info', message, data);\n }\n\n warn(message: string, data?: any): void {\n this.log('warn', message, data);\n }\n\n error(message: string, data?: any): void {\n this.log('error', message, data);\n }\n\n private log(level: LogLevel, message: string, data?: any): void {\n const levelOrder: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n if (levelOrder[level] < levelOrder[Logger.globalLogLevel]) {\n return;\n }\n\n const entry: LogEntry = {\n timestamp: Date.now(),\n level,\n component: this.component,\n message,\n data,\n };\n\n Logger.logs.push(entry);\n\n // Keep logs under the limit\n if (Logger.logs.length > Logger.maxLogs) {\n Logger.logs = Logger.logs.slice(-Logger.maxLogs);\n }\n\n // Console output\n const prefix = `[${new Date().toISOString()}] [${level.toUpperCase()}] [${\n this.component\n }]`;\n const logMessage = data ? `${message} ${JSON.stringify(data)}` : message;\n\n switch (level) {\n case 'debug':\n console.debug(prefix, logMessage);\n break;\n case 'info':\n console.info(prefix, logMessage);\n break;\n case 'warn':\n console.warn(prefix, logMessage);\n break;\n case 'error':\n console.error(prefix, logMessage);\n break;\n default:\n // All log levels handled above\n break;\n }\n }\n}\n","import type { PDFXOptions } from './types/pdfx';\n\n/** Value written to DocInfo `/Creator` and XMP `xmp:CreatorTool`. */\nconst CREATOR_TOOL = 'IMG.LY';\n\n/**\n * Resolve the document title once for BOTH metadata stores. Lone surrogates\n * and XML-illegal control characters would desync or corrupt the XMP side,\n * so they are repaired/stripped before either encoding sees the value.\n */\nfunction resolveTitle(options: PDFXOptions): string {\n const sanitized = (options.title || '')\n // Pairs match first and stay; any surrogate left over is unpaired. No lookbehind: Safari 15.6.\n .replace(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDFFF]/g, (match) =>\n match.length === 2 ? match : '�'\n )\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g, '');\n return sanitized || 'Untitled';\n}\n\n/**\n * One instant rendered in both metadata date formats. PDF/X-4 requires the\n * DocInfo dates and the XMP dates to describe the same time, so both strings\n * must always be derived from the same `Date` via `formatPDFXTimestamps`.\n */\nexport interface PDFXTimestamps {\n /** PDF date string for DOCINFO pdfmarks, e.g. `D:20260722140113+00'00'` */\n pdfDate: string;\n /** ISO-8601 string for the XMP packet, e.g. `2026-07-22T14:01:13+00:00` */\n xmpDate: string;\n}\n\n/**\n * Render `date` at second precision in UTC. Sub-second precision is dropped\n * deliberately: the PDF date format has none, and a fractional part in the\n * XMP value would break the Info↔XMP equivalence preflight checks.\n */\nexport function formatPDFXTimestamps(date: Date): PDFXTimestamps {\n if (Number.isNaN(date.getTime())) {\n throw new Error('formatPDFXTimestamps: invalid Date');\n }\n const p = (n: number) => String(n).padStart(2, '0');\n const y = date.getUTCFullYear();\n const mo = p(date.getUTCMonth() + 1);\n const d = p(date.getUTCDate());\n const h = p(date.getUTCHours());\n const mi = p(date.getUTCMinutes());\n const s = p(date.getUTCSeconds());\n return {\n pdfDate: `D:${y}${mo}${d}${h}${mi}${s}+00'00'`,\n xmpDate: `${y}-${mo}-${d}T${h}:${mi}:${s}+00:00`,\n };\n}\n\n/**\n * Escape a string for use inside a parens-delimited PostScript string.\n * Only `(`, `)`, `\\` need escaping; XML angle brackets and ampersands pass\n * through untouched (PostScript doesn't interpret them).\n */\nfunction escapePSString(value: string): string {\n return value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\(/g, '\\\\(')\n .replace(/\\)/g, '\\\\)');\n}\n\n/**\n * XML-escape a string for use inside element content or quoted attribute\n * values. Covers the five canonical XML entities.\n */\nfunction escapeXML(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Hex-encode a UTF-8 string for use inside a pdfmark `<...>` hex stream\n * literal. PostScript hex strings are case-insensitive; we emit lowercase\n * to match the rest of the pdfmark output.\n */\nfunction utf8ToHex(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let hex = '';\n for (const b of bytes) {\n hex += b.toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/**\n * Encode a string as a BOM-prefixed UTF-16BE hex string for pdfmark text\n * values — a parens literal would be read as PDFDocEncoding and garble\n * non-ASCII titles.\n */\nfunction utf16beHex(value: string): string {\n let hex = 'FEFF';\n for (let i = 0; i < value.length; i++) {\n hex += value.charCodeAt(i).toString(16).toUpperCase().padStart(4, '0');\n }\n return hex;\n}\n\n/**\n * Build the strict PDF/X-4 XMP packet body that fully replaces GS's\n * auto-generated XMP. Preflight checks `pdfxid:GTS_PDFXVersion` specifically;\n * older validators (callas, GS) read `pdfx:GTS_PDFXVersion` — we emit both.\n * `xmpMM:DocumentID`, `RenditionClass`, and `VersionID` round out the entries\n * Acrobat flags as missing on a non-strict X-4.\n *\n * GS's legacy auto-XMP uses the `xapMM` prefix which strict Acrobat Preflight\n * rejects. Replacing the whole packet via the Catalog.Metadata pdfmark\n * bypasses that.\n *\n * Every value that also exists in the final Info dictionary must stay\n * equivalent (PDF/X-4): title/dates/creator match the `generatePostDocinfo`\n * pdfmarks; producer mirrors pdfwrite's own Info stamp.\n */\nfunction buildPDFX4XMPPacket(\n title: string,\n timestamps: PDFXTimestamps,\n docId: string,\n producer: string\n): string {\n const titleX = escapeXML(title);\n const nowX = escapeXML(timestamps.xmpDate);\n const docIdX = escapeXML(docId);\n const producerX = escapeXML(producer);\n // U+FEFF after `begin=\"` is the canonical XMP packet BOM marker.\n // eslint-disable-next-line no-irregular-whitespace\n return `<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\"\n xmlns:pdfx=\"http://ns.adobe.com/pdfx/1.3/\"\n xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\"\n xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n <pdfx:GTS_PDFXVersion>PDF/X-4</pdfx:GTS_PDFXVersion>\n <pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>\n <pdf:Trapped>False</pdf:Trapped>\n <pdf:Producer>${producerX}</pdf:Producer>\n <xmp:CreateDate>${nowX}</xmp:CreateDate>\n <xmp:ModifyDate>${nowX}</xmp:ModifyDate>\n <xmp:MetadataDate>${nowX}</xmp:MetadataDate>\n <xmp:CreatorTool>${CREATOR_TOOL}</xmp:CreatorTool>\n <dc:format>application/pdf</dc:format>\n <dc:title>\n <rdf:Alt>\n <rdf:li xml:lang=\"x-default\">${titleX}</rdf:li>\n </rdf:Alt>\n </dc:title>\n <xmpMM:DocumentID>uuid:${docIdX}</xmpMM:DocumentID>\n <xmpMM:RenditionClass>default</xmpMM:RenditionClass>\n <xmpMM:VersionID>1</xmpMM:VersionID>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>`;\n}\n\nexport interface PDFXDefContext {\n iccProfileHex: string;\n outputConditionIdentifier: string;\n outputCondition: string;\n embedICCProfile: boolean;\n timestamps: PDFXTimestamps;\n docId: string;\n /** Producer string pdfwrite stamps into DocInfo, e.g. `GPL Ghostscript 10.03.1`. */\n producer: string;\n}\n\nexport function generatePDFXDef(\n options: PDFXOptions,\n ctx: PDFXDefContext\n): string {\n // Minimal definition when ICC embedding is disabled: no PDF/X conformance\n // markers and no OutputIntent. DOCINFO entries live in the post-input file.\n if (!ctx.embedICCProfile) {\n return `%!\n% PDF Definition File (ICC embedding disabled)`;\n }\n\n const isX4 = options.outputStandard === 'PDF/X-4';\n const headerComment = isX4\n ? '% PDF/X-4 Definition File'\n : '% PDF/X-3 Definition File';\n\n // X-4 strict conformance: remove transfer functions and halftones globally\n // via setdistillerparams. This must run before any pdfmark so it applies\n // to the full pdfwrite session. Strips the inherited /TR and /HT references\n // Acrobat Preflight reports as hundreds of instances on customer files.\n const distillerPrologue = isX4\n ? '<< /TransferFunctionInfo /Remove /HalftoneInfo /Remove >> setdistillerparams\\n'\n : '';\n\n // X-4 strict conformance: write our own XMP packet and attach it to the\n // Catalog via the Metadata pdfmark. This fully replaces GS's auto-generated\n // XMP (which uses the legacy `xapMM` prefix Acrobat Preflight rejects) and\n // gives us complete control over the entries Preflight checks.\n const xmpReplaceBlock = isX4\n ? `\n\n% Strict PDF/X-4 XMP packet (replaces GS's auto-generated XMP)\n[/_objdef {Metadata} /type /stream /OBJ pdfmark\n[{Metadata} <</Type /Metadata /Subtype /XML>> /PUT pdfmark\n[{Metadata} <${utf8ToHex(\n buildPDFX4XMPPacket(\n resolveTitle(options),\n ctx.timestamps,\n ctx.docId,\n ctx.producer\n )\n )}> /PUT pdfmark\n[{Catalog} <</Metadata {Metadata}>> /PUT pdfmark`\n : '';\n\n return `%!\n${headerComment}\n${distillerPrologue}\n% Supply missing print bounds after each page's size and rotation are installed.\n/pdfshowpage_setpage [\n /pdfshowpage_setpage load /exec load\n {\n dup /TrimBox known not 1 index /ArtBox known not and {\n dup /CropBox known {\n gsave newpath\n dup /CropBox get aload pop moveto lineto\n matrix defaultmatrix setmatrix pathbbox\n 4 array astore grestore\n } {\n [0 0 currentpagedevice /PageSize get aload pop]\n } ifelse\n [/TrimBox 3 -1 roll /PAGE pdfmark\n } if\n } /exec load\n] cvx def\n\n% Embed ICC profile as hex stream\n[/_objdef {icc_PDFX} /type /stream /OBJ pdfmark\n[{icc_PDFX} <</N 4>> /PUT pdfmark\n[{icc_PDFX} <${ctx.iccProfileHex}> /PUT pdfmark\n\n% Define OutputIntent with embedded ICC profile\n[/_objdef {OutputIntent_PDFX} /type /dict /OBJ pdfmark\n[{OutputIntent_PDFX} <<\n /Type /OutputIntent\n /S /GTS_PDFX\n /OutputCondition (${escapePSString(ctx.outputCondition)})\n /OutputConditionIdentifier (${escapePSString(ctx.outputConditionIdentifier)})\n /RegistryName (http://www.color.org)\n /DestOutputProfile {icc_PDFX}\n>> /PUT pdfmark\n\n% Add OutputIntent to Catalog\n[{Catalog} <</OutputIntents [{OutputIntent_PDFX}]>> /PUT pdfmark${xmpReplaceBlock}`;\n}\n\n/**\n * DOCINFO pdfmark file that runs AFTER the input PDF. Ghostscript merges the\n * input's Info dictionary during interpretation, so entries written in the\n * pre-input definition file get overridden by the input's values (the engine\n * writes the scene name as `/Title`, for example). Re-asserting the entries\n * afterwards makes them authoritative and keeps them equivalent to the XMP\n * packet, as PDF/X-4 requires. GS derives its auto-XMP for the non-X-4 paths\n * from the final Info dictionary, so those stay synchronized too.\n */\nexport function generatePostDocinfo(\n options: PDFXOptions,\n timestamps: PDFXTimestamps,\n embedICCProfile: boolean\n): string {\n const title = resolveTitle(options);\n const isX4 = options.outputStandard === 'PDF/X-4';\n\n // X-3 keeps the conformance entry in DOCINFO (ISO 15930-6); X-4 keeps it\n // in XMP only. No claim when ICC embedding is off (output is not PDF/X).\n const x3ConformanceLine =\n isX4 || !embedICCProfile\n ? ''\n : '\\n[ /GTS_PDFXVersion (PDF/X-3:2003) /GTS_PDFXConformance (PDF/X-3:2003) /DOCINFO pdfmark';\n\n return `%!\n% Post-input DOCINFO (must stay equivalent to the XMP packet)\n[ /Title <${utf16beHex(title)}> /DOCINFO pdfmark\n[ /Creator (${CREATOR_TOOL}) /DOCINFO pdfmark\n[ /CreationDate (${timestamps.pdfDate}) /DOCINFO pdfmark\n[ /ModDate (${timestamps.pdfDate}) /DOCINFO pdfmark\n[ /Trapped /False /DOCINFO pdfmark${x3ConformanceLine}`;\n}\n","import type { PDFXOptions } from './types/pdfx';\n\nexport interface BuildGhostscriptArgsContext {\n isCMYKProfile: boolean;\n outputPath: string;\n pdfxDefPath: string;\n inputPath: string;\n postDocinfoPath: string;\n}\n\n/**\n * Build the Ghostscript argv for the conversion run.\n *\n * Pure function: no I/O, no side effects. Centralizes the X-3 vs X-4 branch\n * and the `ghostscriptArgs` full-override short-circuit so the call site in\n * `pdfx.ts` stays readable.\n */\nexport function buildGhostscriptArgs(\n options: PDFXOptions,\n ctx: BuildGhostscriptArgsContext\n): string[] {\n // The post-input DOCINFO file must come after the input so its entries win\n // over Info values inherited from the input PDF.\n const trailing = [\n `-sOutputFile=${ctx.outputPath}`,\n ctx.pdfxDefPath,\n ctx.inputPath,\n ctx.postDocinfoPath,\n ];\n\n // Full override: caller takes responsibility for every flag. We still\n // append the positional output/def/input/post quadruplet so callers don't\n // have to know the internal /tmp/ paths. Empty arrays fall through to\n // defaults.\n if (options.ghostscriptArgs && options.ghostscriptArgs.length > 0) {\n return [...options.ghostscriptArgs, ...trailing];\n }\n\n const isX4 = options.outputStandard === 'PDF/X-4';\n\n const args: string[] = [\n '-dBATCH',\n '-dNOPAUSE',\n '-sDEVICE=pdfwrite',\n // PDF/X-4 requires PDF 1.6 (live transparency); X-3 stays at 1.4.\n isX4 ? '-dCompatibilityLevel=1.6' : '-dCompatibilityLevel=1.4',\n // Disable PDF 1.5+ features for X-3 to avoid warnings; harmless on X-4.\n // Keep `-dWriteObjStms=false` on for X-4 too — the integration tests grep\n // the output for strict-conformance markers, and object streams would\n // hide them inside compressed dictionaries.\n '-dWriteObjStms=false',\n '-dWriteXRefStm=false',\n '-dPDFSETTINGS=/prepress',\n '-dSetPageSize=false',\n '-dAutoRotatePages=/None',\n ];\n\n if (isX4) {\n // pdfwrite Flate-compresses the pdfmark-injected XMP Metadata stream,\n // which Acrobat Preflight flags as a PDF/X-4 violation. Costs output\n // size: the ICC profile and other pdfmark streams stay raw.\n args.push('-dCompressStreams=false');\n }\n\n // X-4 keeps transparency live by definition — never push HaveTransparency=false.\n // For X-3, default to flattening so output is strictly compliant; callers\n // can opt out (producing a non-strict X-3 with live transparency).\n if (!isX4 && options.flattenTransparency !== false) {\n args.push('-dHaveTransparency=false');\n }\n\n if (ctx.isCMYKProfile) {\n args.push(\n '-sColorConversionStrategy=CMYK',\n '-dProcessColorModel=/DeviceCMYK',\n '-dConvertCMYKImagesToRGB=false'\n );\n } else {\n args.push('-sColorConversionStrategy=RGB');\n }\n\n return [...args, ...trailing];\n}\n","import type { PDFXOptions, PDFX3Options } from './types/pdfx';\nimport { getDefaultConversionRuntime } from '@imgly/pdf-conversion-utils';\nimport { BlobUtils } from './utils/blob-utils';\nimport { Logger } from './utils/logger';\nimport {\n formatPDFXTimestamps,\n generatePDFXDef,\n generatePostDocinfo,\n} from './pdfx-def';\nimport { buildGhostscriptArgs } from './pdfx-args';\n\n/**\n * maxInputSize stays optional for callers so they can use the default.\n * Helpers require a resolved limit: `size > undefined` would silently skip the size guard.\n */\ninterface ResolvedPDFXOptions extends PDFXOptions {\n maxInputSize: number;\n}\n\n/**\n * PDF/X conversion function.\n *\n * Converts RGB PDF(s) to the selected PDF/X standard (defaults to `PDF/X-4`)\n * using the specified output profile. PDF/X-4 keeps live transparency so\n * vector text on transparent pages stays selectable. Set\n * `outputStandard: 'PDF/X-3'` to fall back to the older PDF 1.4 standard\n * (which requires flattening transparency).\n *\n * Known limitation: `/Author`, `/Subject`, and `/Keywords` entries inherited\n * from the input PDF are carried into the output without XMP counterparts,\n * which preflight tools may flag. CE.SDK exports never write these keys.\n *\n * @overload\n * @param inputPDF Single PDF blob to convert\n * @param options Conversion configuration\n * @returns Promise resolving to converted PDF blob\n *\n * @overload\n * @param inputPDFs Array of PDF blobs to convert\n * @param options Conversion configuration\n * @returns Promise resolving to array of converted PDF blobs\n */\nexport function convertToPDFX(\n inputPDF: Blob,\n options: PDFXOptions\n): Promise<Blob>;\nexport function convertToPDFX(\n inputPDFs: Blob[],\n options: PDFXOptions\n): Promise<Blob[]>;\nexport async function convertToPDFX(\n input: Blob | Blob[],\n options: PDFXOptions\n): Promise<Blob | Blob[]> {\n const maxInputSize =\n options.maxInputSize === undefined\n ? 100 * 1024 * 1024\n : options.maxInputSize;\n if (!Number.isSafeInteger(maxInputSize) || maxInputSize <= 0) {\n throw new Error('maxInputSize must be a positive safe integer in bytes');\n }\n\n // Apply the X-4 default at the entry point so internal helpers see a\n // concrete outputStandard. Explicit caller values win over the default.\n const resolvedOptions: ResolvedPDFXOptions = {\n outputStandard: 'PDF/X-4',\n ...options,\n maxInputSize,\n };\n\n // Handle array input (batch processing)\n if (Array.isArray(input)) {\n if (input.length === 0) {\n return [];\n }\n\n // Process each blob sequentially to avoid overwhelming the WASM module\n const results: Blob[] = [];\n for (let i = 0; i < input.length; i++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n const converted = await convertToPDFXSingle(input[i], resolvedOptions);\n results.push(converted);\n } catch (error) {\n const batchError = new Error(\n `Failed to convert PDF ${i + 1} of ${input.length}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error }\n );\n if (error instanceof Error && 'code' in error) {\n Object.assign(batchError, {\n code: error.code,\n ...('diagnostics' in error && {\n diagnostics: error.diagnostics,\n }),\n ...('exitCode' in error && { exitCode: error.exitCode }),\n });\n }\n throw batchError;\n }\n }\n return results;\n }\n\n // Handle single blob input\n return convertToPDFXSingle(input, resolvedOptions);\n}\n\n/**\n * Resolves a preset to the ICC profile bundled next to this module.\n *\n * Every URL is a literal, because a bundler copies a profile into the build\n * only when it can read the path. Built from a variable it copies none, and\n * the export fails on whatever the host returns instead.\n */\nfunction bundledProfileURL(profile: string): string {\n switch (profile) {\n case 'gracol':\n return new URL('./GRACoL2013_CRPC6.icc', import.meta.url).href;\n case 'srgb':\n return new URL('./sRGB_IEC61966-2-1.icc', import.meta.url).href;\n default:\n return new URL('./ISOcoated_v2_eci.icc', import.meta.url).href;\n }\n}\n\n/**\n * @deprecated Use `convertToPDFX` instead. This alias is preserved for\n * backwards compatibility and will be removed in a future major release.\n *\n * Defaults to `outputStandard: 'PDF/X-3'` to match the historical behavior\n * of this function — unlike `convertToPDFX`, which defaults to PDF/X-4.\n * Callers can still pass `outputStandard: 'PDF/X-4'` explicitly to opt in.\n */\nexport function convertToPDFX3(\n inputPDF: Blob,\n options: PDFX3Options\n): Promise<Blob>;\nexport function convertToPDFX3(\n inputPDFs: Blob[],\n options: PDFX3Options\n): Promise<Blob[]>;\nexport function convertToPDFX3(\n input: Blob | Blob[],\n options: PDFX3Options\n): Promise<Blob | Blob[]> {\n // Preserve historical X-3 default for the deprecated alias. Explicit\n // caller values still win, so { outputStandard: 'PDF/X-4' } also works.\n const x3Defaulted: PDFX3Options = { outputStandard: 'PDF/X-3', ...options };\n // Delegate without narrowing — runtime branch on Array.isArray inside\n // convertToPDFX already matches the overload semantics.\n return convertToPDFX(input as Blob, x3Defaulted);\n}\n\n/**\n * Internal function to convert a single PDF\n */\nasync function convertToPDFXSingle(\n inputPDF: Blob,\n options: ResolvedPDFXOptions\n): Promise<Blob> {\n // Validate inputs\n if (!(inputPDF instanceof Blob)) {\n throw new Error('Input must be a Blob');\n }\n\n if (inputPDF.size === 0) {\n throw new Error('Input PDF is empty');\n }\n\n if (inputPDF.size > options.maxInputSize) {\n throw new Error(\n `Input PDF too large (${inputPDF.size} bytes). Maximum: ${options.maxInputSize} bytes`\n );\n }\n\n // Validate output profile is provided\n if (!options.outputProfile) {\n throw new Error(\n 'outputProfile is required. Must be one of: \"gracol\", \"fogra39\", \"srgb\", \"custom\"'\n );\n }\n\n // Validate output profile value\n const validProfiles = ['gracol', 'fogra39', 'srgb', 'custom'];\n if (!validProfiles.includes(options.outputProfile)) {\n throw new Error(\n `Invalid outputProfile \"${\n options.outputProfile\n }\". Must be one of: ${validProfiles.join(', ')}`\n );\n }\n\n // Validate custom profile requirement\n if (options.outputProfile === 'custom' && !options.customProfile) {\n throw new Error(\n 'customProfile Blob is required when outputProfile is \"custom\"'\n );\n }\n\n // Validate custom profile if provided\n if (options.customProfile && !(options.customProfile instanceof Blob)) {\n throw new Error('customProfile must be a Blob');\n }\n\n // Validate PDF format\n const isValidPDF = await BlobUtils.validatePDF(inputPDF);\n if (!isValidPDF) {\n throw new Error('Invalid PDF format');\n }\n\n const runtime = options.runtime ?? getDefaultConversionRuntime();\n const operationOptions = {\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n };\n const { version } = await runtime.preload(operationOptions);\n const logger = new Logger('PDFXConversion');\n logger.info('Converting PDF in Ghostscript worker');\n const files: Record<string, Uint8Array | string> = {};\n // Setup file paths\n const inputPath = '/work/input.pdf';\n const outputPath = '/work/output.pdf';\n const pdfxDefPath = '/work/pdfx_def.ps';\n const postDocinfoPath = '/work/pdfx_post.ps';\n const customProfilePath = '/work/custom.icc';\n\n // Write input PDF to virtual filesystem\n files['input.pdf'] = await BlobUtils.toUint8Array(inputPDF);\n\n // Write ICC profiles to virtual filesystem\n if (options.outputProfile === 'custom' && options.customProfile) {\n files['custom.icc'] = await BlobUtils.toUint8Array(options.customProfile);\n } else if (options.outputProfile !== 'custom') {\n // Load the bundled ICC profile\n const profileInfo =\n PROFILE_PRESETS[options.outputProfile as keyof typeof PROFILE_PRESETS];\n\n // Load ICC profile - different approach for Node.js vs browser\n const isNode =\n typeof process !== 'undefined' && process.versions?.node != null;\n\n let profileBlob: Blob;\n\n if (isNode) {\n // Node.js: Load from filesystem using readFileSync\n // Use indirect dynamic import to prevent Webpack 5 from statically analyzing these imports\n // But use direct imports in test environments (vitest) where indirect imports bypass mocking\n // See: https://github.com/imgly/ubq/issues/11471\n const isTestEnv =\n process.env.VITEST === 'true' || process.env.NODE_ENV === 'test';\n\n // Note: new Function() could fail in CSP-restricted environments, but CSP is a browser\n // security mechanism and doesn't apply to Node.js. This code only runs in Node.js (isNode check above).\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const indirectImport = new Function('s', 'return import(s)') as (\n s: string\n ) => Promise<any>;\n const dynamicImport = isTestEnv\n ? (s: string) => import(s)\n : indirectImport;\n\n const { readFileSync } = await dynamicImport('fs');\n const { fileURLToPath } = await dynamicImport('url');\n const { dirname, join } = await dynamicImport('path');\n\n // Get the directory of the built module\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const profileFilePath = join(moduleDir, profileInfo.file);\n\n const profileData = readFileSync(profileFilePath);\n profileBlob = new Blob([profileData], {\n type: 'application/vnd.iccprofile',\n });\n } else {\n // Browser: Use fetch\n const profileUrl = bundledProfileURL(options.outputProfile);\n const profileResponse = await fetch(profileUrl, {\n signal: options.signal,\n });\n if (!profileResponse.ok) {\n throw new Error(\n `Failed to load ICC profile ${profileInfo.file}: ${profileResponse.statusText}`\n );\n }\n profileBlob = await profileResponse.blob();\n }\n\n files[profileInfo.file] = await BlobUtils.toUint8Array(profileBlob);\n }\n\n // Determine ICC profile path and metadata for Ghostscript\n let iccProfilePath: string;\n let outputConditionIdentifier: string;\n let outputCondition: string;\n\n if (options.outputProfile === 'custom') {\n iccProfilePath = customProfilePath;\n // Use custom values or defaults\n outputConditionIdentifier =\n options.outputConditionIdentifier || 'Custom Profile';\n outputCondition = options.outputCondition || 'Custom ICC Profile';\n } else {\n const preset =\n PROFILE_PRESETS[options.outputProfile as keyof typeof PROFILE_PRESETS];\n iccProfilePath = `/work/${preset.file}`;\n // Allow overriding preset values\n outputConditionIdentifier =\n options.outputConditionIdentifier || preset.identifier;\n outputCondition = options.outputCondition || preset.info;\n }\n\n // Read ICC profile data to inspect its color space\n const iccData = files[iccProfilePath.slice('/work/'.length)] as Uint8Array;\n\n // Determine color conversion strategy based on profile type\n // ICC profile color space is at bytes 16-19\n // 'RGB ' = 0x52474220, 'CMYK' = 0x434D594B\n const colorSpaceBytes = iccData.slice(16, 20);\n const colorSpaceStr = String.fromCharCode(...colorSpaceBytes);\n const isCMYKProfile = colorSpaceStr.trim() === 'CMYK';\n\n // Embed ICC profile + PDF/X-3 OutputIntent by default. Callers can opt\n // out (e.g. when a downstream prepress pipeline handles ICC embedding).\n const embedICCProfile = options.embedICCProfile !== false;\n\n // Only hex-encode the profile for pdfmark embedding when we'll actually\n // embed it. WASM doesn't support (file) (r) file syntax, so pdfmark needs\n // the raw hex stream inline.\n const iccHex = embedICCProfile\n ? Array.from(iccData)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n : '';\n\n // One instant for both metadata stores (DocInfo and XMP dates).\n const timestamps = formatPDFXTimestamps(new Date());\n\n // pdfwrite stamps its own Producer into DocInfo (not overridable in GPL\n // builds); the XMP packet must mirror it exactly.\n if (typeof version !== 'string' || version.length === 0) {\n throw new Error(\n 'Ghostscript module reported no version; cannot mirror the Producer into XMP'\n );\n }\n\n const pdfxDefinition = generatePDFXDef(options, {\n iccProfileHex: iccHex,\n outputConditionIdentifier,\n outputCondition,\n embedICCProfile,\n timestamps,\n docId: generateDocumentId(),\n producer: `GPL Ghostscript ${version}`,\n });\n files['pdfx_def.ps'] = pdfxDefinition;\n files['pdfx_post.ps'] = generatePostDocinfo(\n options,\n timestamps,\n embedICCProfile\n );\n\n // Note on ICC profile selection when embedICCProfile is false:\n // pdfwrite's color conversion uses Ghostscript's bundled default CMYK\n // profile (regardless of the selected outputProfile) since\n // `-sOutputICCProfile` only controls OutputIntent embedding on the\n // pdfwrite device, not the conversion math. That's acceptable here\n // because downstream prepress pipelines (ZePrA, PitStop) are expected\n // to re-normalize colors using their own profile anyway; the plugin's\n // job in this mode is only to deliver a device CMYK PDF without an\n // embedded OutputIntent.\n const gsArgs = buildGhostscriptArgs(options, {\n isCMYKProfile,\n outputPath,\n pdfxDefPath,\n inputPath,\n postDocinfoPath,\n });\n\n const result = await runtime.run(\n { files, args: gsArgs, outputFiles: ['output.pdf'] },\n {\n ...operationOptions,\n // PDF/X-4 disables stream compression, so a valid output can grow far\n // beyond its input. Keep the plugin's historical unrestricted output\n // behavior unless the caller requests a limit.\n maxOutputBytes: options.maxOutputBytes ?? Number.MAX_SAFE_INTEGER,\n }\n );\n return new Blob([new Uint8Array(result.files['output.pdf'])], {\n type: 'application/pdf',\n });\n}\n\n/**\n * Generate an RFC 4122 v4 UUID for the XMP `xmpMM:DocumentID` field. Uses\n * the Web Crypto API where available (modern browsers, Node 19+); falls\n * back to a Math.random shim for older Node runtimes. The DocumentID is\n * an identifier, not a security boundary, so the fallback is acceptable.\n */\nfunction generateDocumentId(): string {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.floor(Math.random() * 16);\n // Standard RFC 4122 v4 y-nibble construction: clamp to 10/11 (binary) via\n // bit-clear of 0x3 then set 0x8. Bitwise math is unavoidable here.\n // eslint-disable-next-line no-bitwise\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// Profile presets from the spec\nconst PROFILE_PRESETS = {\n gracol: {\n file: 'GRACoL2013_CRPC6.icc',\n identifier: 'CGATS 21.2',\n info: 'GRACoL 2013 CRPC6',\n },\n fogra39: {\n file: 'ISOcoated_v2_eci.icc',\n identifier: 'FOGRA39',\n info: 'ISO Coated v2 (ECI)',\n },\n srgb: {\n file: 'sRGB_IEC61966-2-1.icc',\n identifier: 'sRGB IEC61966-2.1',\n info: 'sRGB IEC61966-2.1',\n },\n};\n"],"mappings":"AAQA,IAAIA,EACAC,EAAc,EAElB,SAASC,GAAmC,CAC1C,GAAI,CAACF,EAAS,CACZ,IAAMG,EACJ,OAAO,QAAY,KAAe,QAAQ,UAAU,MAAQ,KACxDC,EAAM,IAAI,IACdD,EAAS,2BAA6B,8BACtC,YAAY,GACd,EAEIF,EAAc,GAChBG,EAAI,aAAa,IAAI,QAAS,OAAOH,CAAW,CAAC,EAEnD,EAAU;;AAAiCG,EAAI,KAAK,CAAC,KAClD,GAAWC,EAAO,4BAA4B,EAC9C,GAAU,CAGT,KAFA,IAAe,EACf,EAAU,IAAA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F,CAAC,EAEKsH,EAAS,MAAMhI,EAAQ,IAC3B,CAAE,QAAO,KAAM+H,EAAQ,YAAa,CAAC,YAAY,CAAE,EACnD,CACE,GAAG1B,EAIH,eAAgB3F,EAAQ,uBAC1B,CACF,EACA,OAAO,IAAI,KAAK,CAAC,IAAI,WAAWsH,EAAO,MAAM,aAAa,CAAC,EAAG,CAC5D,KAAM,iBACR,CAAC,CACH,CAQA,SAASF,GAA6B,CAIpC,OAHI,OAAO,WAAW,QAAQ,YAAe,WACpC,WAAW,OAAO,WAAW,EAE/B,uCAAuC,QAAQ,QAAU,GAAM,CACpE,IAAMxF,EAAI,KAAK,MAAM,KAAK,OAAO,EAAI,EAAE,EAKvC,OADU2F,IAAM,IAAM3F,EAAKA,EAAI,EAAO,EAAA,CAC7B,SAAS,EAAE,CACtB,CAAC,CACH,CAGA,MAAMkE,EAAkB,CACtB,OAAQ,CACN,KAAM,uBACN,WAAY,aACZ,KAAM,mBACR,EACA,QAAS,CACP,KAAM,uBACN,WAAY,UACZ,KAAM,qBACR,EACA,KAAM,CACJ,KAAM,wBACN,WAAY,oBACZ,KAAM,mBACR,CACF,E"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["runtime","importRetry","load","isNode","url","module","error","conversionError","message","loadForOperation","options","signal","timeoutMs","started","timeoutError","abort","timer","cancelled","reject","loaded","remaining","adapter","job","previous","getDefaultConversionRuntime","BlobUtils","blob","buffer","reader","resolve","data","pdfHeader","i","_typeof","o","toPrimitive","t","e","r","toPropertyKey","_defineProperty","Logger","component","level","levelOrder","entry","prefix","logMessage","CREATOR_TOOL","resolveTitle","match","formatPDFXTimestamps","date","p","n","y","mo","d","h","mi","escapePSString","value","escapeXML","utf8ToHex","bytes","hex","b","utf16beHex","buildPDFX4XMPPacket","titleX","title","nowX","timestamps","docIdX","docId","producer","generatePDFXDef","ctx","isX4","headerComment","distillerPrologue","xmpReplaceBlock","generatePostDocinfo","x3ConformanceLine","embedICCProfile","buildGhostscriptArgs","trailing","args","convertToPDFX","maxInputSize","resolvedOptions","input","results","converted","convertToPDFXSingle","batchError","bundledProfileURL","file","convertToPDFX3","inputPDF","validProfiles","operationOptions","files","profileInfo","resolvePreset","profileBlob","isTestEnv","indirectImport","dynamicImport","s","profileData","readFileSync","join","dirname","fileURLToPath","profileUrl","profileResponse","iccProfilePath","outputConditionIdentifier","outputCondition","preset","iccData","colorSpaceBytes","isCMYKProfile","iccHex","version","generateDocumentId","gsArgs","result","c","PROFILE_PRESETS","GRACOL_2006_PRESET"],"sources":["../src/standalone-runtime.ts","../src/utils/blob-utils.ts","../src/utils/logger.ts","../src/pdfx-def.ts","../src/pdfx-args.ts","../src/pdfx.ts"],"sourcesContent":["import type {\n ConversionRuntime,\n OperationOptions,\n ConversionJob,\n RunOptions,\n ConversionErrorCode,\n} from '@imgly/pdf-conversion-utils';\n\nlet runtime: Promise<ConversionRuntime> | undefined;\nlet importRetry = 0;\n\nfunction load(): Promise<ConversionRuntime> {\n if (!runtime) {\n const isNode =\n typeof process !== 'undefined' && process.versions?.node != null;\n const url = new URL(\n isNode ? './pdf-conversion/node.js' : './pdf-conversion/browser.js',\n import.meta.url\n );\n // Browsers cache failed module imports, so only actual load failures get a new URL.\n if (importRetry > 0) {\n url.searchParams.set('retry', String(importRetry));\n }\n runtime = import(/* webpackIgnore: true */ url.href).then(\n (module) => module.getDefaultConversionRuntime() as ConversionRuntime,\n (error) => {\n importRetry += 1;\n runtime = undefined;\n throw error;\n }\n );\n }\n return runtime;\n}\n\nfunction conversionError(message: string, code: ConversionErrorCode): Error {\n // Preserve the runtime error shape without loading its module to cancel.\n return Object.assign(new Error(message), {\n name: 'ConversionError',\n code,\n diagnostics: [],\n });\n}\n\nasync function loadForOperation(\n options: OperationOptions = {}\n): Promise<{ loaded: ConversionRuntime; timeoutMs: number }> {\n const { signal } = options;\n if (signal?.aborted) {\n throw conversionError('Conversion was aborted', 'ABORTED');\n }\n const timeoutMs = options.timeoutMs ?? 30_000;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw conversionError(\n 'timeoutMs must be a positive safe integer',\n 'INVALID_INPUT'\n );\n }\n if (timeoutMs > 2 ** 31 - 1) {\n throw conversionError(\n `timeoutMs must not exceed ${2 ** 31 - 1}`,\n 'INVALID_INPUT'\n );\n }\n\n const started = performance.now();\n const timeoutError = () =>\n conversionError(`Conversion timed out after ${timeoutMs}ms`, 'TIMEOUT');\n let abort!: () => void;\n let timer!: ReturnType<typeof setTimeout>;\n const cancelled = new Promise<never>((_, reject) => {\n abort = () => reject(conversionError('Conversion was aborted', 'ABORTED'));\n signal?.addEventListener('abort', abort, { once: true });\n timer = setTimeout(() => reject(timeoutError()), timeoutMs);\n });\n try {\n // Only stop this caller's wait; other callers still share the module load.\n const loaded = await Promise.race([load(), cancelled]);\n const remaining = Math.ceil(timeoutMs - (performance.now() - started));\n if (remaining <= 0) throw timeoutError();\n return { loaded, timeoutMs: remaining };\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n }\n}\n\n// The standalone CDN entry resolves the same runtime locally without a bare npm import.\nconst adapter: ConversionRuntime = {\n async preload(options?: OperationOptions) {\n const { loaded, timeoutMs } = await loadForOperation(options);\n return loaded.preload({ ...options, timeoutMs });\n },\n async run(job: ConversionJob, options?: RunOptions) {\n const { loaded, timeoutMs } = await loadForOperation(options);\n return loaded.run(job, { ...options, timeoutMs });\n },\n dispose() {\n const previous = runtime;\n runtime = undefined;\n void previous?.then(\n (loaded) => loaded.dispose(),\n () => undefined\n );\n },\n};\n\nexport function getDefaultConversionRuntime(): ConversionRuntime {\n return adapter;\n}\n","export class BlobUtils {\n static async toUint8Array(blob: Blob): Promise<Uint8Array> {\n if (blob.arrayBuffer) {\n const buffer = await blob.arrayBuffer();\n return new Uint8Array(buffer);\n }\n\n // Fallback for older browsers\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => {\n if (reader.result instanceof ArrayBuffer) {\n resolve(new Uint8Array(reader.result));\n } else {\n reject(new Error('Failed to read blob as ArrayBuffer'));\n }\n };\n reader.onerror = () => reject(reader.error);\n reader.readAsArrayBuffer(blob);\n });\n }\n\n static async validatePDF(blob: Blob): Promise<boolean> {\n try {\n const data = await this.toUint8Array(blob);\n\n // Check PDF magic number\n const pdfHeader = new Uint8Array([0x25, 0x50, 0x44, 0x46]); // %PDF\n\n if (data.length < 4) {\n return false;\n }\n\n for (let i = 0; i < 4; i++) {\n if (data[i] !== pdfHeader[i]) {\n return false;\n }\n }\n\n return true;\n } catch {\n return false;\n }\n }\n}\n","/* eslint-disable no-console */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface LogEntry {\n timestamp: number;\n level: LogLevel;\n component: string;\n message: string;\n data?: any;\n}\n\nexport class Logger {\n private static globalLogLevel: LogLevel = 'warn';\n\n private static logs: LogEntry[] = [];\n\n private static maxLogs = 1000;\n\n constructor(private component: string) {}\n\n static setLogLevel(level: LogLevel): void {\n Logger.globalLogLevel = level;\n }\n\n static getLogs(): LogEntry[] {\n return [...Logger.logs];\n }\n\n static clearLogs(): void {\n Logger.logs = [];\n }\n\n debug(message: string, data?: any): void {\n this.log('debug', message, data);\n }\n\n info(message: string, data?: any): void {\n this.log('info', message, data);\n }\n\n warn(message: string, data?: any): void {\n this.log('warn', message, data);\n }\n\n error(message: string, data?: any): void {\n this.log('error', message, data);\n }\n\n private log(level: LogLevel, message: string, data?: any): void {\n const levelOrder: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n if (levelOrder[level] < levelOrder[Logger.globalLogLevel]) {\n return;\n }\n\n const entry: LogEntry = {\n timestamp: Date.now(),\n level,\n component: this.component,\n message,\n data,\n };\n\n Logger.logs.push(entry);\n\n // Keep logs under the limit\n if (Logger.logs.length > Logger.maxLogs) {\n Logger.logs = Logger.logs.slice(-Logger.maxLogs);\n }\n\n // Console output\n const prefix = `[${new Date().toISOString()}] [${level.toUpperCase()}] [${\n this.component\n }]`;\n const logMessage = data ? `${message} ${JSON.stringify(data)}` : message;\n\n switch (level) {\n case 'debug':\n console.debug(prefix, logMessage);\n break;\n case 'info':\n console.info(prefix, logMessage);\n break;\n case 'warn':\n console.warn(prefix, logMessage);\n break;\n case 'error':\n console.error(prefix, logMessage);\n break;\n default:\n // All log levels handled above\n break;\n }\n }\n}\n","import type { PDFXOptions } from './types/pdfx';\n\n/** Value written to DocInfo `/Creator` and XMP `xmp:CreatorTool`. */\nconst CREATOR_TOOL = 'IMG.LY';\n\n/**\n * Resolve the document title once for BOTH metadata stores. Lone surrogates\n * and XML-illegal control characters would desync or corrupt the XMP side,\n * so they are repaired/stripped before either encoding sees the value.\n */\nfunction resolveTitle(options: PDFXOptions): string {\n const sanitized = (options.title || '')\n // Pairs match first and stay; any surrogate left over is unpaired. No lookbehind: Safari 15.6.\n .replace(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDFFF]/g, (match) =>\n match.length === 2 ? match : '�'\n )\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g, '');\n return sanitized || 'Untitled';\n}\n\n/**\n * One instant rendered in both metadata date formats. PDF/X-4 requires the\n * DocInfo dates and the XMP dates to describe the same time, so both strings\n * must always be derived from the same `Date` via `formatPDFXTimestamps`.\n */\nexport interface PDFXTimestamps {\n /** PDF date string for DOCINFO pdfmarks, e.g. `D:20260722140113+00'00'` */\n pdfDate: string;\n /** ISO-8601 string for the XMP packet, e.g. `2026-07-22T14:01:13+00:00` */\n xmpDate: string;\n}\n\n/**\n * Render `date` at second precision in UTC. Sub-second precision is dropped\n * deliberately: the PDF date format has none, and a fractional part in the\n * XMP value would break the Info↔XMP equivalence preflight checks.\n */\nexport function formatPDFXTimestamps(date: Date): PDFXTimestamps {\n if (Number.isNaN(date.getTime())) {\n throw new Error('formatPDFXTimestamps: invalid Date');\n }\n const p = (n: number) => String(n).padStart(2, '0');\n const y = date.getUTCFullYear();\n const mo = p(date.getUTCMonth() + 1);\n const d = p(date.getUTCDate());\n const h = p(date.getUTCHours());\n const mi = p(date.getUTCMinutes());\n const s = p(date.getUTCSeconds());\n return {\n pdfDate: `D:${y}${mo}${d}${h}${mi}${s}+00'00'`,\n xmpDate: `${y}-${mo}-${d}T${h}:${mi}:${s}+00:00`,\n };\n}\n\n/**\n * Escape a string for use inside a parens-delimited PostScript string.\n * Only `(`, `)`, `\\` need escaping; XML angle brackets and ampersands pass\n * through untouched (PostScript doesn't interpret them).\n */\nfunction escapePSString(value: string): string {\n return value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\(/g, '\\\\(')\n .replace(/\\)/g, '\\\\)');\n}\n\n/**\n * XML-escape a string for use inside element content or quoted attribute\n * values. Covers the five canonical XML entities.\n */\nfunction escapeXML(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Hex-encode a UTF-8 string for use inside a pdfmark `<...>` hex stream\n * literal. PostScript hex strings are case-insensitive; we emit lowercase\n * to match the rest of the pdfmark output.\n */\nfunction utf8ToHex(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let hex = '';\n for (const b of bytes) {\n hex += b.toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/**\n * Encode a string as a BOM-prefixed UTF-16BE hex string for pdfmark text\n * values — a parens literal would be read as PDFDocEncoding and garble\n * non-ASCII titles.\n */\nfunction utf16beHex(value: string): string {\n let hex = 'FEFF';\n for (let i = 0; i < value.length; i++) {\n hex += value.charCodeAt(i).toString(16).toUpperCase().padStart(4, '0');\n }\n return hex;\n}\n\n/**\n * Build the strict PDF/X-4 XMP packet body that fully replaces GS's\n * auto-generated XMP. Preflight checks `pdfxid:GTS_PDFXVersion` specifically;\n * older validators (callas, GS) read `pdfx:GTS_PDFXVersion` — we emit both.\n * `xmpMM:DocumentID`, `RenditionClass`, and `VersionID` round out the entries\n * Acrobat flags as missing on a non-strict X-4.\n *\n * GS's legacy auto-XMP uses the `xapMM` prefix which strict Acrobat Preflight\n * rejects. Replacing the whole packet via the Catalog.Metadata pdfmark\n * bypasses that.\n *\n * Every value that also exists in the final Info dictionary must stay\n * equivalent (PDF/X-4): title/dates/creator match the `generatePostDocinfo`\n * pdfmarks; producer mirrors pdfwrite's own Info stamp.\n */\nfunction buildPDFX4XMPPacket(\n title: string,\n timestamps: PDFXTimestamps,\n docId: string,\n producer: string\n): string {\n const titleX = escapeXML(title);\n const nowX = escapeXML(timestamps.xmpDate);\n const docIdX = escapeXML(docId);\n const producerX = escapeXML(producer);\n // U+FEFF after `begin=\"` is the canonical XMP packet BOM marker.\n // eslint-disable-next-line no-irregular-whitespace\n return `<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\"\n xmlns:pdfx=\"http://ns.adobe.com/pdfx/1.3/\"\n xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\"\n xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n <pdfx:GTS_PDFXVersion>PDF/X-4</pdfx:GTS_PDFXVersion>\n <pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>\n <pdf:Trapped>False</pdf:Trapped>\n <pdf:Producer>${producerX}</pdf:Producer>\n <xmp:CreateDate>${nowX}</xmp:CreateDate>\n <xmp:ModifyDate>${nowX}</xmp:ModifyDate>\n <xmp:MetadataDate>${nowX}</xmp:MetadataDate>\n <xmp:CreatorTool>${CREATOR_TOOL}</xmp:CreatorTool>\n <dc:format>application/pdf</dc:format>\n <dc:title>\n <rdf:Alt>\n <rdf:li xml:lang=\"x-default\">${titleX}</rdf:li>\n </rdf:Alt>\n </dc:title>\n <xmpMM:DocumentID>uuid:${docIdX}</xmpMM:DocumentID>\n <xmpMM:RenditionClass>default</xmpMM:RenditionClass>\n <xmpMM:VersionID>1</xmpMM:VersionID>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>`;\n}\n\nexport interface PDFXDefContext {\n iccProfileHex: string;\n outputConditionIdentifier: string;\n outputCondition: string;\n embedICCProfile: boolean;\n timestamps: PDFXTimestamps;\n docId: string;\n /** Producer string pdfwrite stamps into DocInfo, e.g. `GPL Ghostscript 10.03.1`. */\n producer: string;\n}\n\nexport function generatePDFXDef(\n options: PDFXOptions,\n ctx: PDFXDefContext\n): string {\n // Minimal definition when ICC embedding is disabled: no PDF/X conformance\n // markers and no OutputIntent. DOCINFO entries live in the post-input file.\n if (!ctx.embedICCProfile) {\n return `%!\n% PDF Definition File (ICC embedding disabled)`;\n }\n\n const isX4 = options.outputStandard === 'PDF/X-4';\n const headerComment = isX4\n ? '% PDF/X-4 Definition File'\n : '% PDF/X-3 Definition File';\n\n // X-4 strict conformance: remove transfer functions and halftones globally\n // via setdistillerparams. This must run before any pdfmark so it applies\n // to the full pdfwrite session. Strips the inherited /TR and /HT references\n // Acrobat Preflight reports as hundreds of instances on customer files.\n const distillerPrologue = isX4\n ? '<< /TransferFunctionInfo /Remove /HalftoneInfo /Remove >> setdistillerparams\\n'\n : '';\n\n // X-4 strict conformance: write our own XMP packet and attach it to the\n // Catalog via the Metadata pdfmark. This fully replaces GS's auto-generated\n // XMP (which uses the legacy `xapMM` prefix Acrobat Preflight rejects) and\n // gives us complete control over the entries Preflight checks.\n const xmpReplaceBlock = isX4\n ? `\n\n% Strict PDF/X-4 XMP packet (replaces GS's auto-generated XMP)\n[/_objdef {Metadata} /type /stream /OBJ pdfmark\n[{Metadata} <</Type /Metadata /Subtype /XML>> /PUT pdfmark\n[{Metadata} <${utf8ToHex(\n buildPDFX4XMPPacket(\n resolveTitle(options),\n ctx.timestamps,\n ctx.docId,\n ctx.producer\n )\n )}> /PUT pdfmark\n[{Catalog} <</Metadata {Metadata}>> /PUT pdfmark`\n : '';\n\n return `%!\n${headerComment}\n${distillerPrologue}\n% Supply missing print bounds after each page's size and rotation are installed.\n/pdfshowpage_setpage [\n /pdfshowpage_setpage load /exec load\n {\n dup /TrimBox known not 1 index /ArtBox known not and {\n dup /CropBox known {\n gsave newpath\n dup /CropBox get aload pop moveto lineto\n matrix defaultmatrix setmatrix pathbbox\n 4 array astore grestore\n } {\n [0 0 currentpagedevice /PageSize get aload pop]\n } ifelse\n [/TrimBox 3 -1 roll /PAGE pdfmark\n } if\n } /exec load\n] cvx def\n\n% Embed ICC profile as hex stream\n[/_objdef {icc_PDFX} /type /stream /OBJ pdfmark\n[{icc_PDFX} <</N 4>> /PUT pdfmark\n[{icc_PDFX} <${ctx.iccProfileHex}> /PUT pdfmark\n\n% Define OutputIntent with embedded ICC profile\n[/_objdef {OutputIntent_PDFX} /type /dict /OBJ pdfmark\n[{OutputIntent_PDFX} <<\n /Type /OutputIntent\n /S /GTS_PDFX\n /OutputCondition (${escapePSString(ctx.outputCondition)})\n /OutputConditionIdentifier (${escapePSString(ctx.outputConditionIdentifier)})\n /RegistryName (http://www.color.org)\n /DestOutputProfile {icc_PDFX}\n>> /PUT pdfmark\n\n% Add OutputIntent to Catalog\n[{Catalog} <</OutputIntents [{OutputIntent_PDFX}]>> /PUT pdfmark${xmpReplaceBlock}`;\n}\n\n/**\n * DOCINFO pdfmark file that runs AFTER the input PDF. Ghostscript merges the\n * input's Info dictionary during interpretation, so entries written in the\n * pre-input definition file get overridden by the input's values (the engine\n * writes the scene name as `/Title`, for example). Re-asserting the entries\n * afterwards makes them authoritative and keeps them equivalent to the XMP\n * packet, as PDF/X-4 requires. GS derives its auto-XMP for the non-X-4 paths\n * from the final Info dictionary, so those stay synchronized too.\n */\nexport function generatePostDocinfo(\n options: PDFXOptions,\n timestamps: PDFXTimestamps,\n embedICCProfile: boolean\n): string {\n const title = resolveTitle(options);\n const isX4 = options.outputStandard === 'PDF/X-4';\n\n // X-3 keeps the conformance entry in DOCINFO (ISO 15930-6); X-4 keeps it\n // in XMP only. No claim when ICC embedding is off (output is not PDF/X).\n const x3ConformanceLine =\n isX4 || !embedICCProfile\n ? ''\n : '\\n[ /GTS_PDFXVersion (PDF/X-3:2003) /GTS_PDFXConformance (PDF/X-3:2003) /DOCINFO pdfmark';\n\n return `%!\n% Post-input DOCINFO (must stay equivalent to the XMP packet)\n[ /Title <${utf16beHex(title)}> /DOCINFO pdfmark\n[ /Creator (${CREATOR_TOOL}) /DOCINFO pdfmark\n[ /CreationDate (${timestamps.pdfDate}) /DOCINFO pdfmark\n[ /ModDate (${timestamps.pdfDate}) /DOCINFO pdfmark\n[ /Trapped /False /DOCINFO pdfmark${x3ConformanceLine}`;\n}\n","import type { PDFXOptions } from './types/pdfx';\n\nexport interface BuildGhostscriptArgsContext {\n isCMYKProfile: boolean;\n outputPath: string;\n pdfxDefPath: string;\n inputPath: string;\n postDocinfoPath: string;\n}\n\n/**\n * Build the Ghostscript argv for the conversion run.\n *\n * Pure function: no I/O, no side effects. Centralizes the X-3 vs X-4 branch\n * and the `ghostscriptArgs` full-override short-circuit so the call site in\n * `pdfx.ts` stays readable.\n */\nexport function buildGhostscriptArgs(\n options: PDFXOptions,\n ctx: BuildGhostscriptArgsContext\n): string[] {\n // The post-input DOCINFO file must come after the input so its entries win\n // over Info values inherited from the input PDF.\n const trailing = [\n `-sOutputFile=${ctx.outputPath}`,\n ctx.pdfxDefPath,\n ctx.inputPath,\n ctx.postDocinfoPath,\n ];\n\n // Full override: caller takes responsibility for every flag. We still\n // append the positional output/def/input/post quadruplet so callers don't\n // have to know the internal /tmp/ paths. Empty arrays fall through to\n // defaults.\n if (options.ghostscriptArgs && options.ghostscriptArgs.length > 0) {\n return [...options.ghostscriptArgs, ...trailing];\n }\n\n const isX4 = options.outputStandard === 'PDF/X-4';\n\n const args: string[] = [\n '-dBATCH',\n '-dNOPAUSE',\n '-sDEVICE=pdfwrite',\n // PDF/X-4 requires PDF 1.6 (live transparency); X-3 stays at 1.4.\n isX4 ? '-dCompatibilityLevel=1.6' : '-dCompatibilityLevel=1.4',\n // Disable PDF 1.5+ features for X-3 to avoid warnings; harmless on X-4.\n // Keep `-dWriteObjStms=false` on for X-4 too — the integration tests grep\n // the output for strict-conformance markers, and object streams would\n // hide them inside compressed dictionaries.\n '-dWriteObjStms=false',\n '-dWriteXRefStm=false',\n '-dPDFSETTINGS=/prepress',\n '-dSetPageSize=false',\n '-dAutoRotatePages=/None',\n ];\n\n if (isX4) {\n // pdfwrite Flate-compresses the pdfmark-injected XMP Metadata stream,\n // which Acrobat Preflight flags as a PDF/X-4 violation. Costs output\n // size: the ICC profile and other pdfmark streams stay raw.\n args.push('-dCompressStreams=false');\n }\n\n // X-4 keeps transparency live by definition — never push HaveTransparency=false.\n // For X-3, default to flattening so output is strictly compliant; callers\n // can opt out (producing a non-strict X-3 with live transparency).\n if (!isX4 && options.flattenTransparency !== false) {\n args.push('-dHaveTransparency=false');\n }\n\n if (ctx.isCMYKProfile) {\n args.push(\n '-sColorConversionStrategy=CMYK',\n '-dProcessColorModel=/DeviceCMYK',\n '-dConvertCMYKImagesToRGB=false'\n );\n } else {\n args.push('-sColorConversionStrategy=RGB');\n }\n\n return [...args, ...trailing];\n}\n","import type { PDFXOptions, PDFX3Options } from './types/pdfx';\nimport { getDefaultConversionRuntime } from '@imgly/pdf-conversion-utils';\nimport { BlobUtils } from './utils/blob-utils';\nimport { Logger } from './utils/logger';\nimport {\n formatPDFXTimestamps,\n generatePDFXDef,\n generatePostDocinfo,\n} from './pdfx-def';\nimport { buildGhostscriptArgs } from './pdfx-args';\n\n/**\n * maxInputSize stays optional for callers so they can use the default.\n * Helpers require a resolved limit: `size > undefined` would silently skip the size guard.\n */\ninterface ResolvedPDFXOptions extends PDFXOptions {\n maxInputSize: number;\n}\n\n/**\n * PDF/X conversion function.\n *\n * Converts RGB PDF(s) to the selected PDF/X standard (defaults to `PDF/X-4`)\n * using the specified output profile. PDF/X-4 keeps live transparency so\n * vector text on transparent pages stays selectable. Set\n * `outputStandard: 'PDF/X-3'` to fall back to the older PDF 1.4 standard\n * (which requires flattening transparency).\n *\n * Known limitation: `/Author`, `/Subject`, and `/Keywords` entries inherited\n * from the input PDF are carried into the output without XMP counterparts,\n * which preflight tools may flag. CE.SDK exports never write these keys.\n *\n * @overload\n * @param inputPDF Single PDF blob to convert\n * @param options Conversion configuration\n * @returns Promise resolving to converted PDF blob\n *\n * @overload\n * @param inputPDFs Array of PDF blobs to convert\n * @param options Conversion configuration\n * @returns Promise resolving to array of converted PDF blobs\n */\nexport function convertToPDFX(\n inputPDF: Blob,\n options: PDFXOptions\n): Promise<Blob>;\nexport function convertToPDFX(\n inputPDFs: Blob[],\n options: PDFXOptions\n): Promise<Blob[]>;\nexport async function convertToPDFX(\n input: Blob | Blob[],\n options: PDFXOptions\n): Promise<Blob | Blob[]> {\n const maxInputSize =\n options.maxInputSize === undefined\n ? 100 * 1024 * 1024\n : options.maxInputSize;\n if (!Number.isSafeInteger(maxInputSize) || maxInputSize <= 0) {\n throw new Error('maxInputSize must be a positive safe integer in bytes');\n }\n\n // Apply the X-4 default at the entry point so internal helpers see a\n // concrete outputStandard. Explicit caller values win over the default.\n const resolvedOptions: ResolvedPDFXOptions = {\n outputStandard: 'PDF/X-4',\n ...options,\n maxInputSize,\n };\n\n // Handle array input (batch processing)\n if (Array.isArray(input)) {\n if (input.length === 0) {\n return [];\n }\n\n // Process each blob sequentially to avoid overwhelming the WASM module\n const results: Blob[] = [];\n for (let i = 0; i < input.length; i++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n const converted = await convertToPDFXSingle(input[i], resolvedOptions);\n results.push(converted);\n } catch (error) {\n const batchError = new Error(\n `Failed to convert PDF ${i + 1} of ${input.length}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error }\n );\n if (error instanceof Error && 'code' in error) {\n Object.assign(batchError, {\n code: error.code,\n ...('diagnostics' in error && {\n diagnostics: error.diagnostics,\n }),\n ...('exitCode' in error && { exitCode: error.exitCode }),\n });\n }\n throw batchError;\n }\n }\n return results;\n }\n\n // Handle single blob input\n return convertToPDFXSingle(input, resolvedOptions);\n}\n\n/**\n * Resolves a preset to the ICC profile bundled next to this module.\n *\n * Every URL is a literal, because a bundler copies a profile into the build\n * only when it can read the path. Built from a variable it copies none, and\n * the export fails on whatever the host returns instead.\n */\nfunction bundledProfileURL(file: string): string {\n switch (file) {\n case 'GRACoL2013_CRPC6.icc':\n return new URL('./GRACoL2013_CRPC6.icc', import.meta.url).href;\n case 'GRACoL2006_Coated1v2.icc':\n return new URL('./GRACoL2006_Coated1v2.icc', import.meta.url).href;\n case 'sRGB_IEC61966-2-1.icc':\n return new URL('./sRGB_IEC61966-2-1.icc', import.meta.url).href;\n default:\n return new URL('./ISOcoated_v2_eci.icc', import.meta.url).href;\n }\n}\n\n/**\n * @deprecated Use `convertToPDFX` instead. This alias is preserved for\n * backwards compatibility and will be removed in a future major release.\n *\n * Defaults to `outputStandard: 'PDF/X-3'` to match the historical behavior\n * of this function — unlike `convertToPDFX`, which defaults to PDF/X-4.\n * Callers can still pass `outputStandard: 'PDF/X-4'` explicitly to opt in.\n */\nexport function convertToPDFX3(\n inputPDF: Blob,\n options: PDFX3Options\n): Promise<Blob>;\nexport function convertToPDFX3(\n inputPDFs: Blob[],\n options: PDFX3Options\n): Promise<Blob[]>;\nexport function convertToPDFX3(\n input: Blob | Blob[],\n options: PDFX3Options\n): Promise<Blob | Blob[]> {\n // Preserve historical X-3 default for the deprecated alias. Explicit\n // caller values still win, so { outputStandard: 'PDF/X-4' } also works.\n const x3Defaulted: PDFX3Options = { outputStandard: 'PDF/X-3', ...options };\n // Delegate without narrowing — runtime branch on Array.isArray inside\n // convertToPDFX already matches the overload semantics.\n return convertToPDFX(input as Blob, x3Defaulted);\n}\n\n/**\n * Internal function to convert a single PDF\n */\nasync function convertToPDFXSingle(\n inputPDF: Blob,\n options: ResolvedPDFXOptions\n): Promise<Blob> {\n // Validate inputs\n if (!(inputPDF instanceof Blob)) {\n throw new Error('Input must be a Blob');\n }\n\n if (inputPDF.size === 0) {\n throw new Error('Input PDF is empty');\n }\n\n if (inputPDF.size > options.maxInputSize) {\n throw new Error(\n `Input PDF too large (${inputPDF.size} bytes). Maximum: ${options.maxInputSize} bytes`\n );\n }\n\n // Validate output profile is provided\n if (!options.outputProfile) {\n throw new Error(\n 'outputProfile is required. Must be one of: \"gracol\", \"fogra39\", \"srgb\", \"custom\"'\n );\n }\n\n // Validate output profile value\n const validProfiles = ['gracol', 'fogra39', 'srgb', 'custom'];\n if (!validProfiles.includes(options.outputProfile)) {\n throw new Error(\n `Invalid outputProfile \"${\n options.outputProfile\n }\". Must be one of: ${validProfiles.join(', ')}`\n );\n }\n\n // Validate custom profile requirement\n if (options.outputProfile === 'custom' && !options.customProfile) {\n throw new Error(\n 'customProfile Blob is required when outputProfile is \"custom\"'\n );\n }\n\n // Validate custom profile if provided\n if (options.customProfile && !(options.customProfile instanceof Blob)) {\n throw new Error('customProfile must be a Blob');\n }\n\n // Validate PDF format\n const isValidPDF = await BlobUtils.validatePDF(inputPDF);\n if (!isValidPDF) {\n throw new Error('Invalid PDF format');\n }\n\n const runtime = options.runtime ?? getDefaultConversionRuntime();\n const operationOptions = {\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n };\n const { version } = await runtime.preload(operationOptions);\n const logger = new Logger('PDFXConversion');\n logger.info('Converting PDF in Ghostscript worker');\n const files: Record<string, Uint8Array | string> = {};\n // Setup file paths\n const inputPath = '/work/input.pdf';\n const outputPath = '/work/output.pdf';\n const pdfxDefPath = '/work/pdfx_def.ps';\n const postDocinfoPath = '/work/pdfx_post.ps';\n const customProfilePath = '/work/custom.icc';\n\n // Write input PDF to virtual filesystem\n files['input.pdf'] = await BlobUtils.toUint8Array(inputPDF);\n\n // Write ICC profiles to virtual filesystem\n if (options.outputProfile === 'custom' && options.customProfile) {\n files['custom.icc'] = await BlobUtils.toUint8Array(options.customProfile);\n } else if (options.outputProfile !== 'custom') {\n // Load the bundled ICC profile\n const profileInfo = resolvePreset(options);\n\n // Load ICC profile - different approach for Node.js vs browser\n const isNode =\n typeof process !== 'undefined' && process.versions?.node != null;\n\n let profileBlob: Blob;\n\n if (isNode) {\n // Node.js: Load from filesystem using readFileSync\n // Use indirect dynamic import to prevent Webpack 5 from statically analyzing these imports\n // But use direct imports in test environments (vitest) where indirect imports bypass mocking\n // See: https://github.com/imgly/ubq/issues/11471\n const isTestEnv =\n process.env.VITEST === 'true' || process.env.NODE_ENV === 'test';\n\n // Note: new Function() could fail in CSP-restricted environments, but CSP is a browser\n // security mechanism and doesn't apply to Node.js. This code only runs in Node.js (isNode check above).\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const indirectImport = new Function('s', 'return import(s)') as (\n s: string\n ) => Promise<any>;\n const dynamicImport = isTestEnv\n ? (s: string) => import(s)\n : indirectImport;\n\n const { readFileSync } = await dynamicImport('fs');\n const { fileURLToPath } = await dynamicImport('url');\n const { dirname, join } = await dynamicImport('path');\n\n // Get the directory of the built module\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const profileFilePath = join(moduleDir, profileInfo.file);\n\n const profileData = readFileSync(profileFilePath);\n profileBlob = new Blob([profileData], {\n type: 'application/vnd.iccprofile',\n });\n } else {\n // Browser: Use fetch\n const profileUrl = bundledProfileURL(profileInfo.file);\n const profileResponse = await fetch(profileUrl, {\n signal: options.signal,\n });\n if (!profileResponse.ok) {\n throw new Error(\n `Failed to load ICC profile ${profileInfo.file}: ${profileResponse.statusText}`\n );\n }\n profileBlob = await profileResponse.blob();\n }\n\n files[profileInfo.file] = await BlobUtils.toUint8Array(profileBlob);\n }\n\n // Determine ICC profile path and metadata for Ghostscript\n let iccProfilePath: string;\n let outputConditionIdentifier: string;\n let outputCondition: string;\n\n if (options.outputProfile === 'custom') {\n iccProfilePath = customProfilePath;\n // Use custom values or defaults\n outputConditionIdentifier =\n options.outputConditionIdentifier || 'Custom Profile';\n outputCondition = options.outputCondition || 'Custom ICC Profile';\n } else {\n const preset = resolvePreset(options);\n iccProfilePath = `/work/${preset.file}`;\n // Allow overriding preset values\n outputConditionIdentifier =\n options.outputConditionIdentifier || preset.identifier;\n outputCondition = options.outputCondition || preset.info;\n }\n\n // Read ICC profile data to inspect its color space\n const iccData = files[iccProfilePath.slice('/work/'.length)] as Uint8Array;\n\n // Determine color conversion strategy based on profile type\n // ICC profile color space is at bytes 16-19\n // 'RGB ' = 0x52474220, 'CMYK' = 0x434D594B\n const colorSpaceBytes = iccData.slice(16, 20);\n const colorSpaceStr = String.fromCharCode(...colorSpaceBytes);\n const isCMYKProfile = colorSpaceStr.trim() === 'CMYK';\n\n // Embed ICC profile + PDF/X-3 OutputIntent by default. Callers can opt\n // out (e.g. when a downstream prepress pipeline handles ICC embedding).\n const embedICCProfile = options.embedICCProfile !== false;\n\n // Only hex-encode the profile for pdfmark embedding when we'll actually\n // embed it. WASM doesn't support (file) (r) file syntax, so pdfmark needs\n // the raw hex stream inline.\n const iccHex = embedICCProfile\n ? Array.from(iccData)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n : '';\n\n // One instant for both metadata stores (DocInfo and XMP dates).\n const timestamps = formatPDFXTimestamps(new Date());\n\n // pdfwrite stamps its own Producer into DocInfo (not overridable in GPL\n // builds); the XMP packet must mirror it exactly.\n if (typeof version !== 'string' || version.length === 0) {\n throw new Error(\n 'Ghostscript module reported no version; cannot mirror the Producer into XMP'\n );\n }\n\n const pdfxDefinition = generatePDFXDef(options, {\n iccProfileHex: iccHex,\n outputConditionIdentifier,\n outputCondition,\n embedICCProfile,\n timestamps,\n docId: generateDocumentId(),\n producer: `GPL Ghostscript ${version}`,\n });\n files['pdfx_def.ps'] = pdfxDefinition;\n files['pdfx_post.ps'] = generatePostDocinfo(\n options,\n timestamps,\n embedICCProfile\n );\n\n // Note on ICC profile selection when embedICCProfile is false:\n // pdfwrite's color conversion uses Ghostscript's bundled default CMYK\n // profile (regardless of the selected outputProfile) since\n // `-sOutputICCProfile` only controls OutputIntent embedding on the\n // pdfwrite device, not the conversion math. That's acceptable here\n // because downstream prepress pipelines (ZePrA, PitStop) are expected\n // to re-normalize colors using their own profile anyway; the plugin's\n // job in this mode is only to deliver a device CMYK PDF without an\n // embedded OutputIntent.\n const gsArgs = buildGhostscriptArgs(options, {\n isCMYKProfile,\n outputPath,\n pdfxDefPath,\n inputPath,\n postDocinfoPath,\n });\n\n const result = await runtime.run(\n { files, args: gsArgs, outputFiles: ['output.pdf'] },\n {\n ...operationOptions,\n // PDF/X-4 disables stream compression, so a valid output can grow far\n // beyond its input. Keep the plugin's historical unrestricted output\n // behavior unless the caller requests a limit.\n maxOutputBytes: options.maxOutputBytes ?? Number.MAX_SAFE_INTEGER,\n }\n );\n return new Blob([new Uint8Array(result.files['output.pdf'])], {\n type: 'application/pdf',\n });\n}\n\n/**\n * Generate an RFC 4122 v4 UUID for the XMP `xmpMM:DocumentID` field. Uses\n * the Web Crypto API where available (modern browsers, Node 19+); falls\n * back to a Math.random shim for older Node runtimes. The DocumentID is\n * an identifier, not a security boundary, so the fallback is acceptable.\n */\nfunction generateDocumentId(): string {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.floor(Math.random() * 16);\n // Standard RFC 4122 v4 y-nibble construction: clamp to 10/11 (binary) via\n // bit-clear of 0x3 then set 0x8. Bitwise math is unavoidable here.\n // eslint-disable-next-line no-bitwise\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// Profile presets from the spec\nconst PROFILE_PRESETS = {\n gracol: {\n file: 'GRACoL2013_CRPC6.icc',\n identifier: 'CGATS 21.2',\n info: 'GRACoL 2013 CRPC6',\n },\n fogra39: {\n file: 'ISOcoated_v2_eci.icc',\n identifier: 'FOGRA39',\n info: 'ISO Coated v2 (ECI)',\n },\n srgb: {\n file: 'sRGB_IEC61966-2-1.icc',\n identifier: 'sRGB IEC61966-2.1',\n info: 'sRGB IEC61966-2.1',\n },\n};\n\n// PDF/X-3 readers commonly accept only ICC v2 profiles, and GRACoL 2013 is v4,\n// so 'gracol' with PDF/X-3 uses the v2 GRACoL 2006 profile.\nconst GRACOL_2006_PRESET = {\n file: 'GRACoL2006_Coated1v2.icc',\n identifier: 'CGATS TR 006',\n info: 'GRACoL 2006 Coated #1',\n};\n\nfunction resolvePreset(options: ResolvedPDFXOptions) {\n if (\n options.outputProfile === 'gracol' &&\n options.outputStandard === 'PDF/X-3'\n ) {\n return GRACOL_2006_PRESET;\n }\n return PROFILE_PRESETS[options.outputProfile as keyof typeof PROFILE_PRESETS];\n}\n"],"mappings":"AAQA,IAAIA,EACAC,EAAc,EAElB,SAASC,GAAmC,CAC1C,GAAI,CAACF,EAAS,CACZ,IAAMG,EACJ,OAAO,QAAY,KAAe,QAAQ,UAAU,MAAQ,KACxDC,EAAM,IAAI,IACdD,EAAS,2BAA6B,8BACtC,YAAY,GACd,EAEIF,EAAc,GAChBG,EAAI,aAAa,IAAI,QAAS,OAAOH,CAAW,CAAC,EAEnD,EAAU;;AAAiCG,EAAI,KAAK,CAAC,KAClD,GAAWC,EAAO,4BAA4B,EAC9C,GAAU,CAGT,KAFA,IAAe,EACf,EAAU,IAAA,GACJC,CACR,CACF,CACF,CACA,OAAON,CACT,CAEA,SAASO,EAAgB,EAAiB,EAAkC,CAE1E,OAAO,OAAO,OAAW,MAAMC,CAAO,EAAG,CACvC,KAAM,kBACN,OACA,YAAa,CAAC,CAChB,CAAC,CACH,CAEA,eAAeC,EACb,EAA4B,CAAC,EAC8B,CAC3D,GAAM,CAAE,UAAWC,EACnB,GAAIC,GAAQ,QACV,MAA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,EAAO,MAAM,aAAa,CAAC,EAAG,CAC5D,KAAM,iBACR,CAAC,CACH,CAQA,SAASF,GAA6B,CAIpC,OAHI,OAAO,WAAW,QAAQ,YAAe,WACpC,WAAW,OAAO,WAAW,EAE/B,uCAAuC,QAAQ,QAAU,GAAM,CACpE,IAAMxF,EAAI,KAAK,MAAM,KAAK,OAAO,EAAI,EAAE,EAKvC,OADU2F,IAAM,IAAM3F,EAAKA,EAAI,EAAO,EAAA,CAC7B,SAAS,EAAE,CACtB,CAAC,CACH,CAGA,MAAM4F,EAAkB,CACtB,OAAQ,CACN,KAAM,uBACN,WAAY,aACZ,KAAM,mBACR,EACA,QAAS,CACP,KAAM,uBACN,WAAY,UACZ,KAAM,qBACR,EACA,KAAM,CACJ,KAAM,wBACN,WAAY,oBACZ,KAAM,mBACR,CACF,EAIMC,EAAqB,CACzB,KAAM,2BACN,WAAY,eACZ,KAAM,uBACR,EAEA,SAAS3B,EAAc,EAA8B,CAOnD,OALE9F,EAAQ,gBAAkB,UAC1BA,EAAQ,iBAAmB,UAEpByH,EAEFD,EAAgBxH,EAAQ,cACjC,C"}
|
package/dist/index.npm.mjs
CHANGED
|
@@ -81,5 +81,5 @@ ${i}
|
|
|
81
81
|
[ /Creator (${s}) /DOCINFO pdfmark
|
|
82
82
|
[ /CreationDate (${t.pdfDate}) /DOCINFO pdfmark
|
|
83
83
|
[ /ModDate (${t.pdfDate}) /DOCINFO pdfmark
|
|
84
|
-
[ /Trapped /False /DOCINFO pdfmark${i}`}function _(e,t){let n=[`-sOutputFile=${t.outputPath}`,t.pdfxDefPath,t.inputPath,t.postDocinfoPath];if(e.ghostscriptArgs&&e.ghostscriptArgs.length>0)return[...e.ghostscriptArgs,...n];let r=e.outputStandard===`PDF/X-4`,i=[`-dBATCH`,`-dNOPAUSE`,`-sDEVICE=pdfwrite`,r?`-dCompatibilityLevel=1.6`:`-dCompatibilityLevel=1.4`,`-dWriteObjStms=false`,`-dWriteXRefStm=false`,`-dPDFSETTINGS=/prepress`,`-dSetPageSize=false`,`-dAutoRotatePages=/None`];return r&&i.push(`-dCompressStreams=false`),!r&&e.flattenTransparency!==!1&&i.push(`-dHaveTransparency=false`),t.isCMYKProfile?i.push(`-sColorConversionStrategy=CMYK`,`-dProcessColorModel=/DeviceCMYK`,`-dConvertCMYKImagesToRGB=false`):i.push(`-sColorConversionStrategy=RGB`),[...i,...n]}async function v(e,t){let n=t.maxInputSize===void 0?104857600:t.maxInputSize;if(!Number.isSafeInteger(n)||n<=0)throw Error(`maxInputSize must be a positive safe integer in bytes`);let r={outputStandard:`PDF/X-4`,...t,maxInputSize:n};if(Array.isArray(e)){if(e.length===0)return[];let t=[];for(let n=0;n<e.length;n++)try{let i=await x(e[n],r);t.push(i)}catch(t){let r=Error(`Failed to convert PDF ${n+1} of ${e.length}: ${t instanceof Error?t.message:String(t)}`,{cause:t});throw t instanceof Error&&`code`in t&&Object.assign(r,{code:t.code,...`diagnostics`in t&&{diagnostics:t.diagnostics},...`exitCode`in t&&{exitCode:t.exitCode}}),r}return t}return x(e,r)}function y(e){switch(e){case`
|
|
84
|
+
[ /Trapped /False /DOCINFO pdfmark${i}`}function _(e,t){let n=[`-sOutputFile=${t.outputPath}`,t.pdfxDefPath,t.inputPath,t.postDocinfoPath];if(e.ghostscriptArgs&&e.ghostscriptArgs.length>0)return[...e.ghostscriptArgs,...n];let r=e.outputStandard===`PDF/X-4`,i=[`-dBATCH`,`-dNOPAUSE`,`-sDEVICE=pdfwrite`,r?`-dCompatibilityLevel=1.6`:`-dCompatibilityLevel=1.4`,`-dWriteObjStms=false`,`-dWriteXRefStm=false`,`-dPDFSETTINGS=/prepress`,`-dSetPageSize=false`,`-dAutoRotatePages=/None`];return r&&i.push(`-dCompressStreams=false`),!r&&e.flattenTransparency!==!1&&i.push(`-dHaveTransparency=false`),t.isCMYKProfile?i.push(`-sColorConversionStrategy=CMYK`,`-dProcessColorModel=/DeviceCMYK`,`-dConvertCMYKImagesToRGB=false`):i.push(`-sColorConversionStrategy=RGB`),[...i,...n]}async function v(e,t){let n=t.maxInputSize===void 0?104857600:t.maxInputSize;if(!Number.isSafeInteger(n)||n<=0)throw Error(`maxInputSize must be a positive safe integer in bytes`);let r={outputStandard:`PDF/X-4`,...t,maxInputSize:n};if(Array.isArray(e)){if(e.length===0)return[];let t=[];for(let n=0;n<e.length;n++)try{let i=await x(e[n],r);t.push(i)}catch(t){let r=Error(`Failed to convert PDF ${n+1} of ${e.length}: ${t instanceof Error?t.message:String(t)}`,{cause:t});throw t instanceof Error&&`code`in t&&Object.assign(r,{code:t.code,...`diagnostics`in t&&{diagnostics:t.diagnostics},...`exitCode`in t&&{exitCode:t.exitCode}}),r}return t}return x(e,r)}function y(e){switch(e){case`GRACoL2013_CRPC6.icc`:return new URL(`./GRACoL2013_CRPC6.icc`,import.meta.url).href;case`GRACoL2006_Coated1v2.icc`:return new URL(`./GRACoL2006_Coated1v2.icc`,import.meta.url).href;case`sRGB_IEC61966-2-1.icc`:return new URL(`./sRGB_IEC61966-2-1.icc`,import.meta.url).href;default:return new URL(`./ISOcoated_v2_eci.icc`,import.meta.url).href}}function b(e,t){return v(e,{outputStandard:`PDF/X-3`,...t})}async function x(n,r){if(!(n instanceof Blob))throw Error(`Input must be a Blob`);if(n.size===0)throw Error(`Input PDF is empty`);if(n.size>r.maxInputSize)throw Error(`Input PDF too large (${n.size} bytes). Maximum: ${r.maxInputSize} bytes`);if(!r.outputProfile)throw Error(`outputProfile is required. Must be one of: "gracol", "fogra39", "srgb", "custom"`);let i=[`gracol`,`fogra39`,`srgb`,`custom`];if(!i.includes(r.outputProfile))throw Error(`Invalid outputProfile "${r.outputProfile}". Must be one of: ${i.join(`, `)}`);if(r.outputProfile===`custom`&&!r.customProfile)throw Error(`customProfile Blob is required when outputProfile is "custom"`);if(r.customProfile&&!(r.customProfile instanceof Blob))throw Error(`customProfile must be a Blob`);if(!await t.validatePDF(n))throw Error(`Invalid PDF format`);let a=r.runtime??e(),s={signal:r.signal,timeoutMs:r.timeoutMs},{version:c}=await a.preload(s);new o(`PDFXConversion`).info(`Converting PDF in Ghostscript worker`);let u={};if(u[`input.pdf`]=await t.toUint8Array(n),r.outputProfile===`custom`&&r.customProfile)u[`custom.icc`]=await t.toUint8Array(r.customProfile);else if(r.outputProfile!==`custom`){let e=T(r),n=typeof process<`u`&&process.versions?.node!=null,i;if(n){let t=process.env.VITEST===`true`||!1,n=Function(`s`,`return import(s)`),r=t?e=>import(e):n,{readFileSync:a}=await r(`fs`),{fileURLToPath:o}=await r(`url`),{dirname:s,join:c}=await r(`path`),l=a(c(s(o(import.meta.url)),e.file));i=new Blob([l],{type:`application/vnd.iccprofile`})}else{let t=y(e.file),n=await fetch(t,{signal:r.signal});if(!n.ok)throw Error(`Failed to load ICC profile ${e.file}: ${n.statusText}`);i=await n.blob()}u[e.file]=await t.toUint8Array(i)}let d,f,p;if(r.outputProfile===`custom`)d=`/work/custom.icc`,f=r.outputConditionIdentifier||`Custom Profile`,p=r.outputCondition||`Custom ICC Profile`;else{let e=T(r);d=`/work/${e.file}`,f=r.outputConditionIdentifier||e.identifier,p=r.outputCondition||e.info}let m=u[d.slice(6)],v=m.slice(16,20),b=String.fromCharCode(...v).trim()===`CMYK`,x=r.embedICCProfile!==!1,C=x?Array.from(m).map(e=>e.toString(16).padStart(2,`0`)).join(``):``,w=l(/* @__PURE__ */ new Date);if(typeof c!=`string`||c.length===0)throw Error(`Ghostscript module reported no version; cannot mirror the Producer into XMP`);u[`pdfx_def.ps`]=h(r,{iccProfileHex:C,outputConditionIdentifier:f,outputCondition:p,embedICCProfile:x,timestamps:w,docId:S(),producer:`GPL Ghostscript ${c}`}),u[`pdfx_post.ps`]=g(r,w,x);let E=_(r,{isCMYKProfile:b,outputPath:`/work/output.pdf`,pdfxDefPath:`/work/pdfx_def.ps`,inputPath:`/work/input.pdf`,postDocinfoPath:`/work/pdfx_post.ps`}),D=await a.run({files:u,args:E,outputFiles:[`output.pdf`]},{...s,maxOutputBytes:r.maxOutputBytes??2**53-1});return new Blob([new Uint8Array(D.files[`output.pdf`])],{type:`application/pdf`})}function S(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.floor(Math.random()*16);return(e===`x`?t:t&3|8).toString(16)})}const C={gracol:{file:`GRACoL2013_CRPC6.icc`,identifier:`CGATS 21.2`,info:`GRACoL 2013 CRPC6`},fogra39:{file:`ISOcoated_v2_eci.icc`,identifier:`FOGRA39`,info:`ISO Coated v2 (ECI)`},srgb:{file:`sRGB_IEC61966-2-1.icc`,identifier:`sRGB IEC61966-2.1`,info:`sRGB IEC61966-2.1`}},w={file:`GRACoL2006_Coated1v2.icc`,identifier:`CGATS TR 006`,info:`GRACoL 2006 Coated #1`};function T(e){return e.outputProfile===`gracol`&&e.outputStandard===`PDF/X-3`?w:C[e.outputProfile]}export{o as Logger,v as convertToPDFX,b as convertToPDFX3};
|
|
85
85
|
//# sourceMappingURL=index.npm.mjs.map
|
package/dist/index.npm.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.npm.mjs","names":["BlobUtils","blob","buffer","reader","resolve","reject","data","pdfHeader","i","_typeof","o","toPrimitive","t","e","r","toPropertyKey","_defineProperty","Logger","component","level","message","levelOrder","entry","prefix","logMessage","CREATOR_TOOL","resolveTitle","options","match","formatPDFXTimestamps","date","p","n","y","mo","d","h","mi","escapePSString","value","escapeXML","utf8ToHex","bytes","hex","b","utf16beHex","buildPDFX4XMPPacket","titleX","title","nowX","timestamps","docIdX","docId","producer","generatePDFXDef","ctx","isX4","headerComment","distillerPrologue","xmpReplaceBlock","generatePostDocinfo","x3ConformanceLine","embedICCProfile","buildGhostscriptArgs","trailing","args","convertToPDFX","maxInputSize","resolvedOptions","input","results","converted","convertToPDFXSingle","error","batchError","bundledProfileURL","profile","convertToPDFX3","inputPDF","validProfiles","runtime","getDefaultConversionRuntime","operationOptions","files","profileInfo","PROFILE_PRESETS","isNode","profileBlob","isTestEnv","indirectImport","dynamicImport","s","profileData","readFileSync","join","dirname","fileURLToPath","profileUrl","profileResponse","iccProfilePath","outputConditionIdentifier","outputCondition","preset","iccData","colorSpaceBytes","isCMYKProfile","iccHex","version","generateDocumentId","gsArgs","result","c"],"sources":["../src/utils/blob-utils.ts","../src/utils/logger.ts","../src/pdfx-def.ts","../src/pdfx-args.ts","../src/pdfx.ts"],"sourcesContent":["export class BlobUtils {\n static async toUint8Array(blob: Blob): Promise<Uint8Array> {\n if (blob.arrayBuffer) {\n const buffer = await blob.arrayBuffer();\n return new Uint8Array(buffer);\n }\n\n // Fallback for older browsers\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => {\n if (reader.result instanceof ArrayBuffer) {\n resolve(new Uint8Array(reader.result));\n } else {\n reject(new Error('Failed to read blob as ArrayBuffer'));\n }\n };\n reader.onerror = () => reject(reader.error);\n reader.readAsArrayBuffer(blob);\n });\n }\n\n static async validatePDF(blob: Blob): Promise<boolean> {\n try {\n const data = await this.toUint8Array(blob);\n\n // Check PDF magic number\n const pdfHeader = new Uint8Array([0x25, 0x50, 0x44, 0x46]); // %PDF\n\n if (data.length < 4) {\n return false;\n }\n\n for (let i = 0; i < 4; i++) {\n if (data[i] !== pdfHeader[i]) {\n return false;\n }\n }\n\n return true;\n } catch {\n return false;\n }\n }\n}\n","/* eslint-disable no-console */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface LogEntry {\n timestamp: number;\n level: LogLevel;\n component: string;\n message: string;\n data?: any;\n}\n\nexport class Logger {\n private static globalLogLevel: LogLevel = 'warn';\n\n private static logs: LogEntry[] = [];\n\n private static maxLogs = 1000;\n\n constructor(private component: string) {}\n\n static setLogLevel(level: LogLevel): void {\n Logger.globalLogLevel = level;\n }\n\n static getLogs(): LogEntry[] {\n return [...Logger.logs];\n }\n\n static clearLogs(): void {\n Logger.logs = [];\n }\n\n debug(message: string, data?: any): void {\n this.log('debug', message, data);\n }\n\n info(message: string, data?: any): void {\n this.log('info', message, data);\n }\n\n warn(message: string, data?: any): void {\n this.log('warn', message, data);\n }\n\n error(message: string, data?: any): void {\n this.log('error', message, data);\n }\n\n private log(level: LogLevel, message: string, data?: any): void {\n const levelOrder: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n if (levelOrder[level] < levelOrder[Logger.globalLogLevel]) {\n return;\n }\n\n const entry: LogEntry = {\n timestamp: Date.now(),\n level,\n component: this.component,\n message,\n data,\n };\n\n Logger.logs.push(entry);\n\n // Keep logs under the limit\n if (Logger.logs.length > Logger.maxLogs) {\n Logger.logs = Logger.logs.slice(-Logger.maxLogs);\n }\n\n // Console output\n const prefix = `[${new Date().toISOString()}] [${level.toUpperCase()}] [${\n this.component\n }]`;\n const logMessage = data ? `${message} ${JSON.stringify(data)}` : message;\n\n switch (level) {\n case 'debug':\n console.debug(prefix, logMessage);\n break;\n case 'info':\n console.info(prefix, logMessage);\n break;\n case 'warn':\n console.warn(prefix, logMessage);\n break;\n case 'error':\n console.error(prefix, logMessage);\n break;\n default:\n // All log levels handled above\n break;\n }\n }\n}\n","import type { PDFXOptions } from './types/pdfx';\n\n/** Value written to DocInfo `/Creator` and XMP `xmp:CreatorTool`. */\nconst CREATOR_TOOL = 'IMG.LY';\n\n/**\n * Resolve the document title once for BOTH metadata stores. Lone surrogates\n * and XML-illegal control characters would desync or corrupt the XMP side,\n * so they are repaired/stripped before either encoding sees the value.\n */\nfunction resolveTitle(options: PDFXOptions): string {\n const sanitized = (options.title || '')\n // Pairs match first and stay; any surrogate left over is unpaired. No lookbehind: Safari 15.6.\n .replace(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDFFF]/g, (match) =>\n match.length === 2 ? match : '�'\n )\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g, '');\n return sanitized || 'Untitled';\n}\n\n/**\n * One instant rendered in both metadata date formats. PDF/X-4 requires the\n * DocInfo dates and the XMP dates to describe the same time, so both strings\n * must always be derived from the same `Date` via `formatPDFXTimestamps`.\n */\nexport interface PDFXTimestamps {\n /** PDF date string for DOCINFO pdfmarks, e.g. `D:20260722140113+00'00'` */\n pdfDate: string;\n /** ISO-8601 string for the XMP packet, e.g. `2026-07-22T14:01:13+00:00` */\n xmpDate: string;\n}\n\n/**\n * Render `date` at second precision in UTC. Sub-second precision is dropped\n * deliberately: the PDF date format has none, and a fractional part in the\n * XMP value would break the Info↔XMP equivalence preflight checks.\n */\nexport function formatPDFXTimestamps(date: Date): PDFXTimestamps {\n if (Number.isNaN(date.getTime())) {\n throw new Error('formatPDFXTimestamps: invalid Date');\n }\n const p = (n: number) => String(n).padStart(2, '0');\n const y = date.getUTCFullYear();\n const mo = p(date.getUTCMonth() + 1);\n const d = p(date.getUTCDate());\n const h = p(date.getUTCHours());\n const mi = p(date.getUTCMinutes());\n const s = p(date.getUTCSeconds());\n return {\n pdfDate: `D:${y}${mo}${d}${h}${mi}${s}+00'00'`,\n xmpDate: `${y}-${mo}-${d}T${h}:${mi}:${s}+00:00`,\n };\n}\n\n/**\n * Escape a string for use inside a parens-delimited PostScript string.\n * Only `(`, `)`, `\\` need escaping; XML angle brackets and ampersands pass\n * through untouched (PostScript doesn't interpret them).\n */\nfunction escapePSString(value: string): string {\n return value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\(/g, '\\\\(')\n .replace(/\\)/g, '\\\\)');\n}\n\n/**\n * XML-escape a string for use inside element content or quoted attribute\n * values. Covers the five canonical XML entities.\n */\nfunction escapeXML(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Hex-encode a UTF-8 string for use inside a pdfmark `<...>` hex stream\n * literal. PostScript hex strings are case-insensitive; we emit lowercase\n * to match the rest of the pdfmark output.\n */\nfunction utf8ToHex(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let hex = '';\n for (const b of bytes) {\n hex += b.toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/**\n * Encode a string as a BOM-prefixed UTF-16BE hex string for pdfmark text\n * values — a parens literal would be read as PDFDocEncoding and garble\n * non-ASCII titles.\n */\nfunction utf16beHex(value: string): string {\n let hex = 'FEFF';\n for (let i = 0; i < value.length; i++) {\n hex += value.charCodeAt(i).toString(16).toUpperCase().padStart(4, '0');\n }\n return hex;\n}\n\n/**\n * Build the strict PDF/X-4 XMP packet body that fully replaces GS's\n * auto-generated XMP. Preflight checks `pdfxid:GTS_PDFXVersion` specifically;\n * older validators (callas, GS) read `pdfx:GTS_PDFXVersion` — we emit both.\n * `xmpMM:DocumentID`, `RenditionClass`, and `VersionID` round out the entries\n * Acrobat flags as missing on a non-strict X-4.\n *\n * GS's legacy auto-XMP uses the `xapMM` prefix which strict Acrobat Preflight\n * rejects. Replacing the whole packet via the Catalog.Metadata pdfmark\n * bypasses that.\n *\n * Every value that also exists in the final Info dictionary must stay\n * equivalent (PDF/X-4): title/dates/creator match the `generatePostDocinfo`\n * pdfmarks; producer mirrors pdfwrite's own Info stamp.\n */\nfunction buildPDFX4XMPPacket(\n title: string,\n timestamps: PDFXTimestamps,\n docId: string,\n producer: string\n): string {\n const titleX = escapeXML(title);\n const nowX = escapeXML(timestamps.xmpDate);\n const docIdX = escapeXML(docId);\n const producerX = escapeXML(producer);\n // U+FEFF after `begin=\"` is the canonical XMP packet BOM marker.\n // eslint-disable-next-line no-irregular-whitespace\n return `<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\"\n xmlns:pdfx=\"http://ns.adobe.com/pdfx/1.3/\"\n xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\"\n xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n <pdfx:GTS_PDFXVersion>PDF/X-4</pdfx:GTS_PDFXVersion>\n <pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>\n <pdf:Trapped>False</pdf:Trapped>\n <pdf:Producer>${producerX}</pdf:Producer>\n <xmp:CreateDate>${nowX}</xmp:CreateDate>\n <xmp:ModifyDate>${nowX}</xmp:ModifyDate>\n <xmp:MetadataDate>${nowX}</xmp:MetadataDate>\n <xmp:CreatorTool>${CREATOR_TOOL}</xmp:CreatorTool>\n <dc:format>application/pdf</dc:format>\n <dc:title>\n <rdf:Alt>\n <rdf:li xml:lang=\"x-default\">${titleX}</rdf:li>\n </rdf:Alt>\n </dc:title>\n <xmpMM:DocumentID>uuid:${docIdX}</xmpMM:DocumentID>\n <xmpMM:RenditionClass>default</xmpMM:RenditionClass>\n <xmpMM:VersionID>1</xmpMM:VersionID>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>`;\n}\n\nexport interface PDFXDefContext {\n iccProfileHex: string;\n outputConditionIdentifier: string;\n outputCondition: string;\n embedICCProfile: boolean;\n timestamps: PDFXTimestamps;\n docId: string;\n /** Producer string pdfwrite stamps into DocInfo, e.g. `GPL Ghostscript 10.03.1`. */\n producer: string;\n}\n\nexport function generatePDFXDef(\n options: PDFXOptions,\n ctx: PDFXDefContext\n): string {\n // Minimal definition when ICC embedding is disabled: no PDF/X conformance\n // markers and no OutputIntent. DOCINFO entries live in the post-input file.\n if (!ctx.embedICCProfile) {\n return `%!\n% PDF Definition File (ICC embedding disabled)`;\n }\n\n const isX4 = options.outputStandard === 'PDF/X-4';\n const headerComment = isX4\n ? '% PDF/X-4 Definition File'\n : '% PDF/X-3 Definition File';\n\n // X-4 strict conformance: remove transfer functions and halftones globally\n // via setdistillerparams. This must run before any pdfmark so it applies\n // to the full pdfwrite session. Strips the inherited /TR and /HT references\n // Acrobat Preflight reports as hundreds of instances on customer files.\n const distillerPrologue = isX4\n ? '<< /TransferFunctionInfo /Remove /HalftoneInfo /Remove >> setdistillerparams\\n'\n : '';\n\n // X-4 strict conformance: write our own XMP packet and attach it to the\n // Catalog via the Metadata pdfmark. This fully replaces GS's auto-generated\n // XMP (which uses the legacy `xapMM` prefix Acrobat Preflight rejects) and\n // gives us complete control over the entries Preflight checks.\n const xmpReplaceBlock = isX4\n ? `\n\n% Strict PDF/X-4 XMP packet (replaces GS's auto-generated XMP)\n[/_objdef {Metadata} /type /stream /OBJ pdfmark\n[{Metadata} <</Type /Metadata /Subtype /XML>> /PUT pdfmark\n[{Metadata} <${utf8ToHex(\n buildPDFX4XMPPacket(\n resolveTitle(options),\n ctx.timestamps,\n ctx.docId,\n ctx.producer\n )\n )}> /PUT pdfmark\n[{Catalog} <</Metadata {Metadata}>> /PUT pdfmark`\n : '';\n\n return `%!\n${headerComment}\n${distillerPrologue}\n% Supply missing print bounds after each page's size and rotation are installed.\n/pdfshowpage_setpage [\n /pdfshowpage_setpage load /exec load\n {\n dup /TrimBox known not 1 index /ArtBox known not and {\n dup /CropBox known {\n gsave newpath\n dup /CropBox get aload pop moveto lineto\n matrix defaultmatrix setmatrix pathbbox\n 4 array astore grestore\n } {\n [0 0 currentpagedevice /PageSize get aload pop]\n } ifelse\n [/TrimBox 3 -1 roll /PAGE pdfmark\n } if\n } /exec load\n] cvx def\n\n% Embed ICC profile as hex stream\n[/_objdef {icc_PDFX} /type /stream /OBJ pdfmark\n[{icc_PDFX} <</N 4>> /PUT pdfmark\n[{icc_PDFX} <${ctx.iccProfileHex}> /PUT pdfmark\n\n% Define OutputIntent with embedded ICC profile\n[/_objdef {OutputIntent_PDFX} /type /dict /OBJ pdfmark\n[{OutputIntent_PDFX} <<\n /Type /OutputIntent\n /S /GTS_PDFX\n /OutputCondition (${escapePSString(ctx.outputCondition)})\n /OutputConditionIdentifier (${escapePSString(ctx.outputConditionIdentifier)})\n /RegistryName (http://www.color.org)\n /DestOutputProfile {icc_PDFX}\n>> /PUT pdfmark\n\n% Add OutputIntent to Catalog\n[{Catalog} <</OutputIntents [{OutputIntent_PDFX}]>> /PUT pdfmark${xmpReplaceBlock}`;\n}\n\n/**\n * DOCINFO pdfmark file that runs AFTER the input PDF. Ghostscript merges the\n * input's Info dictionary during interpretation, so entries written in the\n * pre-input definition file get overridden by the input's values (the engine\n * writes the scene name as `/Title`, for example). Re-asserting the entries\n * afterwards makes them authoritative and keeps them equivalent to the XMP\n * packet, as PDF/X-4 requires. GS derives its auto-XMP for the non-X-4 paths\n * from the final Info dictionary, so those stay synchronized too.\n */\nexport function generatePostDocinfo(\n options: PDFXOptions,\n timestamps: PDFXTimestamps,\n embedICCProfile: boolean\n): string {\n const title = resolveTitle(options);\n const isX4 = options.outputStandard === 'PDF/X-4';\n\n // X-3 keeps the conformance entry in DOCINFO (ISO 15930-6); X-4 keeps it\n // in XMP only. No claim when ICC embedding is off (output is not PDF/X).\n const x3ConformanceLine =\n isX4 || !embedICCProfile\n ? ''\n : '\\n[ /GTS_PDFXVersion (PDF/X-3:2003) /GTS_PDFXConformance (PDF/X-3:2003) /DOCINFO pdfmark';\n\n return `%!\n% Post-input DOCINFO (must stay equivalent to the XMP packet)\n[ /Title <${utf16beHex(title)}> /DOCINFO pdfmark\n[ /Creator (${CREATOR_TOOL}) /DOCINFO pdfmark\n[ /CreationDate (${timestamps.pdfDate}) /DOCINFO pdfmark\n[ /ModDate (${timestamps.pdfDate}) /DOCINFO pdfmark\n[ /Trapped /False /DOCINFO pdfmark${x3ConformanceLine}`;\n}\n","import type { PDFXOptions } from './types/pdfx';\n\nexport interface BuildGhostscriptArgsContext {\n isCMYKProfile: boolean;\n outputPath: string;\n pdfxDefPath: string;\n inputPath: string;\n postDocinfoPath: string;\n}\n\n/**\n * Build the Ghostscript argv for the conversion run.\n *\n * Pure function: no I/O, no side effects. Centralizes the X-3 vs X-4 branch\n * and the `ghostscriptArgs` full-override short-circuit so the call site in\n * `pdfx.ts` stays readable.\n */\nexport function buildGhostscriptArgs(\n options: PDFXOptions,\n ctx: BuildGhostscriptArgsContext\n): string[] {\n // The post-input DOCINFO file must come after the input so its entries win\n // over Info values inherited from the input PDF.\n const trailing = [\n `-sOutputFile=${ctx.outputPath}`,\n ctx.pdfxDefPath,\n ctx.inputPath,\n ctx.postDocinfoPath,\n ];\n\n // Full override: caller takes responsibility for every flag. We still\n // append the positional output/def/input/post quadruplet so callers don't\n // have to know the internal /tmp/ paths. Empty arrays fall through to\n // defaults.\n if (options.ghostscriptArgs && options.ghostscriptArgs.length > 0) {\n return [...options.ghostscriptArgs, ...trailing];\n }\n\n const isX4 = options.outputStandard === 'PDF/X-4';\n\n const args: string[] = [\n '-dBATCH',\n '-dNOPAUSE',\n '-sDEVICE=pdfwrite',\n // PDF/X-4 requires PDF 1.6 (live transparency); X-3 stays at 1.4.\n isX4 ? '-dCompatibilityLevel=1.6' : '-dCompatibilityLevel=1.4',\n // Disable PDF 1.5+ features for X-3 to avoid warnings; harmless on X-4.\n // Keep `-dWriteObjStms=false` on for X-4 too — the integration tests grep\n // the output for strict-conformance markers, and object streams would\n // hide them inside compressed dictionaries.\n '-dWriteObjStms=false',\n '-dWriteXRefStm=false',\n '-dPDFSETTINGS=/prepress',\n '-dSetPageSize=false',\n '-dAutoRotatePages=/None',\n ];\n\n if (isX4) {\n // pdfwrite Flate-compresses the pdfmark-injected XMP Metadata stream,\n // which Acrobat Preflight flags as a PDF/X-4 violation. Costs output\n // size: the ICC profile and other pdfmark streams stay raw.\n args.push('-dCompressStreams=false');\n }\n\n // X-4 keeps transparency live by definition — never push HaveTransparency=false.\n // For X-3, default to flattening so output is strictly compliant; callers\n // can opt out (producing a non-strict X-3 with live transparency).\n if (!isX4 && options.flattenTransparency !== false) {\n args.push('-dHaveTransparency=false');\n }\n\n if (ctx.isCMYKProfile) {\n args.push(\n '-sColorConversionStrategy=CMYK',\n '-dProcessColorModel=/DeviceCMYK',\n '-dConvertCMYKImagesToRGB=false'\n );\n } else {\n args.push('-sColorConversionStrategy=RGB');\n }\n\n return [...args, ...trailing];\n}\n","import type { PDFXOptions, PDFX3Options } from './types/pdfx';\nimport { getDefaultConversionRuntime } from '@imgly/pdf-conversion-utils';\nimport { BlobUtils } from './utils/blob-utils';\nimport { Logger } from './utils/logger';\nimport {\n formatPDFXTimestamps,\n generatePDFXDef,\n generatePostDocinfo,\n} from './pdfx-def';\nimport { buildGhostscriptArgs } from './pdfx-args';\n\n/**\n * maxInputSize stays optional for callers so they can use the default.\n * Helpers require a resolved limit: `size > undefined` would silently skip the size guard.\n */\ninterface ResolvedPDFXOptions extends PDFXOptions {\n maxInputSize: number;\n}\n\n/**\n * PDF/X conversion function.\n *\n * Converts RGB PDF(s) to the selected PDF/X standard (defaults to `PDF/X-4`)\n * using the specified output profile. PDF/X-4 keeps live transparency so\n * vector text on transparent pages stays selectable. Set\n * `outputStandard: 'PDF/X-3'` to fall back to the older PDF 1.4 standard\n * (which requires flattening transparency).\n *\n * Known limitation: `/Author`, `/Subject`, and `/Keywords` entries inherited\n * from the input PDF are carried into the output without XMP counterparts,\n * which preflight tools may flag. CE.SDK exports never write these keys.\n *\n * @overload\n * @param inputPDF Single PDF blob to convert\n * @param options Conversion configuration\n * @returns Promise resolving to converted PDF blob\n *\n * @overload\n * @param inputPDFs Array of PDF blobs to convert\n * @param options Conversion configuration\n * @returns Promise resolving to array of converted PDF blobs\n */\nexport function convertToPDFX(\n inputPDF: Blob,\n options: PDFXOptions\n): Promise<Blob>;\nexport function convertToPDFX(\n inputPDFs: Blob[],\n options: PDFXOptions\n): Promise<Blob[]>;\nexport async function convertToPDFX(\n input: Blob | Blob[],\n options: PDFXOptions\n): Promise<Blob | Blob[]> {\n const maxInputSize =\n options.maxInputSize === undefined\n ? 100 * 1024 * 1024\n : options.maxInputSize;\n if (!Number.isSafeInteger(maxInputSize) || maxInputSize <= 0) {\n throw new Error('maxInputSize must be a positive safe integer in bytes');\n }\n\n // Apply the X-4 default at the entry point so internal helpers see a\n // concrete outputStandard. Explicit caller values win over the default.\n const resolvedOptions: ResolvedPDFXOptions = {\n outputStandard: 'PDF/X-4',\n ...options,\n maxInputSize,\n };\n\n // Handle array input (batch processing)\n if (Array.isArray(input)) {\n if (input.length === 0) {\n return [];\n }\n\n // Process each blob sequentially to avoid overwhelming the WASM module\n const results: Blob[] = [];\n for (let i = 0; i < input.length; i++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n const converted = await convertToPDFXSingle(input[i], resolvedOptions);\n results.push(converted);\n } catch (error) {\n const batchError = new Error(\n `Failed to convert PDF ${i + 1} of ${input.length}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error }\n );\n if (error instanceof Error && 'code' in error) {\n Object.assign(batchError, {\n code: error.code,\n ...('diagnostics' in error && {\n diagnostics: error.diagnostics,\n }),\n ...('exitCode' in error && { exitCode: error.exitCode }),\n });\n }\n throw batchError;\n }\n }\n return results;\n }\n\n // Handle single blob input\n return convertToPDFXSingle(input, resolvedOptions);\n}\n\n/**\n * Resolves a preset to the ICC profile bundled next to this module.\n *\n * Every URL is a literal, because a bundler copies a profile into the build\n * only when it can read the path. Built from a variable it copies none, and\n * the export fails on whatever the host returns instead.\n */\nfunction bundledProfileURL(profile: string): string {\n switch (profile) {\n case 'gracol':\n return new URL('./GRACoL2013_CRPC6.icc', import.meta.url).href;\n case 'srgb':\n return new URL('./sRGB_IEC61966-2-1.icc', import.meta.url).href;\n default:\n return new URL('./ISOcoated_v2_eci.icc', import.meta.url).href;\n }\n}\n\n/**\n * @deprecated Use `convertToPDFX` instead. This alias is preserved for\n * backwards compatibility and will be removed in a future major release.\n *\n * Defaults to `outputStandard: 'PDF/X-3'` to match the historical behavior\n * of this function — unlike `convertToPDFX`, which defaults to PDF/X-4.\n * Callers can still pass `outputStandard: 'PDF/X-4'` explicitly to opt in.\n */\nexport function convertToPDFX3(\n inputPDF: Blob,\n options: PDFX3Options\n): Promise<Blob>;\nexport function convertToPDFX3(\n inputPDFs: Blob[],\n options: PDFX3Options\n): Promise<Blob[]>;\nexport function convertToPDFX3(\n input: Blob | Blob[],\n options: PDFX3Options\n): Promise<Blob | Blob[]> {\n // Preserve historical X-3 default for the deprecated alias. Explicit\n // caller values still win, so { outputStandard: 'PDF/X-4' } also works.\n const x3Defaulted: PDFX3Options = { outputStandard: 'PDF/X-3', ...options };\n // Delegate without narrowing — runtime branch on Array.isArray inside\n // convertToPDFX already matches the overload semantics.\n return convertToPDFX(input as Blob, x3Defaulted);\n}\n\n/**\n * Internal function to convert a single PDF\n */\nasync function convertToPDFXSingle(\n inputPDF: Blob,\n options: ResolvedPDFXOptions\n): Promise<Blob> {\n // Validate inputs\n if (!(inputPDF instanceof Blob)) {\n throw new Error('Input must be a Blob');\n }\n\n if (inputPDF.size === 0) {\n throw new Error('Input PDF is empty');\n }\n\n if (inputPDF.size > options.maxInputSize) {\n throw new Error(\n `Input PDF too large (${inputPDF.size} bytes). Maximum: ${options.maxInputSize} bytes`\n );\n }\n\n // Validate output profile is provided\n if (!options.outputProfile) {\n throw new Error(\n 'outputProfile is required. Must be one of: \"gracol\", \"fogra39\", \"srgb\", \"custom\"'\n );\n }\n\n // Validate output profile value\n const validProfiles = ['gracol', 'fogra39', 'srgb', 'custom'];\n if (!validProfiles.includes(options.outputProfile)) {\n throw new Error(\n `Invalid outputProfile \"${\n options.outputProfile\n }\". Must be one of: ${validProfiles.join(', ')}`\n );\n }\n\n // Validate custom profile requirement\n if (options.outputProfile === 'custom' && !options.customProfile) {\n throw new Error(\n 'customProfile Blob is required when outputProfile is \"custom\"'\n );\n }\n\n // Validate custom profile if provided\n if (options.customProfile && !(options.customProfile instanceof Blob)) {\n throw new Error('customProfile must be a Blob');\n }\n\n // Validate PDF format\n const isValidPDF = await BlobUtils.validatePDF(inputPDF);\n if (!isValidPDF) {\n throw new Error('Invalid PDF format');\n }\n\n const runtime = options.runtime ?? getDefaultConversionRuntime();\n const operationOptions = {\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n };\n const { version } = await runtime.preload(operationOptions);\n const logger = new Logger('PDFXConversion');\n logger.info('Converting PDF in Ghostscript worker');\n const files: Record<string, Uint8Array | string> = {};\n // Setup file paths\n const inputPath = '/work/input.pdf';\n const outputPath = '/work/output.pdf';\n const pdfxDefPath = '/work/pdfx_def.ps';\n const postDocinfoPath = '/work/pdfx_post.ps';\n const customProfilePath = '/work/custom.icc';\n\n // Write input PDF to virtual filesystem\n files['input.pdf'] = await BlobUtils.toUint8Array(inputPDF);\n\n // Write ICC profiles to virtual filesystem\n if (options.outputProfile === 'custom' && options.customProfile) {\n files['custom.icc'] = await BlobUtils.toUint8Array(options.customProfile);\n } else if (options.outputProfile !== 'custom') {\n // Load the bundled ICC profile\n const profileInfo =\n PROFILE_PRESETS[options.outputProfile as keyof typeof PROFILE_PRESETS];\n\n // Load ICC profile - different approach for Node.js vs browser\n const isNode =\n typeof process !== 'undefined' && process.versions?.node != null;\n\n let profileBlob: Blob;\n\n if (isNode) {\n // Node.js: Load from filesystem using readFileSync\n // Use indirect dynamic import to prevent Webpack 5 from statically analyzing these imports\n // But use direct imports in test environments (vitest) where indirect imports bypass mocking\n // See: https://github.com/imgly/ubq/issues/11471\n const isTestEnv =\n process.env.VITEST === 'true' || process.env.NODE_ENV === 'test';\n\n // Note: new Function() could fail in CSP-restricted environments, but CSP is a browser\n // security mechanism and doesn't apply to Node.js. This code only runs in Node.js (isNode check above).\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const indirectImport = new Function('s', 'return import(s)') as (\n s: string\n ) => Promise<any>;\n const dynamicImport = isTestEnv\n ? (s: string) => import(s)\n : indirectImport;\n\n const { readFileSync } = await dynamicImport('fs');\n const { fileURLToPath } = await dynamicImport('url');\n const { dirname, join } = await dynamicImport('path');\n\n // Get the directory of the built module\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const profileFilePath = join(moduleDir, profileInfo.file);\n\n const profileData = readFileSync(profileFilePath);\n profileBlob = new Blob([profileData], {\n type: 'application/vnd.iccprofile',\n });\n } else {\n // Browser: Use fetch\n const profileUrl = bundledProfileURL(options.outputProfile);\n const profileResponse = await fetch(profileUrl, {\n signal: options.signal,\n });\n if (!profileResponse.ok) {\n throw new Error(\n `Failed to load ICC profile ${profileInfo.file}: ${profileResponse.statusText}`\n );\n }\n profileBlob = await profileResponse.blob();\n }\n\n files[profileInfo.file] = await BlobUtils.toUint8Array(profileBlob);\n }\n\n // Determine ICC profile path and metadata for Ghostscript\n let iccProfilePath: string;\n let outputConditionIdentifier: string;\n let outputCondition: string;\n\n if (options.outputProfile === 'custom') {\n iccProfilePath = customProfilePath;\n // Use custom values or defaults\n outputConditionIdentifier =\n options.outputConditionIdentifier || 'Custom Profile';\n outputCondition = options.outputCondition || 'Custom ICC Profile';\n } else {\n const preset =\n PROFILE_PRESETS[options.outputProfile as keyof typeof PROFILE_PRESETS];\n iccProfilePath = `/work/${preset.file}`;\n // Allow overriding preset values\n outputConditionIdentifier =\n options.outputConditionIdentifier || preset.identifier;\n outputCondition = options.outputCondition || preset.info;\n }\n\n // Read ICC profile data to inspect its color space\n const iccData = files[iccProfilePath.slice('/work/'.length)] as Uint8Array;\n\n // Determine color conversion strategy based on profile type\n // ICC profile color space is at bytes 16-19\n // 'RGB ' = 0x52474220, 'CMYK' = 0x434D594B\n const colorSpaceBytes = iccData.slice(16, 20);\n const colorSpaceStr = String.fromCharCode(...colorSpaceBytes);\n const isCMYKProfile = colorSpaceStr.trim() === 'CMYK';\n\n // Embed ICC profile + PDF/X-3 OutputIntent by default. Callers can opt\n // out (e.g. when a downstream prepress pipeline handles ICC embedding).\n const embedICCProfile = options.embedICCProfile !== false;\n\n // Only hex-encode the profile for pdfmark embedding when we'll actually\n // embed it. WASM doesn't support (file) (r) file syntax, so pdfmark needs\n // the raw hex stream inline.\n const iccHex = embedICCProfile\n ? Array.from(iccData)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n : '';\n\n // One instant for both metadata stores (DocInfo and XMP dates).\n const timestamps = formatPDFXTimestamps(new Date());\n\n // pdfwrite stamps its own Producer into DocInfo (not overridable in GPL\n // builds); the XMP packet must mirror it exactly.\n if (typeof version !== 'string' || version.length === 0) {\n throw new Error(\n 'Ghostscript module reported no version; cannot mirror the Producer into XMP'\n );\n }\n\n const pdfxDefinition = generatePDFXDef(options, {\n iccProfileHex: iccHex,\n outputConditionIdentifier,\n outputCondition,\n embedICCProfile,\n timestamps,\n docId: generateDocumentId(),\n producer: `GPL Ghostscript ${version}`,\n });\n files['pdfx_def.ps'] = pdfxDefinition;\n files['pdfx_post.ps'] = generatePostDocinfo(\n options,\n timestamps,\n embedICCProfile\n );\n\n // Note on ICC profile selection when embedICCProfile is false:\n // pdfwrite's color conversion uses Ghostscript's bundled default CMYK\n // profile (regardless of the selected outputProfile) since\n // `-sOutputICCProfile` only controls OutputIntent embedding on the\n // pdfwrite device, not the conversion math. That's acceptable here\n // because downstream prepress pipelines (ZePrA, PitStop) are expected\n // to re-normalize colors using their own profile anyway; the plugin's\n // job in this mode is only to deliver a device CMYK PDF without an\n // embedded OutputIntent.\n const gsArgs = buildGhostscriptArgs(options, {\n isCMYKProfile,\n outputPath,\n pdfxDefPath,\n inputPath,\n postDocinfoPath,\n });\n\n const result = await runtime.run(\n { files, args: gsArgs, outputFiles: ['output.pdf'] },\n {\n ...operationOptions,\n // PDF/X-4 disables stream compression, so a valid output can grow far\n // beyond its input. Keep the plugin's historical unrestricted output\n // behavior unless the caller requests a limit.\n maxOutputBytes: options.maxOutputBytes ?? Number.MAX_SAFE_INTEGER,\n }\n );\n return new Blob([new Uint8Array(result.files['output.pdf'])], {\n type: 'application/pdf',\n });\n}\n\n/**\n * Generate an RFC 4122 v4 UUID for the XMP `xmpMM:DocumentID` field. Uses\n * the Web Crypto API where available (modern browsers, Node 19+); falls\n * back to a Math.random shim for older Node runtimes. The DocumentID is\n * an identifier, not a security boundary, so the fallback is acceptable.\n */\nfunction generateDocumentId(): string {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.floor(Math.random() * 16);\n // Standard RFC 4122 v4 y-nibble construction: clamp to 10/11 (binary) via\n // bit-clear of 0x3 then set 0x8. Bitwise math is unavoidable here.\n // eslint-disable-next-line no-bitwise\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// Profile presets from the spec\nconst PROFILE_PRESETS = {\n gracol: {\n file: 'GRACoL2013_CRPC6.icc',\n identifier: 'CGATS 21.2',\n info: 'GRACoL 2013 CRPC6',\n },\n fogra39: {\n file: 'ISOcoated_v2_eci.icc',\n identifier: 'FOGRA39',\n info: 'ISO Coated v2 (ECI)',\n },\n srgb: {\n file: 'sRGB_IEC61966-2-1.icc',\n identifier: 'sRGB IEC61966-2.1',\n info: 'sRGB IEC61966-2.1',\n },\n};\n"],"mappings":"A,0EAAA,IAAaA,EAAb,KAAuB,CACrB,aAAa,aAAa,EAAiC,CACzD,GAAIC,EAAK,YAAa,CACpB,IAAMC,EAAS,MAAMD,EAAK,YAAY,EACtC,OAAO,IAAI,WAAWC,CAAM,CAC9B,CAGA,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,IAAMC,EAAS,IAAI,WACnB,EAAO,WAAe,CAChBA,EAAO,kBAAkB,YAC3BC,EAAQ,IAAI,WAAWD,EAAO,MAAM,CAAC,EAErCE,EAAO,gBAAI,MAAM,oCAAoC,CAAC,CAE1D,EACA,EAAO,YAAgBA,EAAOF,EAAO,KAAK,EAC1CA,EAAO,kBAAkBF,CAAI,CAC/B,CAAC,CACH,CAEA,aAAa,YAAY,EAA8B,CACrD,GAAI,CACF,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G,CAAC,CAAC,CAC3C,KAAK,EAAE,EACV,GAGEM,EAAarB,kBAAqB,IAAI,IAAM,EAIlD,GAAI,OAAO8E,GAAY,UAAYA,EAAQ,SAAW,EACpD,MAAU,MACR,6EACF,EAYF,EAAM,eATiBrD,EAAgB3B,EAAS,CAC9C,cAAe+E,EACf,4BACA,kBACA,kBACA,aACA,MAAOE,EAAmB,EAC1B,SAAU,mBAAmBD,GAC/B,CACoC,EACpC,EAAM,gBAAkB/C,EACtBjC,EACAuB,EACAY,CACF,EAWA,IAAM+C,EAAS9C,EAAqBpC,EAAS,CAC3C,gBACA,8BACA,gCACA,4BACA,oCACF,CAAC,EAEKmF,EAAS,MAAM9B,EAAQ,IAC3B,CAAE,QAAO,KAAM6B,EAAQ,YAAa,CAAC,YAAY,CAAE,EACnD,CACE,GAAG3B,EAIH,eAAgBvD,EAAQ,uBAC1B,CACF,EACA,OAAO,IAAI,KAAK,CAAC,IAAI,WAAWmF,EAAO,MAAM,aAAa,CAAC,EAAG,CAC5D,KAAM,iBACR,CAAC,CACH,CAQA,SAASF,GAA6B,CAIpC,OAHI,OAAO,WAAW,QAAQ,YAAe,WACpC,WAAW,OAAO,WAAW,EAE/B,uCAAuC,QAAQ,QAAU,GAAM,CACpE,IAAM9F,EAAI,KAAK,MAAM,KAAK,OAAO,EAAI,EAAE,EAKvC,OADUiG,IAAM,IAAMjG,EAAKA,EAAI,EAAO,EAAA,CAC7B,SAAS,EAAE,CACtB,CAAC,CACH,CAGA,MAAMuE,EAAkB,CACtB,OAAQ,CACN,KAAM,uBACN,WAAY,aACZ,KAAM,mBACR,EACA,QAAS,CACP,KAAM,uBACN,WAAY,UACZ,KAAM,qBACR,EACA,KAAM,CACJ,KAAM,wBACN,WAAY,oBACZ,KAAM,mBACR,CACF,E"}
|
|
1
|
+
{"version":3,"file":"index.npm.mjs","names":["BlobUtils","blob","buffer","reader","resolve","reject","data","pdfHeader","i","_typeof","o","toPrimitive","t","e","r","toPropertyKey","_defineProperty","Logger","component","level","message","levelOrder","entry","prefix","logMessage","CREATOR_TOOL","resolveTitle","options","match","formatPDFXTimestamps","date","p","n","y","mo","d","h","mi","escapePSString","value","escapeXML","utf8ToHex","bytes","hex","b","utf16beHex","buildPDFX4XMPPacket","titleX","title","nowX","timestamps","docIdX","docId","producer","generatePDFXDef","ctx","isX4","headerComment","distillerPrologue","xmpReplaceBlock","generatePostDocinfo","x3ConformanceLine","embedICCProfile","buildGhostscriptArgs","trailing","args","convertToPDFX","maxInputSize","resolvedOptions","input","results","converted","convertToPDFXSingle","error","batchError","bundledProfileURL","file","convertToPDFX3","inputPDF","validProfiles","runtime","getDefaultConversionRuntime","operationOptions","files","profileInfo","resolvePreset","isNode","profileBlob","isTestEnv","indirectImport","dynamicImport","s","profileData","readFileSync","join","dirname","fileURLToPath","profileUrl","profileResponse","iccProfilePath","outputConditionIdentifier","outputCondition","preset","iccData","colorSpaceBytes","isCMYKProfile","iccHex","version","generateDocumentId","gsArgs","result","c","PROFILE_PRESETS","GRACOL_2006_PRESET"],"sources":["../src/utils/blob-utils.ts","../src/utils/logger.ts","../src/pdfx-def.ts","../src/pdfx-args.ts","../src/pdfx.ts"],"sourcesContent":["export class BlobUtils {\n static async toUint8Array(blob: Blob): Promise<Uint8Array> {\n if (blob.arrayBuffer) {\n const buffer = await blob.arrayBuffer();\n return new Uint8Array(buffer);\n }\n\n // Fallback for older browsers\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => {\n if (reader.result instanceof ArrayBuffer) {\n resolve(new Uint8Array(reader.result));\n } else {\n reject(new Error('Failed to read blob as ArrayBuffer'));\n }\n };\n reader.onerror = () => reject(reader.error);\n reader.readAsArrayBuffer(blob);\n });\n }\n\n static async validatePDF(blob: Blob): Promise<boolean> {\n try {\n const data = await this.toUint8Array(blob);\n\n // Check PDF magic number\n const pdfHeader = new Uint8Array([0x25, 0x50, 0x44, 0x46]); // %PDF\n\n if (data.length < 4) {\n return false;\n }\n\n for (let i = 0; i < 4; i++) {\n if (data[i] !== pdfHeader[i]) {\n return false;\n }\n }\n\n return true;\n } catch {\n return false;\n }\n }\n}\n","/* eslint-disable no-console */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface LogEntry {\n timestamp: number;\n level: LogLevel;\n component: string;\n message: string;\n data?: any;\n}\n\nexport class Logger {\n private static globalLogLevel: LogLevel = 'warn';\n\n private static logs: LogEntry[] = [];\n\n private static maxLogs = 1000;\n\n constructor(private component: string) {}\n\n static setLogLevel(level: LogLevel): void {\n Logger.globalLogLevel = level;\n }\n\n static getLogs(): LogEntry[] {\n return [...Logger.logs];\n }\n\n static clearLogs(): void {\n Logger.logs = [];\n }\n\n debug(message: string, data?: any): void {\n this.log('debug', message, data);\n }\n\n info(message: string, data?: any): void {\n this.log('info', message, data);\n }\n\n warn(message: string, data?: any): void {\n this.log('warn', message, data);\n }\n\n error(message: string, data?: any): void {\n this.log('error', message, data);\n }\n\n private log(level: LogLevel, message: string, data?: any): void {\n const levelOrder: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n if (levelOrder[level] < levelOrder[Logger.globalLogLevel]) {\n return;\n }\n\n const entry: LogEntry = {\n timestamp: Date.now(),\n level,\n component: this.component,\n message,\n data,\n };\n\n Logger.logs.push(entry);\n\n // Keep logs under the limit\n if (Logger.logs.length > Logger.maxLogs) {\n Logger.logs = Logger.logs.slice(-Logger.maxLogs);\n }\n\n // Console output\n const prefix = `[${new Date().toISOString()}] [${level.toUpperCase()}] [${\n this.component\n }]`;\n const logMessage = data ? `${message} ${JSON.stringify(data)}` : message;\n\n switch (level) {\n case 'debug':\n console.debug(prefix, logMessage);\n break;\n case 'info':\n console.info(prefix, logMessage);\n break;\n case 'warn':\n console.warn(prefix, logMessage);\n break;\n case 'error':\n console.error(prefix, logMessage);\n break;\n default:\n // All log levels handled above\n break;\n }\n }\n}\n","import type { PDFXOptions } from './types/pdfx';\n\n/** Value written to DocInfo `/Creator` and XMP `xmp:CreatorTool`. */\nconst CREATOR_TOOL = 'IMG.LY';\n\n/**\n * Resolve the document title once for BOTH metadata stores. Lone surrogates\n * and XML-illegal control characters would desync or corrupt the XMP side,\n * so they are repaired/stripped before either encoding sees the value.\n */\nfunction resolveTitle(options: PDFXOptions): string {\n const sanitized = (options.title || '')\n // Pairs match first and stay; any surrogate left over is unpaired. No lookbehind: Safari 15.6.\n .replace(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDFFF]/g, (match) =>\n match.length === 2 ? match : '�'\n )\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g, '');\n return sanitized || 'Untitled';\n}\n\n/**\n * One instant rendered in both metadata date formats. PDF/X-4 requires the\n * DocInfo dates and the XMP dates to describe the same time, so both strings\n * must always be derived from the same `Date` via `formatPDFXTimestamps`.\n */\nexport interface PDFXTimestamps {\n /** PDF date string for DOCINFO pdfmarks, e.g. `D:20260722140113+00'00'` */\n pdfDate: string;\n /** ISO-8601 string for the XMP packet, e.g. `2026-07-22T14:01:13+00:00` */\n xmpDate: string;\n}\n\n/**\n * Render `date` at second precision in UTC. Sub-second precision is dropped\n * deliberately: the PDF date format has none, and a fractional part in the\n * XMP value would break the Info↔XMP equivalence preflight checks.\n */\nexport function formatPDFXTimestamps(date: Date): PDFXTimestamps {\n if (Number.isNaN(date.getTime())) {\n throw new Error('formatPDFXTimestamps: invalid Date');\n }\n const p = (n: number) => String(n).padStart(2, '0');\n const y = date.getUTCFullYear();\n const mo = p(date.getUTCMonth() + 1);\n const d = p(date.getUTCDate());\n const h = p(date.getUTCHours());\n const mi = p(date.getUTCMinutes());\n const s = p(date.getUTCSeconds());\n return {\n pdfDate: `D:${y}${mo}${d}${h}${mi}${s}+00'00'`,\n xmpDate: `${y}-${mo}-${d}T${h}:${mi}:${s}+00:00`,\n };\n}\n\n/**\n * Escape a string for use inside a parens-delimited PostScript string.\n * Only `(`, `)`, `\\` need escaping; XML angle brackets and ampersands pass\n * through untouched (PostScript doesn't interpret them).\n */\nfunction escapePSString(value: string): string {\n return value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\(/g, '\\\\(')\n .replace(/\\)/g, '\\\\)');\n}\n\n/**\n * XML-escape a string for use inside element content or quoted attribute\n * values. Covers the five canonical XML entities.\n */\nfunction escapeXML(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Hex-encode a UTF-8 string for use inside a pdfmark `<...>` hex stream\n * literal. PostScript hex strings are case-insensitive; we emit lowercase\n * to match the rest of the pdfmark output.\n */\nfunction utf8ToHex(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let hex = '';\n for (const b of bytes) {\n hex += b.toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/**\n * Encode a string as a BOM-prefixed UTF-16BE hex string for pdfmark text\n * values — a parens literal would be read as PDFDocEncoding and garble\n * non-ASCII titles.\n */\nfunction utf16beHex(value: string): string {\n let hex = 'FEFF';\n for (let i = 0; i < value.length; i++) {\n hex += value.charCodeAt(i).toString(16).toUpperCase().padStart(4, '0');\n }\n return hex;\n}\n\n/**\n * Build the strict PDF/X-4 XMP packet body that fully replaces GS's\n * auto-generated XMP. Preflight checks `pdfxid:GTS_PDFXVersion` specifically;\n * older validators (callas, GS) read `pdfx:GTS_PDFXVersion` — we emit both.\n * `xmpMM:DocumentID`, `RenditionClass`, and `VersionID` round out the entries\n * Acrobat flags as missing on a non-strict X-4.\n *\n * GS's legacy auto-XMP uses the `xapMM` prefix which strict Acrobat Preflight\n * rejects. Replacing the whole packet via the Catalog.Metadata pdfmark\n * bypasses that.\n *\n * Every value that also exists in the final Info dictionary must stay\n * equivalent (PDF/X-4): title/dates/creator match the `generatePostDocinfo`\n * pdfmarks; producer mirrors pdfwrite's own Info stamp.\n */\nfunction buildPDFX4XMPPacket(\n title: string,\n timestamps: PDFXTimestamps,\n docId: string,\n producer: string\n): string {\n const titleX = escapeXML(title);\n const nowX = escapeXML(timestamps.xmpDate);\n const docIdX = escapeXML(docId);\n const producerX = escapeXML(producer);\n // U+FEFF after `begin=\"` is the canonical XMP packet BOM marker.\n // eslint-disable-next-line no-irregular-whitespace\n return `<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\"\n xmlns:pdfx=\"http://ns.adobe.com/pdfx/1.3/\"\n xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\"\n xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n <pdfx:GTS_PDFXVersion>PDF/X-4</pdfx:GTS_PDFXVersion>\n <pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>\n <pdf:Trapped>False</pdf:Trapped>\n <pdf:Producer>${producerX}</pdf:Producer>\n <xmp:CreateDate>${nowX}</xmp:CreateDate>\n <xmp:ModifyDate>${nowX}</xmp:ModifyDate>\n <xmp:MetadataDate>${nowX}</xmp:MetadataDate>\n <xmp:CreatorTool>${CREATOR_TOOL}</xmp:CreatorTool>\n <dc:format>application/pdf</dc:format>\n <dc:title>\n <rdf:Alt>\n <rdf:li xml:lang=\"x-default\">${titleX}</rdf:li>\n </rdf:Alt>\n </dc:title>\n <xmpMM:DocumentID>uuid:${docIdX}</xmpMM:DocumentID>\n <xmpMM:RenditionClass>default</xmpMM:RenditionClass>\n <xmpMM:VersionID>1</xmpMM:VersionID>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>`;\n}\n\nexport interface PDFXDefContext {\n iccProfileHex: string;\n outputConditionIdentifier: string;\n outputCondition: string;\n embedICCProfile: boolean;\n timestamps: PDFXTimestamps;\n docId: string;\n /** Producer string pdfwrite stamps into DocInfo, e.g. `GPL Ghostscript 10.03.1`. */\n producer: string;\n}\n\nexport function generatePDFXDef(\n options: PDFXOptions,\n ctx: PDFXDefContext\n): string {\n // Minimal definition when ICC embedding is disabled: no PDF/X conformance\n // markers and no OutputIntent. DOCINFO entries live in the post-input file.\n if (!ctx.embedICCProfile) {\n return `%!\n% PDF Definition File (ICC embedding disabled)`;\n }\n\n const isX4 = options.outputStandard === 'PDF/X-4';\n const headerComment = isX4\n ? '% PDF/X-4 Definition File'\n : '% PDF/X-3 Definition File';\n\n // X-4 strict conformance: remove transfer functions and halftones globally\n // via setdistillerparams. This must run before any pdfmark so it applies\n // to the full pdfwrite session. Strips the inherited /TR and /HT references\n // Acrobat Preflight reports as hundreds of instances on customer files.\n const distillerPrologue = isX4\n ? '<< /TransferFunctionInfo /Remove /HalftoneInfo /Remove >> setdistillerparams\\n'\n : '';\n\n // X-4 strict conformance: write our own XMP packet and attach it to the\n // Catalog via the Metadata pdfmark. This fully replaces GS's auto-generated\n // XMP (which uses the legacy `xapMM` prefix Acrobat Preflight rejects) and\n // gives us complete control over the entries Preflight checks.\n const xmpReplaceBlock = isX4\n ? `\n\n% Strict PDF/X-4 XMP packet (replaces GS's auto-generated XMP)\n[/_objdef {Metadata} /type /stream /OBJ pdfmark\n[{Metadata} <</Type /Metadata /Subtype /XML>> /PUT pdfmark\n[{Metadata} <${utf8ToHex(\n buildPDFX4XMPPacket(\n resolveTitle(options),\n ctx.timestamps,\n ctx.docId,\n ctx.producer\n )\n )}> /PUT pdfmark\n[{Catalog} <</Metadata {Metadata}>> /PUT pdfmark`\n : '';\n\n return `%!\n${headerComment}\n${distillerPrologue}\n% Supply missing print bounds after each page's size and rotation are installed.\n/pdfshowpage_setpage [\n /pdfshowpage_setpage load /exec load\n {\n dup /TrimBox known not 1 index /ArtBox known not and {\n dup /CropBox known {\n gsave newpath\n dup /CropBox get aload pop moveto lineto\n matrix defaultmatrix setmatrix pathbbox\n 4 array astore grestore\n } {\n [0 0 currentpagedevice /PageSize get aload pop]\n } ifelse\n [/TrimBox 3 -1 roll /PAGE pdfmark\n } if\n } /exec load\n] cvx def\n\n% Embed ICC profile as hex stream\n[/_objdef {icc_PDFX} /type /stream /OBJ pdfmark\n[{icc_PDFX} <</N 4>> /PUT pdfmark\n[{icc_PDFX} <${ctx.iccProfileHex}> /PUT pdfmark\n\n% Define OutputIntent with embedded ICC profile\n[/_objdef {OutputIntent_PDFX} /type /dict /OBJ pdfmark\n[{OutputIntent_PDFX} <<\n /Type /OutputIntent\n /S /GTS_PDFX\n /OutputCondition (${escapePSString(ctx.outputCondition)})\n /OutputConditionIdentifier (${escapePSString(ctx.outputConditionIdentifier)})\n /RegistryName (http://www.color.org)\n /DestOutputProfile {icc_PDFX}\n>> /PUT pdfmark\n\n% Add OutputIntent to Catalog\n[{Catalog} <</OutputIntents [{OutputIntent_PDFX}]>> /PUT pdfmark${xmpReplaceBlock}`;\n}\n\n/**\n * DOCINFO pdfmark file that runs AFTER the input PDF. Ghostscript merges the\n * input's Info dictionary during interpretation, so entries written in the\n * pre-input definition file get overridden by the input's values (the engine\n * writes the scene name as `/Title`, for example). Re-asserting the entries\n * afterwards makes them authoritative and keeps them equivalent to the XMP\n * packet, as PDF/X-4 requires. GS derives its auto-XMP for the non-X-4 paths\n * from the final Info dictionary, so those stay synchronized too.\n */\nexport function generatePostDocinfo(\n options: PDFXOptions,\n timestamps: PDFXTimestamps,\n embedICCProfile: boolean\n): string {\n const title = resolveTitle(options);\n const isX4 = options.outputStandard === 'PDF/X-4';\n\n // X-3 keeps the conformance entry in DOCINFO (ISO 15930-6); X-4 keeps it\n // in XMP only. No claim when ICC embedding is off (output is not PDF/X).\n const x3ConformanceLine =\n isX4 || !embedICCProfile\n ? ''\n : '\\n[ /GTS_PDFXVersion (PDF/X-3:2003) /GTS_PDFXConformance (PDF/X-3:2003) /DOCINFO pdfmark';\n\n return `%!\n% Post-input DOCINFO (must stay equivalent to the XMP packet)\n[ /Title <${utf16beHex(title)}> /DOCINFO pdfmark\n[ /Creator (${CREATOR_TOOL}) /DOCINFO pdfmark\n[ /CreationDate (${timestamps.pdfDate}) /DOCINFO pdfmark\n[ /ModDate (${timestamps.pdfDate}) /DOCINFO pdfmark\n[ /Trapped /False /DOCINFO pdfmark${x3ConformanceLine}`;\n}\n","import type { PDFXOptions } from './types/pdfx';\n\nexport interface BuildGhostscriptArgsContext {\n isCMYKProfile: boolean;\n outputPath: string;\n pdfxDefPath: string;\n inputPath: string;\n postDocinfoPath: string;\n}\n\n/**\n * Build the Ghostscript argv for the conversion run.\n *\n * Pure function: no I/O, no side effects. Centralizes the X-3 vs X-4 branch\n * and the `ghostscriptArgs` full-override short-circuit so the call site in\n * `pdfx.ts` stays readable.\n */\nexport function buildGhostscriptArgs(\n options: PDFXOptions,\n ctx: BuildGhostscriptArgsContext\n): string[] {\n // The post-input DOCINFO file must come after the input so its entries win\n // over Info values inherited from the input PDF.\n const trailing = [\n `-sOutputFile=${ctx.outputPath}`,\n ctx.pdfxDefPath,\n ctx.inputPath,\n ctx.postDocinfoPath,\n ];\n\n // Full override: caller takes responsibility for every flag. We still\n // append the positional output/def/input/post quadruplet so callers don't\n // have to know the internal /tmp/ paths. Empty arrays fall through to\n // defaults.\n if (options.ghostscriptArgs && options.ghostscriptArgs.length > 0) {\n return [...options.ghostscriptArgs, ...trailing];\n }\n\n const isX4 = options.outputStandard === 'PDF/X-4';\n\n const args: string[] = [\n '-dBATCH',\n '-dNOPAUSE',\n '-sDEVICE=pdfwrite',\n // PDF/X-4 requires PDF 1.6 (live transparency); X-3 stays at 1.4.\n isX4 ? '-dCompatibilityLevel=1.6' : '-dCompatibilityLevel=1.4',\n // Disable PDF 1.5+ features for X-3 to avoid warnings; harmless on X-4.\n // Keep `-dWriteObjStms=false` on for X-4 too — the integration tests grep\n // the output for strict-conformance markers, and object streams would\n // hide them inside compressed dictionaries.\n '-dWriteObjStms=false',\n '-dWriteXRefStm=false',\n '-dPDFSETTINGS=/prepress',\n '-dSetPageSize=false',\n '-dAutoRotatePages=/None',\n ];\n\n if (isX4) {\n // pdfwrite Flate-compresses the pdfmark-injected XMP Metadata stream,\n // which Acrobat Preflight flags as a PDF/X-4 violation. Costs output\n // size: the ICC profile and other pdfmark streams stay raw.\n args.push('-dCompressStreams=false');\n }\n\n // X-4 keeps transparency live by definition — never push HaveTransparency=false.\n // For X-3, default to flattening so output is strictly compliant; callers\n // can opt out (producing a non-strict X-3 with live transparency).\n if (!isX4 && options.flattenTransparency !== false) {\n args.push('-dHaveTransparency=false');\n }\n\n if (ctx.isCMYKProfile) {\n args.push(\n '-sColorConversionStrategy=CMYK',\n '-dProcessColorModel=/DeviceCMYK',\n '-dConvertCMYKImagesToRGB=false'\n );\n } else {\n args.push('-sColorConversionStrategy=RGB');\n }\n\n return [...args, ...trailing];\n}\n","import type { PDFXOptions, PDFX3Options } from './types/pdfx';\nimport { getDefaultConversionRuntime } from '@imgly/pdf-conversion-utils';\nimport { BlobUtils } from './utils/blob-utils';\nimport { Logger } from './utils/logger';\nimport {\n formatPDFXTimestamps,\n generatePDFXDef,\n generatePostDocinfo,\n} from './pdfx-def';\nimport { buildGhostscriptArgs } from './pdfx-args';\n\n/**\n * maxInputSize stays optional for callers so they can use the default.\n * Helpers require a resolved limit: `size > undefined` would silently skip the size guard.\n */\ninterface ResolvedPDFXOptions extends PDFXOptions {\n maxInputSize: number;\n}\n\n/**\n * PDF/X conversion function.\n *\n * Converts RGB PDF(s) to the selected PDF/X standard (defaults to `PDF/X-4`)\n * using the specified output profile. PDF/X-4 keeps live transparency so\n * vector text on transparent pages stays selectable. Set\n * `outputStandard: 'PDF/X-3'` to fall back to the older PDF 1.4 standard\n * (which requires flattening transparency).\n *\n * Known limitation: `/Author`, `/Subject`, and `/Keywords` entries inherited\n * from the input PDF are carried into the output without XMP counterparts,\n * which preflight tools may flag. CE.SDK exports never write these keys.\n *\n * @overload\n * @param inputPDF Single PDF blob to convert\n * @param options Conversion configuration\n * @returns Promise resolving to converted PDF blob\n *\n * @overload\n * @param inputPDFs Array of PDF blobs to convert\n * @param options Conversion configuration\n * @returns Promise resolving to array of converted PDF blobs\n */\nexport function convertToPDFX(\n inputPDF: Blob,\n options: PDFXOptions\n): Promise<Blob>;\nexport function convertToPDFX(\n inputPDFs: Blob[],\n options: PDFXOptions\n): Promise<Blob[]>;\nexport async function convertToPDFX(\n input: Blob | Blob[],\n options: PDFXOptions\n): Promise<Blob | Blob[]> {\n const maxInputSize =\n options.maxInputSize === undefined\n ? 100 * 1024 * 1024\n : options.maxInputSize;\n if (!Number.isSafeInteger(maxInputSize) || maxInputSize <= 0) {\n throw new Error('maxInputSize must be a positive safe integer in bytes');\n }\n\n // Apply the X-4 default at the entry point so internal helpers see a\n // concrete outputStandard. Explicit caller values win over the default.\n const resolvedOptions: ResolvedPDFXOptions = {\n outputStandard: 'PDF/X-4',\n ...options,\n maxInputSize,\n };\n\n // Handle array input (batch processing)\n if (Array.isArray(input)) {\n if (input.length === 0) {\n return [];\n }\n\n // Process each blob sequentially to avoid overwhelming the WASM module\n const results: Blob[] = [];\n for (let i = 0; i < input.length; i++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n const converted = await convertToPDFXSingle(input[i], resolvedOptions);\n results.push(converted);\n } catch (error) {\n const batchError = new Error(\n `Failed to convert PDF ${i + 1} of ${input.length}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error }\n );\n if (error instanceof Error && 'code' in error) {\n Object.assign(batchError, {\n code: error.code,\n ...('diagnostics' in error && {\n diagnostics: error.diagnostics,\n }),\n ...('exitCode' in error && { exitCode: error.exitCode }),\n });\n }\n throw batchError;\n }\n }\n return results;\n }\n\n // Handle single blob input\n return convertToPDFXSingle(input, resolvedOptions);\n}\n\n/**\n * Resolves a preset to the ICC profile bundled next to this module.\n *\n * Every URL is a literal, because a bundler copies a profile into the build\n * only when it can read the path. Built from a variable it copies none, and\n * the export fails on whatever the host returns instead.\n */\nfunction bundledProfileURL(file: string): string {\n switch (file) {\n case 'GRACoL2013_CRPC6.icc':\n return new URL('./GRACoL2013_CRPC6.icc', import.meta.url).href;\n case 'GRACoL2006_Coated1v2.icc':\n return new URL('./GRACoL2006_Coated1v2.icc', import.meta.url).href;\n case 'sRGB_IEC61966-2-1.icc':\n return new URL('./sRGB_IEC61966-2-1.icc', import.meta.url).href;\n default:\n return new URL('./ISOcoated_v2_eci.icc', import.meta.url).href;\n }\n}\n\n/**\n * @deprecated Use `convertToPDFX` instead. This alias is preserved for\n * backwards compatibility and will be removed in a future major release.\n *\n * Defaults to `outputStandard: 'PDF/X-3'` to match the historical behavior\n * of this function — unlike `convertToPDFX`, which defaults to PDF/X-4.\n * Callers can still pass `outputStandard: 'PDF/X-4'` explicitly to opt in.\n */\nexport function convertToPDFX3(\n inputPDF: Blob,\n options: PDFX3Options\n): Promise<Blob>;\nexport function convertToPDFX3(\n inputPDFs: Blob[],\n options: PDFX3Options\n): Promise<Blob[]>;\nexport function convertToPDFX3(\n input: Blob | Blob[],\n options: PDFX3Options\n): Promise<Blob | Blob[]> {\n // Preserve historical X-3 default for the deprecated alias. Explicit\n // caller values still win, so { outputStandard: 'PDF/X-4' } also works.\n const x3Defaulted: PDFX3Options = { outputStandard: 'PDF/X-3', ...options };\n // Delegate without narrowing — runtime branch on Array.isArray inside\n // convertToPDFX already matches the overload semantics.\n return convertToPDFX(input as Blob, x3Defaulted);\n}\n\n/**\n * Internal function to convert a single PDF\n */\nasync function convertToPDFXSingle(\n inputPDF: Blob,\n options: ResolvedPDFXOptions\n): Promise<Blob> {\n // Validate inputs\n if (!(inputPDF instanceof Blob)) {\n throw new Error('Input must be a Blob');\n }\n\n if (inputPDF.size === 0) {\n throw new Error('Input PDF is empty');\n }\n\n if (inputPDF.size > options.maxInputSize) {\n throw new Error(\n `Input PDF too large (${inputPDF.size} bytes). Maximum: ${options.maxInputSize} bytes`\n );\n }\n\n // Validate output profile is provided\n if (!options.outputProfile) {\n throw new Error(\n 'outputProfile is required. Must be one of: \"gracol\", \"fogra39\", \"srgb\", \"custom\"'\n );\n }\n\n // Validate output profile value\n const validProfiles = ['gracol', 'fogra39', 'srgb', 'custom'];\n if (!validProfiles.includes(options.outputProfile)) {\n throw new Error(\n `Invalid outputProfile \"${\n options.outputProfile\n }\". Must be one of: ${validProfiles.join(', ')}`\n );\n }\n\n // Validate custom profile requirement\n if (options.outputProfile === 'custom' && !options.customProfile) {\n throw new Error(\n 'customProfile Blob is required when outputProfile is \"custom\"'\n );\n }\n\n // Validate custom profile if provided\n if (options.customProfile && !(options.customProfile instanceof Blob)) {\n throw new Error('customProfile must be a Blob');\n }\n\n // Validate PDF format\n const isValidPDF = await BlobUtils.validatePDF(inputPDF);\n if (!isValidPDF) {\n throw new Error('Invalid PDF format');\n }\n\n const runtime = options.runtime ?? getDefaultConversionRuntime();\n const operationOptions = {\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n };\n const { version } = await runtime.preload(operationOptions);\n const logger = new Logger('PDFXConversion');\n logger.info('Converting PDF in Ghostscript worker');\n const files: Record<string, Uint8Array | string> = {};\n // Setup file paths\n const inputPath = '/work/input.pdf';\n const outputPath = '/work/output.pdf';\n const pdfxDefPath = '/work/pdfx_def.ps';\n const postDocinfoPath = '/work/pdfx_post.ps';\n const customProfilePath = '/work/custom.icc';\n\n // Write input PDF to virtual filesystem\n files['input.pdf'] = await BlobUtils.toUint8Array(inputPDF);\n\n // Write ICC profiles to virtual filesystem\n if (options.outputProfile === 'custom' && options.customProfile) {\n files['custom.icc'] = await BlobUtils.toUint8Array(options.customProfile);\n } else if (options.outputProfile !== 'custom') {\n // Load the bundled ICC profile\n const profileInfo = resolvePreset(options);\n\n // Load ICC profile - different approach for Node.js vs browser\n const isNode =\n typeof process !== 'undefined' && process.versions?.node != null;\n\n let profileBlob: Blob;\n\n if (isNode) {\n // Node.js: Load from filesystem using readFileSync\n // Use indirect dynamic import to prevent Webpack 5 from statically analyzing these imports\n // But use direct imports in test environments (vitest) where indirect imports bypass mocking\n // See: https://github.com/imgly/ubq/issues/11471\n const isTestEnv =\n process.env.VITEST === 'true' || process.env.NODE_ENV === 'test';\n\n // Note: new Function() could fail in CSP-restricted environments, but CSP is a browser\n // security mechanism and doesn't apply to Node.js. This code only runs in Node.js (isNode check above).\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const indirectImport = new Function('s', 'return import(s)') as (\n s: string\n ) => Promise<any>;\n const dynamicImport = isTestEnv\n ? (s: string) => import(s)\n : indirectImport;\n\n const { readFileSync } = await dynamicImport('fs');\n const { fileURLToPath } = await dynamicImport('url');\n const { dirname, join } = await dynamicImport('path');\n\n // Get the directory of the built module\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const profileFilePath = join(moduleDir, profileInfo.file);\n\n const profileData = readFileSync(profileFilePath);\n profileBlob = new Blob([profileData], {\n type: 'application/vnd.iccprofile',\n });\n } else {\n // Browser: Use fetch\n const profileUrl = bundledProfileURL(profileInfo.file);\n const profileResponse = await fetch(profileUrl, {\n signal: options.signal,\n });\n if (!profileResponse.ok) {\n throw new Error(\n `Failed to load ICC profile ${profileInfo.file}: ${profileResponse.statusText}`\n );\n }\n profileBlob = await profileResponse.blob();\n }\n\n files[profileInfo.file] = await BlobUtils.toUint8Array(profileBlob);\n }\n\n // Determine ICC profile path and metadata for Ghostscript\n let iccProfilePath: string;\n let outputConditionIdentifier: string;\n let outputCondition: string;\n\n if (options.outputProfile === 'custom') {\n iccProfilePath = customProfilePath;\n // Use custom values or defaults\n outputConditionIdentifier =\n options.outputConditionIdentifier || 'Custom Profile';\n outputCondition = options.outputCondition || 'Custom ICC Profile';\n } else {\n const preset = resolvePreset(options);\n iccProfilePath = `/work/${preset.file}`;\n // Allow overriding preset values\n outputConditionIdentifier =\n options.outputConditionIdentifier || preset.identifier;\n outputCondition = options.outputCondition || preset.info;\n }\n\n // Read ICC profile data to inspect its color space\n const iccData = files[iccProfilePath.slice('/work/'.length)] as Uint8Array;\n\n // Determine color conversion strategy based on profile type\n // ICC profile color space is at bytes 16-19\n // 'RGB ' = 0x52474220, 'CMYK' = 0x434D594B\n const colorSpaceBytes = iccData.slice(16, 20);\n const colorSpaceStr = String.fromCharCode(...colorSpaceBytes);\n const isCMYKProfile = colorSpaceStr.trim() === 'CMYK';\n\n // Embed ICC profile + PDF/X-3 OutputIntent by default. Callers can opt\n // out (e.g. when a downstream prepress pipeline handles ICC embedding).\n const embedICCProfile = options.embedICCProfile !== false;\n\n // Only hex-encode the profile for pdfmark embedding when we'll actually\n // embed it. WASM doesn't support (file) (r) file syntax, so pdfmark needs\n // the raw hex stream inline.\n const iccHex = embedICCProfile\n ? Array.from(iccData)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n : '';\n\n // One instant for both metadata stores (DocInfo and XMP dates).\n const timestamps = formatPDFXTimestamps(new Date());\n\n // pdfwrite stamps its own Producer into DocInfo (not overridable in GPL\n // builds); the XMP packet must mirror it exactly.\n if (typeof version !== 'string' || version.length === 0) {\n throw new Error(\n 'Ghostscript module reported no version; cannot mirror the Producer into XMP'\n );\n }\n\n const pdfxDefinition = generatePDFXDef(options, {\n iccProfileHex: iccHex,\n outputConditionIdentifier,\n outputCondition,\n embedICCProfile,\n timestamps,\n docId: generateDocumentId(),\n producer: `GPL Ghostscript ${version}`,\n });\n files['pdfx_def.ps'] = pdfxDefinition;\n files['pdfx_post.ps'] = generatePostDocinfo(\n options,\n timestamps,\n embedICCProfile\n );\n\n // Note on ICC profile selection when embedICCProfile is false:\n // pdfwrite's color conversion uses Ghostscript's bundled default CMYK\n // profile (regardless of the selected outputProfile) since\n // `-sOutputICCProfile` only controls OutputIntent embedding on the\n // pdfwrite device, not the conversion math. That's acceptable here\n // because downstream prepress pipelines (ZePrA, PitStop) are expected\n // to re-normalize colors using their own profile anyway; the plugin's\n // job in this mode is only to deliver a device CMYK PDF without an\n // embedded OutputIntent.\n const gsArgs = buildGhostscriptArgs(options, {\n isCMYKProfile,\n outputPath,\n pdfxDefPath,\n inputPath,\n postDocinfoPath,\n });\n\n const result = await runtime.run(\n { files, args: gsArgs, outputFiles: ['output.pdf'] },\n {\n ...operationOptions,\n // PDF/X-4 disables stream compression, so a valid output can grow far\n // beyond its input. Keep the plugin's historical unrestricted output\n // behavior unless the caller requests a limit.\n maxOutputBytes: options.maxOutputBytes ?? Number.MAX_SAFE_INTEGER,\n }\n );\n return new Blob([new Uint8Array(result.files['output.pdf'])], {\n type: 'application/pdf',\n });\n}\n\n/**\n * Generate an RFC 4122 v4 UUID for the XMP `xmpMM:DocumentID` field. Uses\n * the Web Crypto API where available (modern browsers, Node 19+); falls\n * back to a Math.random shim for older Node runtimes. The DocumentID is\n * an identifier, not a security boundary, so the fallback is acceptable.\n */\nfunction generateDocumentId(): string {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.floor(Math.random() * 16);\n // Standard RFC 4122 v4 y-nibble construction: clamp to 10/11 (binary) via\n // bit-clear of 0x3 then set 0x8. Bitwise math is unavoidable here.\n // eslint-disable-next-line no-bitwise\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// Profile presets from the spec\nconst PROFILE_PRESETS = {\n gracol: {\n file: 'GRACoL2013_CRPC6.icc',\n identifier: 'CGATS 21.2',\n info: 'GRACoL 2013 CRPC6',\n },\n fogra39: {\n file: 'ISOcoated_v2_eci.icc',\n identifier: 'FOGRA39',\n info: 'ISO Coated v2 (ECI)',\n },\n srgb: {\n file: 'sRGB_IEC61966-2-1.icc',\n identifier: 'sRGB IEC61966-2.1',\n info: 'sRGB IEC61966-2.1',\n },\n};\n\n// PDF/X-3 readers commonly accept only ICC v2 profiles, and GRACoL 2013 is v4,\n// so 'gracol' with PDF/X-3 uses the v2 GRACoL 2006 profile.\nconst GRACOL_2006_PRESET = {\n file: 'GRACoL2006_Coated1v2.icc',\n identifier: 'CGATS TR 006',\n info: 'GRACoL 2006 Coated #1',\n};\n\nfunction resolvePreset(options: ResolvedPDFXOptions) {\n if (\n options.outputProfile === 'gracol' &&\n options.outputStandard === 'PDF/X-3'\n ) {\n return GRACOL_2006_PRESET;\n }\n return PROFILE_PRESETS[options.outputProfile as keyof typeof PROFILE_PRESETS];\n}\n"],"mappings":"A,0EAAA,IAAaA,EAAb,KAAuB,CACrB,aAAa,aAAa,EAAiC,CACzD,GAAIC,EAAK,YAAa,CACpB,IAAMC,EAAS,MAAMD,EAAK,YAAY,EACtC,OAAO,IAAI,WAAWC,CAAM,CAC9B,CAGA,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,IAAMC,EAAS,IAAI,WACnB,EAAO,WAAe,CAChBA,EAAO,kBAAkB,YAC3BC,EAAQ,IAAI,WAAWD,EAAO,MAAM,CAAC,EAErCE,EAAO,gBAAI,MAAM,oCAAoC,CAAC,CAE1D,EACA,EAAO,YAAgBA,EAAOF,EAAO,KAAK,EAC1CA,EAAO,kBAAkBF,CAAI,CAC/B,CAAC,CACH,CAEA,aAAa,YAAY,EAA8B,CACrD,GAAI,CACF,IAAMK,EAAO,MAAM,KAAK,aAAaL,CAAI,EAGnCM,EAAY,IAAI,WAAW,CAAC,GAAM,GAAM,GAAM,EAAI,CAAC,EAEzD,GAAID,EAAK,OAAS,EAChB,MAAO,GAGT,IAAK,IAAIE,EAAI,EAAGA,EAAI,EAAG,IACrB,GAAIF,EAAKE,KAAOD,EAAUC,GACxB,MAAO,GAIX,MAAO,EACT,MAAQ,CACN,MAAO,EACT,CACF,CACF,E,orBCjCA,IAAaS,EAAb,MAAaA,CAAO,CAOlB,YAAY,EAA2B,CAAnB,KAAA,UAAAC,CAAoB,CAExC,OAAO,YAAY,EAAuB,CACxC,EAAO,eAAiB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S9C,EAAqBpC,EAAS,CAC3C,gBACA,8BACA,gCACA,4BACA,oCACF,CAAC,EAEKmF,EAAS,MAAM9B,EAAQ,IAC3B,CAAE,QAAO,KAAM6B,EAAQ,YAAa,CAAC,YAAY,CAAE,EACnD,CACE,GAAG3B,EAIH,eAAgBvD,EAAQ,uBAC1B,CACF,EACA,OAAO,IAAI,KAAK,CAAC,IAAI,WAAWmF,EAAO,MAAM,aAAa,CAAC,EAAG,CAC5D,KAAM,iBACR,CAAC,CACH,CAQA,SAASF,GAA6B,CAIpC,OAHI,OAAO,WAAW,QAAQ,YAAe,WACpC,WAAW,OAAO,WAAW,EAE/B,uCAAuC,QAAQ,QAAU,GAAM,CACpE,IAAM9F,EAAI,KAAK,MAAM,KAAK,OAAO,EAAI,EAAE,EAKvC,OADUiG,IAAM,IAAMjG,EAAKA,EAAI,EAAO,EAAA,CAC7B,SAAS,EAAE,CACtB,CAAC,CACH,CAGA,MAAMkG,EAAkB,CACtB,OAAQ,CACN,KAAM,uBACN,WAAY,aACZ,KAAM,mBACR,EACA,QAAS,CACP,KAAM,uBACN,WAAY,UACZ,KAAM,qBACR,EACA,KAAM,CACJ,KAAM,wBACN,WAAY,oBACZ,KAAM,mBACR,CACF,EAIMC,EAAqB,CACzB,KAAM,2BACN,WAAY,eACZ,KAAM,uBACR,EAEA,SAAS5B,EAAc,EAA8B,CAOnD,OALE1D,EAAQ,gBAAkB,UAC1BA,EAAQ,iBAAmB,UAEpBsF,EAEFD,EAAgBrF,EAAQ,cACjC,C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imgly/plugin-print-ready-pdfs-web",
|
|
3
|
-
"version": "1.87.0-
|
|
3
|
+
"version": "1.87.0-rc.0",
|
|
4
4
|
"description": "Print-Ready PDFs plugin for CE.SDK editor - PDF/X conversion and export functionality. Contains AGPL-3.0 licensed Ghostscript WASM.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"CE.SDK",
|
|
@@ -38,11 +38,11 @@
|
|
|
38
38
|
"@imgly/pdf-conversion-utils": "^0.1.0"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
|
-
"@cesdk/cesdk-js": "^1.87.0-
|
|
41
|
+
"@cesdk/cesdk-js": "^1.87.0-rc.0"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@cesdk/cesdk-js": "1.87.0-
|
|
45
|
-
"@cesdk/engine": "1.87.0-
|
|
44
|
+
"@cesdk/cesdk-js": "1.87.0-rc.0",
|
|
45
|
+
"@cesdk/engine": "1.87.0-rc.0",
|
|
46
46
|
"@cesdk/node": "~1.61.0",
|
|
47
47
|
"@imgly/plugin-tsdown-config": "0.0.0",
|
|
48
48
|
"@imgly/plugin-utils": "0.0.0",
|