PageSourceSearch

https://ticmi.co.id/build/assets/worker-engine-BZRBQvei-CN2ZimOt.js

js ticmi.co.id collected 2026-10-07 19:55:25 UTC 698,806 bytes, 19,595 lines download raw bytes

vendor: 11,587 bytes, lines 1-111
1import{h as _,x as b}from"./browser-BKLM0ThC-IAuFUahz-CkMv4xHN.js";import{c as P,f as g,I as f,_ as D}from"./index-CmpjqHmb.js";import"./app-Ck2zP5RY.js";/* empty css            */const a="RemoteExecutor",i="Worker",F=class c{constructor(n,e){this.worker=n,this.pendingRequests=new Map,this.requestCounter=0,this.handleMessage=t=>{const r=t.data;if(r.type==="ready")return this.logger.debug(a,i,"Worker is ready"),void this.readyTask.resolve(!0);const o=this.pendingRequests.get(r.id);if(o)switch(r.type){case"result":this.logger.debug(a,i,`Received result for ${r.id}`),o.resolve(r.data),this.pendingRequests.delete(r.id);break;case"error":this.logger.debug(a,i,`Received error for ${r.id}:`,r.error),r.error?o.fail(r.error):o.reject({code:P.Unknown,message:"Unknown error"}),this.pendingRequests.delete(r.id);break;case"progress":this.logger.debug(a,i,`Received progress for ${r.id}`),o.progress(r.progress)}else this.logger.warn(a,i,`Received response for unknown request: ${r.id}`)},this.logger=e.logger??new g,this.worker.addEventListener("message",this.handleMessage),this.readyTask=new f,this.pendingRequests.set(c.READY_TASK_ID,this.readyTask),this.worker.postMessage({id:c.READY_TASK_ID,type:"wasmInit",wasmUrl:e.wasmUrl,logger:e.logger?D(e.logger):void 0,fontFallback:e.fontFallback}),this.logger.debug(a,i,"RemoteExecutor created")}generateId(){return`req-${Date.now()}-${this.requestCounter++}`}send(n,e){const t=this.generateId(),r=new f,o={id:t,type:"execute",method:n,args:e};return this.readyTask.wait(()=>{this.pendingRequests.set(t,r),this.logger.debug(a,i,`Sending ${n} request:`,t),this.worker.postMessage(o)},l=>{this.logger.error(a,i,`Worker init failed, rejecting ${n}:`,l),r.reject({code:P.Initialization,message:"Worker initialization failed"})}),r}destroy(){this.worker.removeEventListener("message",this.handleMessage),this.pendingRequests.forEach((n,e)=>{e!==c.READY_TASK_ID&&(n.abort("Worker destroyed"),this.logger.debug(a,i,`Aborted pending request: ${e}`))}),this.pendingRequests.clear(),this.worker.terminate(),this.logger.debug(a,i,"RemoteExecutor destroyed")}openDocumentBuffer(n,e){return this.send("openDocumentBuffer",[n,e])}getMetadata(n){return this.send("getMetadata",[n])}setMetadata(n,e){return this.send("setMetadata",[n,e])}getDocPermissions(n){return this.send("getDocPermissions",[n])}getDocUserPermissions(n){return this.send("getDocUserPermissions",[n])}getSignatures(n){return this.send("getSignatures",[n])}getBookmarks(n){return this.send("getBookmarks",[n])}setBookmarks(n,e){return this.send("setBookmarks",[n,e])}deleteBookmarks(n){return this.send("deleteBookmarks",[n])}renderPageRaw(n,e,t){return this.send("renderPageRaw",[n,e,t])}renderPageRect(n,e,t,r){return this.send("renderPageRect",[n,e,t,r])}renderThumbnailRaw(n,e,t){return this.send("renderThumbnailRaw",[n,e,t])}renderPageAnnotationRaw(n,e,t,r){return this.send("renderPageAnnotationRaw",[n,e,t,r])}renderPageAnnotationsRaw(n,e,t){return this.send("renderPageAnnotationsRaw",[n,e,t])}getPageAnnotationsRaw(n,e){return this.send("getPageAnnotationsRaw",[n,e])}getPageAnnotations(n,e){return this.send("getPageAnnotations",[n,e])}createPageAnnotation(n,e,t,r){return this.send("createPageAnnotation",[n,e,t,r])}updatePageAnnotation(n,e,t,r){return this.send("updatePageAnnotation",[n,e,t,r])}removePageAnnotation(n,e,t){return this.send("removePageAnnotation",[n,e,t])}getPageTextRects(n,e){return this.send("getPageTextRects",[n,e])}searchInPage(n,e,t,r){return this.send("searchInPage",[n,e,t,r])}getAnnotationsBatch(n,e){return this.send("getAnnotationsBatch",[n,e])}searchBatch(n,e,t,r){return this.send("searchBatch",[n,e,t,r])}getAttachments(n){return this.send("getAttachments",[n])}addAttachment(n,e){return this.send("addAttachment",[n,e])}removeAttachment(n,e){return this.send("removeAttachment",[n,e])}readAttachmentContent(n,e){return this.send("readAttachmentContent",[n,e])}getDocumentJavaScriptActions(n){return this.send("getDocumentJavaScriptActions",[n])}getPageAnnoWidgets(n,e){return this.send("getPageAnnoWidgets",[n,e])}getPageWidgetJavaScriptActions(n,e){return this.send("getPageWidgetJavaScriptActions",[n,e])}setFormFieldValue(n,e,t,r){return this.send("setFormFieldValue",[n,e,t,r])}setFormFieldState(n,e,t,r){return this.send("setFormFieldState",[n,e,t,r])}renameWidgetField(n,e,t,r){return this.send("renameWidgetField",[n,e,t,r])}shareWidgetField(n,e,t,r,o){return this.send("shareWidgetField",[n,e,t,r,o])}regenerateWidgetAppearances(n,e,t){return this.send("regenerateWidgetAppearances",[n,e,t])}flattenPage(n,e,t){return this.send("flattenPage",[n,e,t])}extractPages(n,e){return this.send("extractPages",[n,e])}createDocument(n){return this.send("createDocument",[n])}importPages(n,e,t,r){return this.send("importPages",[n,e,t,r])}deletePage(n,e){return this.send("deletePage",[n,e])}extractText(n,e){return this.send("extractText",[n,e])}redactTextInRects(n,e,t,r){return this.send("redactTextInRects",[n,e,t,r])}applyRedaction(n,e,t){return this.send("applyRedaction",[n,e,t])}applyAllRedactions(n,e){return this.send("applyAllRedactions",[n,e])}flattenAnnotation(n,e,t){return this.send("flattenAnnotation",[n,e,t])}exportAnnotationAppearanceAsPdf(n,e,t){return this.send("exportAnnotationAppearanceAsPdf",[n,e,t])}exportAnnotationsAppearanceAsPdf(n,e,t){return this.send("exportAnnotationsAppearanceAsPdf",[n,e,t])}getTextSlices(n,e){return this.send("getTextSlices",[n,e])}getPageGlyphs(n,e){return this.send("getPageGlyphs",[n,e])}getPageGeometry(n,e){return this.send("getPageGeometry",[n,e])}getPageTextRuns(n,e){return this.send("getPageTextRuns",[n,e])}merge(n){return this.send("merge",[n])}mergePages(n){return this.send("mergePages",[n])}preparePrintDocument(n,e){return this.send("preparePrintDocument",[n,e])}saveAsCopy(n){return this.send("saveAsCopy",[n])}closeDocument(n){return this.send("closeDocument",[n])}closeAllDocuments(){return this.send("closeAllDocuments",[])}setDocumentEncryption(n,e,t,r){return this.send("setDocumentEncryption",[n,e,t,r])}removeEncryption(n){return this.send("removeEncryption",[n])}unlockOwnerPermissions(n,e){return this.send("unlockOwnerPermissions",[n,e])}isEncrypted(n){return this.send("isEncrypted",[n])}isOwnerUnlocked(n){return this.send("isOwnerUnlocked",[n])}};F.READY_TASK_ID="0";let E=F;const s="ImageEncoderPool",d="Encoder";class A{constructor(n=2,e,t){this.poolSize=n,this.workerUrl=e,this.workers=[],this.pendingTasks=new Map,this.nextWorkerId=0,this.requestCounter=0,this.logger=t??new g,this.initialize()}initialize(){this.logger.debug(s,d,`Creating worker pool with ${this.poolSize} workers`);for(let n=0;n<this.poolSize;n++)try{const e=new Worker(this.workerUrl,{type:"module"});e.onmessage=this.handleWorkerMessage.bind(this),e.onerror=this.handleWorkerError.bind(this),this.workers.push(e),this.logger.debug(s,d,`Worker ${n} created successfully`)}catch(e){this.logger.error(s,d,`Failed to create worker ${n}:`,e)}}handleWorkerMessage(n){const e=n.data,t=this.pendingTasks.get(e.id);if(t)if(this.pendingTasks.delete(e.id),e.type==="result")t.resolve(e.data);else{const r=e.data;t.reject(new Error(r.message))}else this.logger.warn(s,d,`Received response for unknown task: ${e.id}`)}handleWorkerError(n){this.logger.error(s,d,"Worker error:",n.message)}getNextWorker(){if(this.workers.length===0)return null;const n=this.workers[this.nextWorkerId];return this.nextWorkerId=(this.nextWorkerId+1)%this.workers.length,n}encode(n,e="image/png",t){return new Promise((r,o)=>{const l=this.getNextWorker();if(!l)return void o(new Error("No workers available in the pool"));const u=`encode-${Date.now()}-${this.requestCounter++}`;this.pendingTasks.set(u,{resolve:r,reject:o});const p={id:u,type:"encode",data:{imageData:{data:n.data,width:n.width,height:n.height},imageType:e,quality:t}};this.logger.debug(s,d,`Sending encoding request ${u} (${n.width}x${n.height})`),l.postMessage(p,[n.data.buffer])})}destroy(){this.logger.debug(s,d,"Destroying worker pool"),this.pendingTasks.forEach((n,e)=>{n.reject(new Error("Worker pool destroyed")),this.logger.debug(s,d,`Rejected pending task: ${e}`)}),this.pendingTasks.clear(),this.workers.forEach((n,e)=>{n.terminate(),this.logger.debug(s,d,`Worker ${e} terminated`)}),this.workers=[]}get activeWorkers(){return this.workers.length}get pendingTasksCount(){return this.pendingTasks.size}}function O(m,n){const e=n instanceof Object&&"debug"in n?{logger:n}:n||{},{logger:t,encoderPoolSize:r,fontFallback:o}=e,l=new Worker(URL.createObjectURL(new Blob([`var Rotation = /* @__PURE__ */ ((Rotation2) => {
2  Rotation2[Rotation2["Degree0"] = 0] = "Degree0";
3  Rotation2[Rotation2["Degree90"] = 1] = "Degree90";
4  Rotation2[Rotation2["Degree180"] = 2] = "Degree180";
5  Rotation2[Rotation2["Degree270"] = 3] = "Degree270";
6  return Rotation2;
7})(Rotation || {});
8function toIntPos(p) {
9  return { x: Math.floor(p.x), y: Math.floor(p.y) };
10}
11function toIntSize(s) {
12  return { width: Math.ceil(s.width), height: Math.ceil(s.height) };
13}
14function toIntRect(r) {
15  return {
16    origin: toIntPos(r.origin),
17    size: toIntSize(r.size)
18  };
19}
20function swap(size) {
21  const { width, height } = size;
22  return {
23    width: height,
24    height: width
25  };
26}
27function quadToRect(q) {
28  const xs = [q.p1.x, q.p2.x, q.p3.x, q.p4.x];
29  const ys = [q.p1.y, q.p2.y, q.p3.y, q.p4.y];
30  return {
31    origin: { x: Math.min(...xs), y: Math.min(...ys) },
32    size: {
33      width: Math.max(...xs) - Math.min(...xs),
34      height: Math.max(...ys) - Math.min(...ys)
35    }
36  };
37}
38function rectToQuad(r) {
39  return {
40    p1: { x: r.origin.x, y: r.origin.y },
41    p2: { x: r.origin.x + r.size.width, y: r.origin.y },
42    p3: { x: r.origin.x + r.size.width, y: r.origin.y + r.size.height },
43    p4: { x: r.origin.x, y: r.origin.y + r.size.height }
44  };
45}
46function rotateRect(containerSize, rect, rotation) {
47  let x = rect.origin.x;
48  let y = rect.origin.y;
49  let size = rect.size;
50  switch (rotation) {
51    case 0:
52      break;
53    case 1:
54      x = containerSize.height - rect.origin.y - rect.size.height;
55      y = rect.origin.x;
56      size = swap(rect.size);
57      break;
58    case 2:
59      x = containerSize.width - rect.origin.x - rect.size.width;
60      y = containerSize.height - rect.origin.y - rect.size.height;
61      break;
62    case 3:
63      x = rect.origin.y;
64      y = containerSize.width - rect.origin.x - rect.size.width;
65      size = swap(rect.size);
66      break;
67  }
68  return {
69    origin: {
70      x,
71      y
72    },
73    size: {
74      width: size.width,
75      height: size.height
76    }
77  };
78}
79function scaleRect(rect, scaleFactor) {
80  return {
81    origin: {
82      x: rect.origin.x * scaleFactor,
83      y: rect.origin.y * scaleFactor
84    },
85    size: {
86      width: rect.size.width * scaleFactor,
87      height: rect.size.height * scaleFactor
88    }
89  };
90}
91function transformRect(containerSize, rect, rotation, scaleFactor) {
92  return scaleRect(rotateRect(containerSize, rect, rotation), scaleFactor);
93}
94function buildUserToDeviceMatrix(rect, rotation, outW, outH) {
95  const L = rect.origin.x;
96  const B = rect.origin.y;
97  const W = rect.size.width;
98  const H = rect.size.height;
99  const sx0 = outW / W;
100  const sy0 = outH / H;
101  const sx90 = outW / H;
102  const sy90 = outH / W;
103  switch (rotation) {
104    case 0:
105      return { a: sx0, b: 0, c: 0, d: sy0, e: -sx0 * L, f: -sy0 * B };
106    case 3:
107      return { a: 0, b: -sy90, c: sx90, d: 0, e: -sx90 * B, f: sy90 * (L + W) };
108    case 2:
109      return { a: -sx0, b: 0, c: 0, d: -sy0, e: sx0 * (L + W), f: sy0 * (B + H) };
110    case 1:
111      return { a: 0, b: sy90, c: -sx90, d: 0, e: sx90 * (B + H), f: 
111-sy90 * L };
112  }
113}
114class NoopLogger {
115  /** {@inheritDoc Logger.isEnabled} */
116  isEnabled() {
117    return false;
118  }
119  /** {@inheritDoc Logger.debug} */
120  debug() {
121  }
122  /** {@inheritDoc Logger.info} */
123  info() {
124  }
125  /** {@inheritDoc Logger.warn} */
126  warn() {
127  }
128  /** {@inheritDoc Logger.error} */
129  error() {
130  }
131  /** {@inheritDoc Logger.perf} */
132  perf() {
133  }
134}
135class ConsoleLogger {
136  /** {@inheritDoc Logger.isEnabled} */
137  isEnabled() {
138    return true;
139  }
140  /** {@inheritDoc Logger.debug} */
141  debug(source, category, ...args) {
142    console.debug(\`\${source}.\${category}\`, ...args);
143  }
144  /** {@inheritDoc Logger.info} */
145  info(source, category, ...args) {
146    console.info(\`\${source}.\${category}\`, ...args);
147  }
148  /** {@inheritDoc Logger.warn} */
149  warn(source, category, ...args) {
150    console.warn(\`\${source}.\${category}\`, ...args);
151  }
152  /** {@inheritDoc Logger.error} */
153  error(source, category, ...args) {
154    console.error(\`\${source}.\${category}\`, ...args);
155  }
156  /** {@inheritDoc Logger.perf} */
157  perf(source, category, event, phase, ...args) {
158    console.info(\`\${source}.\${category}.\${event}.\${phase}\`, ...args);
159  }
160}
161class LevelLogger {
162  /**
163   * create new LevelLogger
164   * @param logger - the original logger
165   * @param level - log level that used for filtering, all logs lower than this level will be filtered out
166   */
167  constructor(logger, level) {
168    this.logger = logger;
169    this.level = level;
170  }
171  /** {@inheritDoc Logger.isEnabled} */
172  isEnabled(level) {
173    const levelMap = {
174      debug: 0,
175      info: 1,
176      warn: 2,
177      error: 3
178      /* Error */
179    };
180    return this.level <= levelMap[level];
181  }
182  /** {@inheritDoc Logger.debug} */
183  debug(source, category, ...args) {
184    if (this.level <= 0) {
185      this.logger.debug(source, category, ...args);
186    }
187  }
188  /** {@inheritDoc Logger.info} */
189  info(source, category, ...args) {
190    if (this.level <= 1) {
191      this.logger.info(source, category, ...args);
192    }
193  }
194  /** {@inheritDoc Logger.warn} */
195  warn(source, category, ...args) {
196    if (this.level <= 2) {
197      this.logger.warn(source, category, ...args);
198    }
199  }
200  /** {@inheritDoc Logger.error} */
201  error(source, category, ...args) {
202    if (this.level <= 3) {
203      this.logger.error(source, category, ...args);
204    }
205  }
206  /** {@inheritDoc Logger.perf} */
207  perf(source, category, event, phase, ...args) {
208    this.logger.perf(source, category, event, phase, ...args);
209  }
210}
211class PerfLogger {
212  /**
213   * create new PerfLogger
214   */
215  constructor() {
216    this.marks = /* @__PURE__ */ new Map();
217  }
218  /** {@inheritDoc Logger.isEnabled} */
219  isEnabled() {
220    return false;
221  }
222  /** {@inheritDoc Logger.debug} */
223  debug(source, category, ...args) {
224  }
225  /** {@inheritDoc Logger.info} */
226  info(source, category, ...args) {
227  }
228  /** {@inheritDoc Logger.warn} */
229  warn(source, category, ...args) {
230  }
231  /** {@inheritDoc Logger.error} */
232  error(source, category, ...args) {
233  }
234  /** {@inheritDoc Logger.perf} */
235  perf(source, category, event, phase, identifier, ...args) {
236    const markName = \`\${source}.\${category}.\${event}.\${phase}.\${identifier}\`;
237    switch (phase) {
238      case "Begin":
239        globalThis.performance.mark(markName, { detail: args });
240        this.marks.set(\`\${source}.\${category}.\${event}.\${identifier}\`, Date.now());
241        break;
242      case "End":
243        globalThis.performance.mark(markName, { detail: args });
244        const measureName = \`\${source}.\${category}.\${event}.Measure.\${identifier}\`;
245        const beginMark = \`\${source}.\${category}.\${event}.Begin.\${identifier}\`;
246        globalThis.performance.measure(measureName, beginMark, markName);
247        const startTime = this.marks.get(\`\${source}.\${category}.\${event}.\${identifier}\`);
248        if (startTime) {
249          const duration = Date.now() - startTime;
250          console.info(\`⏱️ \${source}.\${category}.\${event}.\${identifier}: \${duration}ms\`);
251          this.marks.delete(\`\${source}.\${category}.\${event}.\${identifier}\`);
252        }
253        break;
254    }
255  }
256}
257class AllLogger {
258  /**
259   * create new PerfLogger
260   */
261  constructor(loggers) {
262    this.loggers = loggers;
263  }
264  /** {@inheritDoc Logger.isEnabled} */
265  isEnabled(level) {
266    return this.loggers.some((logger) => logger.isEnabled(level));
267  }
268  /** {@inheritDoc Logger.debug} */
269  debug(source, category, ...args) {
270    for (const logger of this.loggers) {
271      logger.debug(source, category, ...args);
272    }
273  }
274  /** {@inheritDoc Logger.info} */
275  info(source, category, ...args) {
276    for (const logger of this.loggers) {
277      logger.info(source, category, ...args);
278    }
279  }
280  /** {@inheritDoc Logger.warn} */
281  warn(source, category, ...args) {
282    for (const logger of this.loggers) {
283      logger.warn(source, category, ...args);
284    }
285  }
286  /** {@inheritDoc Logger.error} */
287  error(source, category, ...args) {
288    for (const logger of this.loggers) {
289      logger.error(source, category, ...args);
290    }
291  }
292  /** {@inheritDoc Logger.perf} */
293  perf(source, category, event, phase, ...args) {
294    for (const logger of this.loggers) {
295      logger.perf(source, category, event, phase, ...args);
296    }
297  }
298}
299class TaskAbortedError extends Error {
300  constructor(reason) {
301    super(\`Task aborted: \${JSON.stringify(reason)}\`);
302    this.name = "TaskAbortedError";
303    this.reason = reason;
304  }
305}
306class TaskRejectedError extends Error {
307  constructor(reason) {
308    super(\`Task rejected: \${JSON.stringify(reason)}\`);
309    this.name = "TaskRejectedError";
310    this.reason = reason;
311  }
312}
313class Task {
314  constructor() {
315    this.state = {
316      stage: 0
317      /* Pending */
318    };
319    this.resolvedCallbacks = [];
320    this.rejectedCallbacks = [];
321    this._promise = null;
322    this.progressCbs = [];
323  }
324  /**
325   * Convert task to promise
326   * @returns promise that will be resolved when task is settled
327   */
328  toPromise() {
329    if (!this._promise) {
330      this._promise = new Promise((resolve, reject) => {
331        this.wait(
332          (result) => resolve(result),
333          (error) => {
334            if (error.type === "abort") {
335              reject(new TaskAbortedError(error.reason));
336            } else {
337              reject(new TaskRejectedError(error.reason));
338            }
339          }
340        );
341      });
342    }
343    return this._promise;
344  }
345  /**
346   * wait for task to be settled
347   * @param resolvedCallback - callback for resolved value
348   * @param rejectedCallback - callback for rejected value
349   */
350  wait(resolvedCallback, rejectedCallback) {
351    switch (this.state.stage) {
352      case 0:
353        this.resolvedCallbacks.push(resolvedCallback);
354        this.rejectedCallbacks.push(rejectedCallback);
355        break;
356      case 1:
357        resolvedCallback(this.state.result);
358        break;
359      case 2:
360        rejectedCallback({
361          type: "reject",
362          reason: this.state.reason
363        });
364        break;
365      case 3:
366        rejectedCallback({
367          type: "abort",
368          reason: this.state.reason
369        });
370        break;
371    }
372  }
373  /**
374   * resolve task with specific result
375   * @param result - result value
376   */
377  resolve(result) {
378    if (this.state.stage === 0) {
379      this.state = {
380        stage: 1,
381        result
382      };
383      for (const resolvedCallback of this.resolvedCallbacks) {
384        try {
385          resolvedCallback(result);
386        } catch (e) {
387        }
388      }
389      this.resolvedCallbacks = [];
390      this.rejectedCallbacks = [];
391    }
392  }
393  /**
394   * reject task with specific reason
395   * @param reason - abort reason
396   *
397   */
398  reject(reason) {
399    if (this.state.stage === 0) {
400      this.state = {
401        stage: 2,
402        reason
403      };
404      for (const rejectedCallback of this.rejectedCallbacks) {
405        try {
406          rejectedCallback({
407            type: "reject",
408            reason
409          });
410        } catch (e) {
411        }
412      }
413      this.resolvedCallbacks = [];
414      this.rejectedCallbacks = [];
415    }
416  }
417  /**
418   * abort task with specific reason
419   * @param reason - abort reason
420   */
421  abort(reason) {
422    if (this.state.stage === 0) {
423      this.state = {
424        stage: 3,
425        reason
426      };
427      for (const rejectedCallback of this.rejectedCallbacks) {
428        try {
429          rejectedCallback({
430            type: "abort",
431            reason
432          });
433        } catch (e) {
434        }
435      }
436      this.resolvedCallbacks = [];
437      this.rejectedCallbacks = [];
438    }
439  }
440  /**
441   * fail task with a TaskError from another task
442   * This is a convenience method for error propagation between tasks
443   * @param error - TaskError from another task
444   */
445  fail(error) {
446    if (error.type === "abort") {
447      this.abort(error.reason);
448    } else {
449      this.reject(error.reason);
450    }
451  }
452  /**
453   * add a progress callback
454   * @param cb - progress callback
455   */
456  onProgress(cb) {
457    this.progressCbs.push(cb);
458  }
459  /**
460   * call progress callback
461   * @param p - progress value
462   */
463  progress(p) {
464    for (const cb of this.progressCbs) cb(p);
465  }
466  /**
467   * Static method to wait for all tasks to resolve
468   * Returns a new task that resolves with an array of all results
469   * Rejects immediately if any task fails
470   *
471   * @param tasks - array of tasks to wait for
472   * @returns new task that resolves when all input tasks resolve
473   * @public
474   */
475  static all(tasks) {
476    const combinedTask = new Task();
477    if (tasks.length === 0) {
478      combinedTask.resolve([]);
479      return combinedTask;
480    }
481    const results = new Array(tasks.length);
482    let resolvedCount = 0;
483    let isSettled = false;
484    tasks.forEach((task, index) => {
485      task.wait(
486        (result) => {
487          if (isSettled) return;
488          results[index] = result;
489          resolvedCount++;
490          if (resolvedCount === tasks.length) {
491            isSettled = true;
492            combinedTask.resolve(results);
493          }
494        },
495        (error) => {
496          if (isSettled) return;
497          isSettled = true;
498          if (error.type === "abort") {
499            combinedTask.abort(error.reason);
500          } else {
501            combinedTask.reject(error.reason);
502          }
503        }
504      );
505    });
506    return combinedTask;
507  }
508  /**
509   * Static method to wait for all tasks to settle (resolve, reject, or abort)
510   * Always resolves with an array of settlement results
511   *
512   * @param tasks - array of tasks to wait for
513   * @returns new task that resolves when all input tasks settle
514   * @public
515   */
516  static allSettled(tasks) {
517    const combinedTask = new Task();
518    if (tasks.length === 0) {
519      combinedTask.resolve([]);
520      return combinedTask;
521    }
522    const results = new Array(tasks.length);
523    let settledCount = 0;
524    tasks.forEach((task, index) => {
525      task.wait(
526        (result) => {
527          results[index] = { status: "resolved", value: result };
528          settledCount++;
529          if (settledCount === tasks.length) {
530            combinedTask.resolve(results);
531          }
532        },
533        (error) => {
534          results[index] = {
535            status: error.type === "abort" ? "aborted" : "rejected",
536            reason: error.reason
537          };
538          settledCount++;
539          if (settledCount === tasks.length) {
540            combinedTask.resolve(results);
541          }
542        }
543      );
544    });
545    return combinedTask;
546  }
547  /**
548   * Static method that resolves/rejects with the first task that settles
549   *
550   * @param tasks - array of tasks to race
551   * @returns new task that settles with the first input task that settles
552   * @public
553   */
554  static race(tasks) {
555    const combinedTask = new Task();
556    if (tasks.length === 0) {
557      combinedTask.reject("No tasks provided");
558      return combinedTask;
559    }
560    let isSettled = false;
561    tasks.forEach((task) => {
562      task.wait(
563        (result) => {
564          if (isSettled) return;
565          isSettled = true;
566          combinedTask.resolve(result);
567        },
568        (error) => {
569          if (isSettled) return;
570          isSettled = true;
571          if (error.type === "abort") {
572            combinedTask.abort(error.reason);
573          } else {
574            combinedTask.reject(error.reason);
575          }
576        }
577      );
578    });
579    return combinedTask;
580  }
581  /**
582   * Utility to track progress of multiple tasks
583   *
584   * @param tasks - array of tasks to track
585   * @param onProgress - callback called when any task completes
586   * @returns new task that resolves when all input tasks resolve
587   * @public
588   */
589  static withProgress(tasks, onProgress) {
590    const combinedTask = Task.all(tasks);
591    if (onProgress) {
592      let completedCount = 0;
593      tasks.forEach((task) => {
594        task.wait(
595          () => {
596            completedCount++;
597            onProgress(completedCount, tasks.length);
598          },
599          () => {
600            completedCount++;
601            onProgress(completedCount, tasks.length);
602          }
603        );
604      });
605    }
606    return combinedTask;
607  }
608}
609const PdfSoftHyphenMarker = "­";
610const PdfZeroWidthSpace = "​";
611const PdfWordJoiner = "⁠";
612const PdfBomOrZwnbsp = "\\uFEFF";
613const PdfNonCharacterFFFE = "￾";
614const PdfNonCharacterFFFF = "ï¿¿";
615const PdfUnwantedTextMarkers = Object.freeze([
616  PdfSoftHyphenMarker,
617  PdfZeroWidthSpace,
618  PdfWordJoiner,
619  PdfBomOrZwnbsp,
620  PdfNonCharacterFFFE,
621  PdfNonCharacterFFFF
622]);
623const PdfUnwantedTextRegex = new RegExp(\`[\${PdfUnwantedTextMarkers.join("")}]\`, "g");
624function stripPdfUnwantedMarkers(text) {
625  return text.replace(PdfUnwantedTextRegex, "");
626}
627var PdfZoomMode = /* @__PURE__ */ ((PdfZoomMode2) => {
628  PdfZoomMode2[PdfZoomMode2["Unknown"] = 0] = "Unknown";
629  PdfZoomMode2[PdfZoomMode2["XYZ"] = 1] = "XYZ";
630  PdfZoomMode2[PdfZoomMode2["FitPage"] = 2] = "FitPage";
631  PdfZoomMode2[PdfZoomMode2["FitHorizontal"] = 3] = "FitHorizontal";
632  PdfZoomMode2[PdfZoomMode2["FitVertical"] = 4] = "FitVertical";
633  PdfZoomMode2[PdfZoomMode2["FitRectangle"] = 5] = "FitRectangle";
634  PdfZoomMode2[PdfZoomMode2["FitBoundingBox"] = 6] = "FitBoundingBox";
635  PdfZoomMode2[PdfZoomMode2["FitBoundingBoxHorizontal"] = 7] = "FitBoundingBoxHorizontal";
636  PdfZoomMode2[PdfZoomMode2["FitBoundingBoxVertical"] = 8] = "FitBoundingBoxVertical";
637  return PdfZoomMode2;
638})(PdfZoomMode || {});
639var PdfTrappedStatus = /* @__PURE__ */ ((PdfTrappedStatus2) => {
640  PdfTrappedStatus2[PdfTrappedStatus2["NotSet"] = 0] = "NotSet";
641  PdfTrappedStatus2[PdfTrappedStatus2["True"] = 1] = "True";
642  PdfTrappedStatus2[PdfTrappedStatus2["False"] = 2] = "False";
643  PdfTrappedStatus2[PdfTrappedStatus2["Unknown"] = 3] = "Unknown";
644  return PdfTrappedStatus2;
645})(PdfTrappedStatus || {});
646var PdfStandardFont = /* @__PURE__ */ ((PdfStandardFont2) => {
647  PdfStandardFont2[PdfStandardFont2["Unknown"] = -1] = "Unknown";
648  PdfStandardFont2[PdfStandardFont2["Courier"] = 0] = "Courier";
649  PdfStandardFont2[PdfStandardFont2["Courier_Bold"] = 1] = "Courier_Bold";
650  PdfStandardFont2[PdfStandardFont2["Courier_BoldOblique"] = 2] = "Courier_BoldOblique";
651  PdfStandardFont2[PdfStandardFont2["Courier_Oblique"] = 3] = "Courier_Oblique";
652  PdfStandardFont2[PdfStandardFont2["Helvetica"] = 4] = "Helvetica";
653  PdfStandardFont2[PdfStandardFont2["Helvetica_Bold"] = 5] = "Helvetica_Bold";
654  PdfStandardFont2[PdfStandardFont2["Helvetica_BoldOblique"] = 6] = "Helvetica_BoldOblique";
655  PdfStandardFont2[PdfStandardFont2["Helvetica_Oblique"] = 7] = "Helvetica_Oblique";
656  PdfStandardFont2[PdfStandardFont2["Times_Roman"] = 8] = "Times_Roman";
657  PdfStandardFont2[PdfStandardFont2["Times_Bold"] = 9] = "Times_Bold";
658  PdfStandardFont2[PdfStandardFont2["Times_BoldItalic"] = 10] = "Times_BoldItalic";
659  PdfStandardFont2[PdfStandardFont2["Times_Italic"] = 11] = "Times_Italic";
660  PdfStandardFont2[PdfStandardFont2["Symbol"] = 12] = "Symbol";
661  PdfStandardFont2[PdfStandardFont2["ZapfDingbats"] = 13] = "ZapfDingbats";
662  return PdfStandardFont2;
663})(PdfStandardFont || {});
664var PdfTextAlignment = /* @__PURE__ */ ((PdfTextAlignment2) => {
665  PdfTextAlignment2[PdfTextAlignment2["Left"] = 0] = "Left";
666  PdfTextAlignment2[PdfTextAlignment2["Center"] = 1] = "Center";
667  PdfTextAlignment2[PdfTextAlignment2["Right"] = 2] = "Right";
668  return PdfTextAlignment2;
669})(PdfTextAlignment || {});
670var PdfBlendMode = /* @__PURE__ */ ((PdfBlendMode2) => {
671  PdfBlendMode2[PdfBlendMode2["Normal"] = 0] = "Normal";
672  PdfBlendMode2[PdfBlendMode2["Multiply"] = 1] = "Multiply";
673  PdfBlendMode2[PdfBlendMode2["Screen"] = 2] = "Screen";
674  PdfBlendMode2[PdfBlendMode2["Overlay"] = 3] = "Overlay";
675  PdfBlendMode2[PdfBlendMode2["Darken"] = 4] = "Darken";
676  PdfBlendMode2[PdfBlendMode2["Lighten"] = 5] = "Lighten";
677  PdfBlendMode2[PdfBlendMode2["ColorDodge"] = 6] = "ColorDodge";
678  PdfBlendMode2[PdfBlendMode2["ColorBurn"] = 7] = "ColorBurn";
679  PdfBlendMode2[PdfBlendMode2["HardLight"] = 8] = "HardLight";
680  PdfBlendMode2[PdfBlendMode2["SoftLight"] = 9] = "SoftLight";
681  PdfBlendMode2[PdfBlendMode2["Difference"] = 10] = "Difference";
682  PdfBlendMode2[PdfBlendMode2["Exclusion"] = 11] = "Exclusion";
683  PdfBlendMode2[PdfBlendMode2["Hue"] = 12] = "Hue";
684  PdfBlendMode2[PdfBlendMode2["Saturation"] = 13] = "Saturation";
685  PdfBlendMode2[PdfBlendMode2["Color"] = 14] = "Color";
686  PdfBlendMode2[PdfBlendMode2["Luminosity"] = 15] = "Luminosity";
687  return PdfBlendMode2;
688})(PdfBlendMode || {});
689var PdfStampFit = /* @__PURE__ */ ((PdfStampFit2) => {
690  PdfStampFit2[PdfStampFit2["Contain"] = 0] = "Contain";
691  PdfStampFit2[PdfStampFit2["Cover"] = 1] = "Cover";
692  PdfStampFit2[PdfStampFit2["Stretch"] = 2] = "Stretch";
693  return PdfStampFit2;
694})(PdfStampFit || {});
695var PdfActionType = /* @__PURE__ */ ((PdfActionType2) => {
696  PdfActionType2[PdfActionType2["Unsupported"] = 0] = "Unsupported";
697  PdfActionType2[PdfActionType2["Goto"] = 1] = "Goto";
698  PdfActionType2[PdfActionType2["RemoteGoto"] = 2] = "RemoteGoto";
699  PdfActionType2[PdfActionType2["URI"] = 3] = "URI";
700  PdfActionType2[PdfActionType2["LaunchAppOrOpenFile"] = 4] = "LaunchAppOrOpenFile";
701  return PdfActionType2;
702})(PdfActionType || {});
703const AP_MODE_NORMAL = 1;
704const AP_MODE_ROLLOVER = 2;
705const AP_MODE_DOWN = 4;
706var PdfAnnotationSubtype = /* @__PURE__ */ ((PdfAnnotationSubtype2) => {
707  PdfAnnotationSubtype2[PdfAnnotationSubtype2["UNKNOWN"] = 0] = "UNKNOWN";
708  PdfAnnotationSubtype2[PdfAnnotationSubtype2["TEXT"] = 1] = "TEXT";
709  PdfAnnotationSubtype2[PdfAnnotationSubtype2["LINK"] = 2] = "LINK";
710  PdfAnnotationSubtype2[PdfAnnotationSubtype2["FREETEXT"] = 3] = "FREETEXT";
711  PdfAnnotationSubtype2[PdfAnnotationSubtype2["LINE"] = 4] = "LINE";
712  PdfAnnotationSubtype2[PdfAnnotationSubtype2["SQUARE"] = 5] = "SQUARE";
713  PdfAnnotationSubtype2[PdfAnnotationSubtype2["CIRCLE"] = 6] = "CIRCLE";
714  PdfAnnotationSubtype2[PdfAnnotationSubtype2["POLYGON"] = 7] = "POLYGON";
715  PdfAnnotationSubtype2[PdfAnnotationSubtype2["POLYLINE"] = 8] = "POLYLINE";
716  PdfAnnotationSubtype2[PdfAnnotationSubtype2["HIGHLIGHT"] = 9] = "HIGHLIGHT";
717  PdfAnnotationSubtype2[PdfAnnotationSubtype2["UNDERLINE"] = 10] = "UNDERLINE";
718  PdfAnnotationSubtype2[PdfAnnotationSubtype2["SQUIGGLY"] = 11] = "SQUIGGLY";
719  PdfAnnotationSubtype2[PdfAnnotationSubtype2["STRIKEOUT"] = 12] = "STRIKEOUT";
720  PdfAnnotationSubtype2[PdfAnnotationSubtype2["STAMP"] = 13] = "STAMP";
721  PdfAnnotationSubtype2[PdfAnnotationSubtype2["CARET"] = 14] = "CARET";
722  PdfAnnotationSubtype2[PdfAnnotationSubtype2["INK"] = 15] = "INK";
723  PdfAnnotationSubtype2[PdfAnnotationSubtype2["POPUP"] = 16] = "POPUP";
724  PdfAnnotationSubtype2[PdfAnnotationSubtype2["FILEATTACHMENT"] = 17] = "FILEATTACHMENT";
725  PdfAnnotationSubtype2[PdfAnnotationSubtype2["SOUND"] = 18] = "SOUND";
726  PdfAnnotationSubtype2[PdfAnnotationSubtype2["MOVIE"] = 19] = "MOVIE";
727  PdfAnnotationSubtype2[PdfAnnotationSubtype2["WIDGET"] = 20] = "WIDGET";
728  PdfAnnotationSubtype2[PdfAnnotationSubtype2["SCREEN"] = 21] = "SCREEN";
729  PdfAnnotationSubtype2[PdfAnnotationSubtype2["PRINTERMARK"] = 22] = "PRINTERMARK";
730  PdfAnnotationSubtype2[PdfAnnotationSubtype2["TRAPNET"] = 23] = "TRAPNET";
731  PdfAnnotationSubtype2[PdfAnnotationSubtype2["WATERMARK"] = 24] = "WATERMARK";
732  PdfAnnotationSubtype2[PdfAnnotationSubtype2["THREED"] = 25] = "THREED";
733  PdfAnnotationSubtype2[PdfAnnotationSubtype2["RICHMEDIA"] = 26] = "RICHMEDIA";
734  PdfAnnotationSubtype2[PdfAnnotationSubtype2["XFAWIDGET"] = 27] = "XFAWIDGET";
735  PdfAnnotationSubtype2[PdfAnnotationSubtype2["REDACT"] = 28] = "REDACT";
736  return PdfAnnotationSubtype2;
737})(PdfAnnotationSubtype || {});
738var AppearanceMode = /* @__PURE__ */ ((AppearanceMode2) => {
739  AppearanceMode2[AppearanceMode2["Normal"] = 0] = "Normal";
740  AppearanceMode2[AppearanceMode2["Rollover"] = 1] = "Rollover";
741  AppearanceMode2[AppearanceMode2["Down"] = 2] = "Down";
742  return AppearanceMode2;
743})(AppearanceMode || {});
744var PdfAnnotationName = /* @__PURE__ */ ((PdfAnnotationName2) => {
745  PdfAnnotationName2[PdfAnnotationName2["Unknown"] = -1] = "Unknown";
746  PdfAnnotationName2[PdfAnnotationName2["Comment"] = 0] = "Comment";
747  PdfAnnotationName2[PdfAnnotationName2["Key"] = 1] = "Key";
748  PdfAnnotationName2[PdfAnnotationName2["Note"] = 2] = "Note";
749  PdfAnnotationName2[PdfAnnotationName2["Help"] = 3] = "Help";
750  PdfAnnotationName2[PdfAnnotationName2["NewParagraph"] = 4] = "NewParagraph";
751  PdfAnnotationName2[PdfAnnotationName2["Paragraph"] = 5] = "Paragraph";
752  PdfAnnotationName2[PdfAnnotationName2["Insert"] = 6] = "Insert";
753  PdfAnnotationName2[PdfAnnotationName2["Graph"] = 7] = "Graph";
754  PdfAnnotationName2[PdfAnnotationName2["PushPin"] = 8] = "PushPin";
755  PdfAnnotationName2[PdfAnnotationName2["Paperclip"] = 9] = "Paperclip";
756  PdfAnnotationName2[PdfAnnotationName2["Tag"] = 10] = "Tag";
757  PdfAnnotationName2[PdfAnnotationName2["Speaker"] = 11] = "Speaker";
758  PdfAnnotationName2[PdfAnnotationName2["Mic"] = 12] = "Mic";
759  PdfAnnotationName2[PdfAnnotationName2["Approved"] = 13] = "Approved";
760  PdfAnnotationName2[PdfAnnotationName2["Experimental"] = 14] = "Experimental";
761  PdfAnnotationName2[PdfAnnotationName2["NotApproved"] = 15] = "NotApproved";
762  PdfAnnotationName2[PdfAnnotationName2["AsIs"] = 16] = "AsIs";
763  PdfAnnotationName2[PdfAnnotationName2["Expired"] = 17] = "Expired";
764  PdfAnnotationName2[PdfAnnotationName2["NotForPublicRelease"] = 18] = "NotForPublicRelease";
765  PdfAnnotationName2[PdfAnnotationName2["Confidential"] = 19] = "Confidential";
766  PdfAnnotationName2[PdfAnnotationName2["Final"] = 20] = "Final";
767  PdfAnnotationName2[PdfAnnotationName2["Sold"] = 21] = "Sold";
768  PdfAnnotationName2[PdfAnnotationName2["Departmental"] = 22] = "Departmental";
769  PdfAnnotationName2[PdfAnnotationName2["ForComment"] = 23] = "ForComment";
770  PdfAnnotationName2[PdfAnnotationName2["TopSecret"] = 24] = "TopSecret";
771  PdfAnnotationName2[PdfAnnotationName2["Draft"] = 25] = "Draft";
772  PdfAnnotationName2[PdfAnnotationName2["ForPublicRelease"] = 26] = "ForPublicRelease";
773  PdfAnnotationName2[PdfAnnotationName2["Completed"] = 27] = "Completed";
774  PdfAnnotationName2[PdfAnnotationName2["Void"] = 28] = "Void";
775  PdfAnnotationName2[PdfAnnotationName2["PreliminaryResults"] = 29] = "PreliminaryResults";
776  PdfAnnotationName2[PdfAnnotationName2["InformationOnly"] = 30] = "InformationOnly";
777  PdfAnnotationName2[PdfAnnotationName2["Rejected"] = 31] = "Rejected";
778  PdfAnnotationName2[PdfAnnotationName2["Witness"] = 32] = "Witness";
779  PdfAnnotationName2[PdfAnnotationName2["InitialHere"] = 33] = "InitialHere";
780  PdfAnnotationName2[PdfAnnotationName2["SignHere"] = 34] = "SignHere";
781  PdfAnnotationName2[PdfAnnotationName2["Accepted"] = 35] = "Accepted";
782  PdfAnnotationName2[PdfAnnotationName2["Custom"] = 36] = "Custom";
783  PdfAnnotationName2[PdfAnnotationName2["Image"] = 37] = "Image";
784  return PdfAnnotationName2;
785})(PdfAnnotationName || {});
786var PdfAnnotationLineEnding = /* @__PURE__ */ ((PdfAnnotationLineEnding2) => {
787  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["None"] = 0] = "None";
788  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Square"] = 1] = "Square";
789  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Circle"] = 2] = "Circle";
790  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Diamond"] = 3] = "Diamond";
791  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["OpenArrow"] = 4] = "OpenArrow";
792  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["ClosedArrow"] = 5] = "ClosedArrow";
793  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Butt"] = 6] = "Butt";
794  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["ROpenArrow"] = 7] = "ROpenArrow";
795  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["RClosedArrow"] = 8] = "RClosedArrow";
796  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Slash"] = 9] = "Slash";
797  PdfAnnotationLineEnding2[PdfAnnotationLineEnding2["Unknown"] = 10] = "Unknown";
798  return PdfAnnotationLineEnding2;
799})(PdfAnnotationLineEnding || {});
800var PdfAnnotationReplyType = /* @__PURE__ */ ((PdfAnnotationReplyType2) => {
801  PdfAnnotationReplyType2[PdfAnnotationReplyType2["Unknown"] = 0] = "Unknown";
802  PdfAnnotationReplyType2[PdfAnnotationReplyType2["Reply"] = 1] = "Reply";
803  PdfAnnotationReplyType2[PdfAnnotationReplyType2["Group"] = 2] = "Group";
804  return PdfAnnotationReplyType2;
805})(PdfAnnotationReplyType || {});
806var PDF_FORM_FIELD_TYPE = /* @__PURE__ */ ((PDF_FORM_FIELD_TYPE2) => {
807  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["UNKNOWN"] = 0] = "UNKNOWN";
808  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["PUSHBUTTON"] = 1] = "PUSHBUTTON";
809  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["CHECKBOX"] = 2] = "CHECKBOX";
810  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["RADIOBUTTON"] = 3] = "RADIOBUTTON";
811  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["COMBOBOX"] = 4] = "COMBOBOX";
812  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["LISTBOX"] = 5] = "LISTBOX";
813  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["TEXTFIELD"] = 6] = "TEXTFIELD";
814  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["SIGNATURE"] = 7] = "SIGNATURE";
815  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA"] = 8] = "XFA";
816  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_CHECKBOX"] = 9] = "XFA_CHECKBOX";
817  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_COMBOBOX"] = 10
817] = "XFA_COMBOBOX";
818  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_IMAGEFIELD"] = 11] = "XFA_IMAGEFIELD";
819  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_LISTBOX"] = 12] = "XFA_LISTBOX";
820  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_PUSHBUTTON"] = 13] = "XFA_PUSHBUTTON";
821  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_SIGNATURE"] = 14] = "XFA_SIGNATURE";
822  PDF_FORM_FIELD_TYPE2[PDF_FORM_FIELD_TYPE2["XFA_TEXTFIELD"] = 15] = "XFA_TEXTFIELD";
823  return PDF_FORM_FIELD_TYPE2;
824})(PDF_FORM_FIELD_TYPE || {});
825var PdfAnnotationColorType = /* @__PURE__ */ ((PdfAnnotationColorType2) => {
826  PdfAnnotationColorType2[PdfAnnotationColorType2["Color"] = 0] = "Color";
827  PdfAnnotationColorType2[PdfAnnotationColorType2["InteriorColor"] = 1] = "InteriorColor";
828  PdfAnnotationColorType2[PdfAnnotationColorType2["OverlayColor"] = 2] = "OverlayColor";
829  PdfAnnotationColorType2[PdfAnnotationColorType2["TextColor"] = 3] = "TextColor";
830  return PdfAnnotationColorType2;
831})(PdfAnnotationColorType || {});
832var PdfAnnotationBorderStyle = /* @__PURE__ */ ((PdfAnnotationBorderStyle2) => {
833  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["UNKNOWN"] = 0] = "UNKNOWN";
834  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["SOLID"] = 1] = "SOLID";
835  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["DASHED"] = 2] = "DASHED";
836  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["BEVELED"] = 3] = "BEVELED";
837  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["INSET"] = 4] = "INSET";
838  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["UNDERLINE"] = 5] = "UNDERLINE";
839  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["CLOUDY"] = 6] = "CLOUDY";
840  return PdfAnnotationBorderStyle2;
841})(PdfAnnotationBorderStyle || {});
842var PDF_FORM_FIELD_FLAG = /* @__PURE__ */ ((PDF_FORM_FIELD_FLAG2) => {
843  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["NONE"] = 0] = "NONE";
844  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["READONLY"] = 1] = "READONLY";
845  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["REQUIRED"] = 2] = "REQUIRED";
846  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["NOEXPORT"] = 4] = "NOEXPORT";
847  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_MULTIPLINE"] = 4096] = "TEXT_MULTIPLINE";
848  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_PASSWORD"] = 8192] = "TEXT_PASSWORD";
849  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_FILESELECT"] = 1048576] = "TEXT_FILESELECT";
850  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_DONOTSPELLCHECK"] = 4194304] = "TEXT_DONOTSPELLCHECK";
851  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_DONOTSCROLL"] = 8388608] = "TEXT_DONOTSCROLL";
852  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_COMB"] = 16777216] = "TEXT_COMB";
853  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_RICHTEXT"] = 33554432] = "TEXT_RICHTEXT";
854  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["BUTTON_NOTOGGLETOOFF"] = 16384] = "BUTTON_NOTOGGLETOOFF";
855  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["BUTTON_RADIO"] = 32768] = "BUTTON_RADIO";
856  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["BUTTON_PUSHBUTTON"] = 65536] = "BUTTON_PUSHBUTTON";
857  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["BUTTON_RADIOSINUNISON"] = 33554432] = "BUTTON_RADIOSINUNISON";
858  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_COMBO"] = 131072] = "CHOICE_COMBO";
859  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_EDIT"] = 262144] = "CHOICE_EDIT";
860  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_SORT"] = 524288] = "CHOICE_SORT";
861  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_MULTL_SELECT"] = 2097152] = "CHOICE_MULTL_SELECT";
862  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_DONOTSPELLCHECK"] = 4194304] = "CHOICE_DONOTSPELLCHECK";
863  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_COMMITONSELCHANGE"] = 67108864] = "CHOICE_COMMITONSELCHANGE";
864  return PDF_FORM_FIELD_FLAG2;
865})(PDF_FORM_FIELD_FLAG || {});
866var PdfPageObjectType = /* @__PURE__ */ ((PdfPageObjectType2) => {
867  PdfPageObjectType2[PdfPageObjectType2["UNKNOWN"] = 0] = "UNKNOWN";
868  PdfPageObjectType2[PdfPageObjectType2["TEXT"] = 1] = "TEXT";
869  PdfPageObjectType2[PdfPageObjectType2["PATH"] = 2] = "PATH";
870  PdfPageObjectType2[PdfPageObjectType2["IMAGE"] = 3] = "IMAGE";
871  PdfPageObjectType2[PdfPageObjectType2["SHADING"] = 4] = "SHADING";
872  PdfPageObjectType2[PdfPageObjectType2["FORM"] = 5] = "FORM";
873  return PdfPageObjectType2;
874})(PdfPageObjectType || {});
875const PdfAnnotationFlagName = Object.freeze({
876  [
877    1
878    /* INVISIBLE */
879  ]: "invisible",
880  [
881    2
882    /* HIDDEN */
883  ]: "hidden",
884  [
885    4
886    /* PRINT */
887  ]: "print",
888  [
889    8
890    /* NO_ZOOM */
891  ]: "noZoom",
892  [
893    16
894    /* NO_ROTATE */
895  ]: "noRotate",
896  [
897    32
898    /* NO_VIEW */
899  ]: "noView",
900  [
901    64
902    /* READ_ONLY */
903  ]: "readOnly",
904  [
905    128
906    /* LOCKED */
907  ]: "locked",
908  [
909    256
910    /* TOGGLE_NOVIEW */
911  ]: "toggleNoView",
912  [
913    512
914    /* LOCKED_CONTENTS */
915  ]: "lockedContents"
916});
917const PdfAnnotationFlagValue = Object.entries(
918  PdfAnnotationFlagName
919).reduce(
920  (acc, [bit, name]) => {
921    acc[name] = Number(bit);
922    return acc;
923  },
924  {}
925);
926function flagsToNames(raw) {
927  return Object.keys(PdfAnnotationFlagName).filter((flag) => (raw & flag) !== 0).map((flag) => PdfAnnotationFlagName[flag]);
928}
929function namesToFlags(names) {
930  return names.reduce(
931    (mask, name) => mask | PdfAnnotationFlagValue[name],
932    0
933    /* NONE */
934  );
935}
936var PDF_ANNOT_AACTION_EVENT = /* @__PURE__ */ ((PDF_ANNOT_AACTION_EVENT2) => {
937  PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2["KEY_STROKE"] = 12] = "KEY_STROKE";
938  PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2["FORMAT"] = 13] = "FORMAT";
939  PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2["VALIDATE"] = 14] = "VALIDATE";
940  PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2["CALCULATE"] = 15] = "CALCULATE";
941  return PDF_ANNOT_AACTION_EVENT2;
942})(PDF_ANNOT_AACTION_EVENT || {});
943var PdfJavaScriptWidgetEventType = /* @__PURE__ */ ((PdfJavaScriptWidgetEventType2) => {
944  PdfJavaScriptWidgetEventType2["Keystroke"] = "keystroke";
945  PdfJavaScriptWidgetEventType2["Format"] = "format";
946  PdfJavaScriptWidgetEventType2["Validate"] = "validate";
947  PdfJavaScriptWidgetEventType2["Calculate"] = "calculate";
948  return PdfJavaScriptWidgetEventType2;
949})(PdfJavaScriptWidgetEventType || {});
950var PdfJavaScriptActionTrigger = /* @__PURE__ */ ((PdfJavaScriptActionTrigger2) => {
951  PdfJavaScriptActionTrigger2["DocumentNamed"] = "document_named";
952  PdfJavaScriptActionTrigger2["WidgetKeystroke"] = "widget_keystroke";
953  PdfJavaScriptActionTrigger2["WidgetFormat"] = "widget_format";
954  PdfJavaScriptActionTrigger2["WidgetValidate"] = "widget_validate";
955  PdfJavaScriptActionTrigger2["WidgetCalculate"] = "widget_calculate";
956  return PdfJavaScriptActionTrigger2;
957})(PdfJavaScriptActionTrigger || {});
958var FontCharset = /* @__PURE__ */ ((FontCharset2) => {
959  FontCharset2[FontCharset2["ANSI"] = 0] = "ANSI";
960  FontCharset2[FontCharset2["DEFAULT"] = 1] = "DEFAULT";
961  FontCharset2[FontCharset2["SYMBOL"] = 2] = "SYMBOL";
962  FontCharset2[FontCharset2["SHIFTJIS"] = 128] = "SHIFTJIS";
963  FontCharset2[FontCharset2["HANGEUL"] = 129] = "HANGEUL";
964  FontCharset2[FontCharset2["GB2312"] = 134] = "GB2312";
965  FontCharset2[FontCharset2["CHINESEBIG5"] = 136] = "CHINESEBIG5";
966  FontCharset2[FontCharset2["GREEK"] = 161] = "GREEK";
967  FontCharset2[FontCharset2["VIETNAMESE"] = 163] = "VIETNAMESE";
968  FontCharset2[FontCharset2["HEBREW"] = 177] = "HEBREW";
969  FontCharset2[FontCharset2["ARABIC"] = 178] = "ARABIC";
970  FontCharset2[FontCharset2["CYRILLIC"] = 204] = "CYRILLIC";
971  FontCharset2[FontCharset2["THAI"] = 222] = "THAI";
972  FontCharset2[FontCharset2["EASTERNEUROPEAN"] = 238] = "EASTERNEUROPEAN";
973  return FontCharset2;
974})(FontCharset || {});
975var PdfPageFlattenFlag = /* @__PURE__ */ ((PdfPageFlattenFlag2) => {
976  PdfPageFlattenFlag2[PdfPageFlattenFlag2["Display"] = 0] = "Display";
977  PdfPageFlattenFlag2[PdfPageFlattenFlag2["Print"] = 1] = "Print";
978  return PdfPageFlattenFlag2;
979})(PdfPageFlattenFlag || {});
980var PdfErrorCode = /* @__PURE__ */ ((PdfErrorCode2) => {
981  PdfErrorCode2[PdfErrorCode2["Ok"] = 0] = "Ok";
982  PdfErrorCode2[PdfErrorCode2["Unknown"] = 1] = "Unknown";
983  PdfErrorCode2[PdfErrorCode2["NotFound"] = 2] = "NotFound";
984  PdfErrorCode2[PdfErrorCode2["WrongFormat"] = 3] = "WrongFormat";
985  PdfErrorCode2[PdfErrorCode2["Password"] = 4] = "Password";
986  PdfErrorCode2[PdfErrorCode2["Security"] = 5] = "Security";
987  PdfErrorCode2[PdfErrorCode2["PageError"] = 6] = "PageError";
988  PdfErrorCode2[PdfErrorCode2["XFALoad"] = 7] = "XFALoad";
989  PdfErrorCode2[PdfErrorCode2["XFALayout"] = 8] = "XFALayout";
990  PdfErrorCode2[PdfErrorCode2["Cancelled"] = 9] = "Cancelled";
991  PdfErrorCode2[PdfErrorCode2["Initialization"] = 10] = "Initialization";
992  PdfErrorCode2[PdfErrorCode2["NotReady"] = 11] = "NotReady";
993  PdfErrorCode2[PdfErrorCode2["NotSupport"] = 12] = "NotSupport";
994  PdfErrorCode2[PdfErrorCode2["LoadDoc"] = 13] = "LoadDoc";
995  PdfErrorCode2[PdfErrorCode2["DocNotOpen"] = 14] = "DocNotOpen";
996  PdfErrorCode2[PdfErrorCode2["CantCloseDoc"] = 15] = "CantCloseDoc";
997  PdfErrorCode2[PdfErrorCode2["CantCreateNewDoc"] = 16] = "CantCreateNewDoc";
998  PdfErrorCode2[PdfErrorCode2["CantImportPages"] = 17] = "CantImportPages";
999  PdfErrorCode2[PdfErrorCode2["CantCreateAnnot"] = 18] = "CantCreateAnnot";
1000  PdfErrorCode2[PdfErrorCode2["CantSetAnnotRect"] = 19] = "CantSetAnnotRect";
1001  PdfErrorCode2[PdfErrorCode2["CantSetAnnotContent"] = 20] = "CantSetAnnotContent";
1002  PdfErrorCode2[PdfErrorCode2["CantRemoveInkList"] = 21] = "CantRemoveInkList";
1003  PdfErrorCode2[PdfErrorCode2["CantAddInkStoke"] = 22] = "CantAddInkStoke";
1004  PdfErrorCode2[PdfErrorCode2["CantReadAttachmentSize"] = 23] = "CantReadAttachmentSize";
1005  PdfErrorCode2[PdfErrorCode2["CantReadAttachmentContent"] = 24] = "CantReadAttachmentContent";
1006  PdfErrorCode2[PdfErrorCode2["CantFocusAnnot"] = 25] = "CantFocusAnnot";
1007  PdfErrorCode2[PdfErrorCode2["CantSelectText"] = 26] = "CantSelectText";
1008  PdfErrorCode2[PdfErrorCode2["CantSelectOption"] = 27] = "CantSelectOption";
1009  PdfErrorCode2[PdfErrorCode2["CantCheckField"] = 28] = "CantCheckField";
1010  PdfErrorCode2[PdfErrorCode2["CantSetAnnotString"] = 29] = "CantSetAnnotString";
1011  PdfErrorCode2[PdfErrorCode2["CantDeletePage"] = 30] = "CantDeletePage";
1012  return PdfErrorCode2;
1013})(PdfErrorCode || {});
1014class PdfTaskHelper {
1015  /**
1016   * Create a task
1017   * @returns new task
1018   */
1019  static create() {
1020    return new Task();
1021  }
1022  /**
1023   * Create a task that has been resolved with value
1024   * @param result - resolved value
1025   * @returns resolved task
1026   */
1027  static resolve(result) {
1028    const task = new Task();
1029    task.resolve(result);
1030    return task;
1031  }
1032  /**
1033   * Create a task that has been rejected with error
1034   * @param reason - rejected error
1035   * @returns rejected task
1036   */
1037  static reject(reason) {
1038    const task = new Task();
1039    task.reject(reason);
1040    return task;
1041  }
1042  /**
1043   * Create a task that has been aborted with error
1044   * @param reason - aborted error
1045   * @returns aborted task
1046   */
1047  static abort(reason) {
1048    const task = new Task();
1049    task.reject(reason);
1050    return task;
1051  }
1052}
1053function pdfColorToWebColor(c) {
1054  const clamp = (n) => Math.max(0, Math.min(255, n));
1055  const toHex = (n) => clamp(n).toString(16).padStart(2, "0");
1056  return \`#\${toHex(c.red)}\${toHex(c.green)}\${toHex(c.blue)}\`;
1057}
1058function webColorToPdfColor(color) {
1059  if (/^#?[0-9a-f]{3}$/i.test(color)) {
1060    color = color.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, "#$1$1$2$2$3$3").toLowerCase();
1061  }
1062  const [, r, g, b] = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color) ?? (() => {
1063    throw new Error(\`Invalid hex colour: "\${color}"\`);
1064  })();
1065  return {
1066    red: parseInt(r, 16),
1067    green: parseInt(g, 16),
1068    blue: parseInt(b, 16)
1069  };
1070}
1071function pdfAlphaToWebOpacity(alpha) {
1072  const clamp = (n) => Math.max(0, Math.min(255, n));
1073  return clamp(alpha) / 255;
1074}
1075function webOpacityToPdfAlpha(opacity) {
1076  const clamp = (n, hi = 255) => Math.max(0, Math.min(hi, n));
1077  return clamp(Math.round(opacity * 255));
1078}
1079function pdfDateToDate(pdf) {
1080  if (!(pdf == null ? void 0 : pdf.startsWith("D:")) || pdf.length < 16) return;
1081  const y = +pdf.slice(2, 6);
1082  const mo = +pdf.slice(6, 8) - 1;
1083  const d = +pdf.slice(8, 10);
1084  const H = +pdf.slice(10, 12);
1085  const M = +pdf.slice(12, 14);
1086  const S = +pdf.slice(14, 16);
1087  return new Date(Date.UTC(y, mo, d, H, M, S));
1088}
1089function dateToPdfDate(date = /* @__PURE__ */ new Date()) {
1090  const z = (n, len = 2) => n.toString().padStart(len, "0");
1091  const YYYY = date.getUTCFullYear();
1092  const MM = z(date.getUTCMonth() + 1);
1093  const DD = z(date.getUTCDate());
1094  const HH = z(date.getUTCHours());
1095  const mm = z(date.getUTCMinutes());
1096  const SS = z(date.getUTCSeconds());
1097  return \`D:\${YYYY}\${MM}\${DD}\${HH}\${mm}\${SS}\`;
1098}
1099const TEXT_ALIGNMENT_INFOS = Object.freeze([
1100  { id: PdfTextAlignment.Left, label: "Left", css: "left" },
1101  { id: PdfTextAlignment.Center, label: "Center", css: "center" },
1102  { id: PdfTextAlignment.Right, label: "Right", css: "right" }
1103]);
1104TEXT_ALIGNMENT_INFOS.reduce(
1105  (m, info) => {
1106    m[info.id] = info;
1107    return m;
1108  },
1109  {}
1110);
1111TEXT_ALIGNMENT_INFOS.reduce(
1112  (m, info) => {
1113    m[info.css] = info.id;
1114    return m;
1115  },
1116  {}
1117);
1118TEXT_ALIGNMENT_INFOS.map((info) => ({
1119  value: info.id,
1120  label: info.label
1121}));
1122var PdfStandardFontFamily = /* @__PURE__ */ ((PdfStandardFontFamily2) => {
1123  PdfStandardFontFamily2["Courier"] = "Courier";
1124  PdfStandardFontFamily2["Helvetica"] = "Helvetica";
1125  PdfStandardFontFamily2["Times"] = "Times";
1126  PdfStandardFontFamily2["Symbol"] = "Symbol";
1127  PdfStandardFontFamily2["ZapfDingbats"] = "ZapfDingbats";
1128  PdfStandardFontFamily2["Unknown"] = "Unknown";
1129  return PdfStandardFontFamily2;
1130})(PdfStandardFontFamily || {});
1131PdfStandardFont.Helvetica;
1132const HELVETICA_DESC = {
1133  id: PdfStandardFont.Helvetica,
1134  family: "Helvetica",
1135  bold: false,
1136  italic: false,
1137  label: "Helvetica",
1138  css: "Helvetica, Arial, sans-serif"
1139};
1140const STANDARD_FONT_DESCRIPTORS = Object.freeze([
1141  {
1142    id: PdfStandardFont.Courier,
1143    family: "Courier",
1144    bold: false,
1145    italic: false,
1146    label: "Courier",
1147    css: "Courier, monospace"
1148  },
1149  {
1150    id: PdfStandardFont.Courier_Bold,
1151    family: "Courier",
1152    bold: true,
1153    italic: false,
1154    label: "Courier Bold",
1155    css: "Courier, monospace"
1156  },
1157  {
1158    id: PdfStandardFont.Courier_BoldOblique,
1159    family: "Courier",
1160    bold: true,
1161    italic: true,
1162    label: "Courier Bold Oblique",
1163    css: "Courier, monospace"
1164  },
1165  {
1166    id: PdfStandardFont.Courier_Oblique,
1167    family: "Courier",
1168    bold: false,
1169    italic: true,
1170    label: "Courier Oblique",
1171    css: "Courier, monospace"
1172  },
1173  HELVETICA_DESC,
1174  {
1175    id: PdfStandardFont.Helvetica_Bold,
1176    family: "Helvetica",
1177    bold: true,
1178    italic: false,
1179    label: "Helvetica Bold",
1180    css: "Helvetica, Arial, sans-serif"
1181  },
1182  {
1183    id: PdfStandardFont.Helvetica_BoldOblique,
1184    family: "Helvetica",
1185    bold: true,
1186    italic: true,
1187    label: "Helvetica Bold Oblique",
1188    css: "Helvetica, Arial, sans-serif"
1189  },
1190  {
1191    id: PdfStandardFont.Helvetica_Oblique,
1192    family: "Helvetica",
1193    bold: false,
1194    italic: true,
1195    label: "Helvetica Oblique",
1196    css: "Helvetica, Arial, sans-serif"
1197  },
1198  {
1199    id: PdfStandardFont.Times_Roman,
1200    family: "Times",
1201    bold: false,
1202    italic: false,
1203    label: "Times Roman",
1204    css: '"Times New Roman", Times, serif'
1205  },
1206  {
1207    id: PdfStandardFont.Times_Bold,
1208    family: "Times",
1209    bold: true,
1210    italic: false,
1211    label: "Times Bold",
1212    css: '"Times New Roman", Times, serif'
1213  },
1214  {
1215    id: PdfStandardFont.Times_BoldItalic,
1216    family: "Times",
1217    bold: true,
1218    italic: true,
1219    label: "Times Bold Italic",
1220    css: '"Times New Roman", Times, serif'
1221  },
1222  {
1223    id: PdfStandardFont.Times_Italic,
1224    family: "Times",
1225    bold: false,
1226    italic: true,
1227    label: "Times Italic",
1228    css: '"Times New Roman", Times, serif'
1229  },
1230  {
1231    id: PdfStandardFont.Symbol,
1232    family: "Symbol",
1233    bold: false,
1234    italic: false,
1235    label: "Symbol",
1236    css: "Symbol, serif"
1237  },
1238  {
1239    id: PdfStandardFont.ZapfDingbats,
1240    family: "ZapfDingbats",
1241    bold: false,
1242    italic: false,
1243    label: "Zapf Dingbats",
1244    css: "ZapfDingbats, serif"
1245  }
1246]);
1247STANDARD_FONT_DESCRIPTORS.reduce((m, d) => (m[d.id] = d, m), {});
1248const familyStyleToId = /* @__PURE__ */ new Map();
1249for (const d of STANDARD_FONT_DESCRIPTORS) {
1250  familyStyleToId.set(\`\${d.family}_\${d.bold}_\${d.italic}\`, d.id);
1251}
1252Object.values(PdfStandardFontFamily).filter(
1253  (f) => f !== "Unknown"
1254  /* Unknown */
1255).map((family) => ({ value: family, label: family }));
1256[
1257  ...new Set(STANDARD_FONT_DESCRIPTORS.map((d) => d.family))
1258];
1259const BLEND_MODE_INFOS = Object.freeze([
1260  { id: PdfBlendMode.Normal, label: "Normal", css: "normal" },
1261  { id: PdfBlendMode.Multiply, label: "Multiply", css: "multiply" },
1262  { id: PdfBlendMode.Screen, label: "Screen", css: "screen" },
1263  { id: PdfBlendMode.Overlay, label: "Overlay", css: "overlay" },
1264  { id: PdfBlendMode.Darken, label: "Darken", css: "darken" },
1265  { id: PdfBlendMode.Lighten, label: "Lighten", css: "lighten" },
1266  { id: PdfBlendMode.ColorDodge, label: "Color Dodge", css: "color-dodge" },
1267  { id: PdfBlendMode.ColorBurn, label: "Color Burn", css: "color-burn" },
1268  { id: PdfBlendMode.HardLight, label: "Hard Light", css: "hard-light" },
1269  { id: PdfBlendMode.SoftLight, label: "Soft Light", css: "soft-light" },
1270  { id: PdfBlendMode.Difference, label: "Difference", css: "difference" },
1271  { id: PdfBlendMode.Exclusion, label: "Exclusion", css: "exclusion" },
1272  { id: PdfBlendMode.Hue, label: "Hue", css: "hue" },
1273  { id: PdfBlendMode.Saturation, label: "Saturation", css: "saturation" },
1274  { id: PdfBlendMode.Color, label: "Color", css: "color" },
1275  { id: PdfBlendMode.Luminosity, label: "Luminosity", css: "luminosity" }
1276]);
1277BLEND_MODE_INFOS.reduce(
1278  (m, info) => {
1279    m[info.id] = info;
1280    return m;
1281  },
1282  {}
1283);
1284BLEND_MODE_INFOS.reduce(
1285  (m, info) => {
1286    m[info.css] = info.id;
1287    return m;
1288  },
1289  {}
1290);
1291BLEND_MODE_INFOS.map((info) => ({
1292  value: info.id,
1293  label: info.label
1294}));
1295BLEND_MODE_INFOS.map((info) => info.id);
1296function deserializeLogger(serialized) {
1297  var _a, _b, _c;
1298  switch (serialized.type) {
1299    case "noop":
1300      return new NoopLogger();
1301    case "console":
1302      return new ConsoleLogger();
1303    case "perf":
1304      return new PerfLogger();
1305    case "level":
1306      if (!((_a = serialized.config) == null ? void 0 : _a.logger) || ((_b = serialized.config) == null ? void 0 : _b.level) === void 0) {
1307        throw new Error("LevelLogger requires logger and level in config");
1308      }
1309      return new LevelLogger(deserializeLogger(serialized.config.logger), serialized.config.level);
1310    case "all":
1311      if (!((_c = serialized.config) == null ? void 0 : _c.loggers)) {
1312        throw new Error("AllLogger requires loggers array in config");
1313      }
1314      return new AllLogger(serialized.config.loggers.map(deserializeLogger));
1315    default:
1316      return new NoopLogger();
1317  }
1318}
1319const V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1320function isUuidV4(str) {
1321  return V4_REGEX.test(str);
1322}
1323function getRandomBytes(len) {
1324  var _a;
1325  if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.getRandomValues) === "function") {
1326    return globalThis.crypto.getRandomValues(new Uint8Array(len));
1327  }
1328  if (typeof require === "function") {
1329    try {
1330      const { randomBytes } = require("crypto");
1331      return randomBytes(len);
1332    } catch {
1333    }
1334  }
1335  const bytes = new Uint8Array(len);
1336  for (let i = 0; i < len; i++) bytes[i] = Math.floor(Math.random() * 256);
1337  return bytes;
1338}
1339function uuidV4() {
1340  var _a;
1341  if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) === "function") {
1342    return globalThis.crypto.randomUUID();
1343  }
1344  const bytes = getRandomBytes(16);
1345  bytes[6] = bytes[6] & 15 | 64;
1346  bytes[8] = bytes[8] & 63 | 128;
1347  const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1348  return \`\${hex.slice(0, 8)}-\${hex.slice(8, 12)}-\${hex.slice(12, 16)}-\${hex.slice(16, 20)}-\${hex.slice(20)}\`;
1349}
1350function getImageMetadata(buffer) {
1351  if (buffer.byteLength < 4) return null;
1352  const bytes = new Uint8Array(buffer);
1353  if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {
1354    return parsePng(buffer);
1355  }
1356  if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {
1357    return parseJpeg(buffer);
1358  }
1359  if (bytes[0] === 37 && bytes[1] === 80 && bytes[2] === 68 && bytes[3] === 70) {
1360    return { mimeType: "application/pdf" };
1361  }
1362  return null;
1363}
1364function parsePng(buffer) {
1365  if (buffer.byteLength < 24) return null;
1366  const view = new DataView(buffer);
1367  const width = view.getUint32(16);
1368  const height = view.getUint32(20);
1369  if (width === 0 || height === 0) return null;
1370  return { mimeType: "image/png", width, height };
1371}
1372function parseJpeg(buffer) {
1373  const bytes = new Uint8Array(buffer);
1374  let offset = 2;
1375  while (offset + 4 < bytes.byteLength) {
1376    if (bytes[offset] !== 255) return null;
1377    const marker = bytes[offset + 1];
1378    if (marker >= 192 && marker <= 195) {
1379      if (offset + 9 > bytes.byteLength) return null;
1380      const view = new DataView(buffer, offset + 5);
1381      const height = view.getUint16(0);
1382      const width = view.getUint16(2);
1383      if (width === 0 || height === 0) return null;
1384      return { mimeType: "image/jpeg", width, height };
1385    }
1386    if (marker === 216 || marker === 217) {
1387      offset += 2;
1388    } else if (marker === 255) {
1389      offset += 1;
1390    } else {
1391      const segLen = bytes[offset + 2] << 8 | bytes[offset + 3];
1392      offset += 2 + segLen;
1393    }
1394  }
1395  return null;
1396}
1397var createPdfium = (() => {
1398  var _scriptName = import.meta.url;
1399  return async function(moduleArg = {}) {
1400    var moduleRtn;
1401    var Module = moduleArg;
1402    var readyPromiseResolve, readyPromiseReject;
1403    var readyPromise = new Promise((resolve, reject) => {
1404      readyPromiseResolve = resolve;
1405      readyPromiseReject = reject;
1406    });
1407    [
1408      "_EPDF_GetMetaKeyCount",
1409      "_EPDF_GetMetaKeyName",
1410      "_EPDF_GetMetaTrapped",
1411      "_EPDF_GetPageRotationByIndex",
1412      "_EPDF_GetPageSizeByIndexNormalized",
1413      "_EPDF_HasMetaText",
1414      "_EPDF_IsEncrypted",
1415      "_EPDF_IsOwnerUnlocked",
1416      "_EPDF_LoadPageNormalized",
1417      "_EPDF_PNG_EncodeRGBA",
1418      "_EPDF_RemoveEncryption",
1419      "_EPDF_RenderAnnotBitmap",
1420      "_EPDF_RenderAnnotBitmapUnrotated",
1421      "_EPDF_SetEncryption",
1422      "_EPDF_SetMetaText",
1423      "_EPDF_SetMetaTrapped",
1424      "_EPDF_UnlockOwnerPermissions",
1425      "_EPDFAction_CreateGoTo",
1426      "_EPDFAction_CreateGoToNamed",
1427      "_EPDFAction_CreateLaunch",
1428      "_EPDFAction_CreateRemoteGoToByName",
1429      "_EPDFAction_CreateRemoteGoToDest",
1430      "_EPDFAction_CreateURI",
1431      "_EPDFAnnot_ApplyRedaction",
1432      "_EPDFAnnot_ClearBorderEffect",
1433      "_EPDFAnnot_ClearColor",
1434      "_EPDFAnnot_ClearMKColor",
1435      "_EPDFAnnot_ClearRectangleDifferences",
1436      "_EPDFAnnot_ExportAppearanceAsDocument",
1437      "_EPDFAnnot_ExportMultipleAppearancesAsDocument",
1438      "_EPDFAnnot_Flatten",
1439      "_EPDFAnnot_GenerateAppearance",
1440      "_EPDFAnnot_GenerateAppearanceWithBlend",
1441      "_EPDFAnnot_GenerateFormFieldAP",
1442      "_EPDFAnnot_GetAPMatrix",
1443      "_EPDFAnnot_GetAvailableAppearanceModes",
1444      "_EPDFAnnot_GetBlendMode",
1445      "_EPDFAnnot_GetBorderDashPattern",
1446      "_EPDFAnnot_GetBorderDashPatternCount",
1447      "_EPDFAnnot_GetBorderEffect",
1448      "_EPDFAnnot_GetBorderStyle",
1449      "_EPDFAnnot_GetButtonExportValue",
1450      "_EPDFAnnot_GetCalloutLine",
1451      "_EPDFAnnot_GetCalloutLineCount",
1452      "_EPDFAnnot_GetColor",
1453      "_EPDFAnnot_GetDefaultAppearance",
1454      "_EPDFAnnot_GetExtendedRotation",
1455      "_EPDFAnnot_GetFormFieldObjectNumber",
1456      "_EPDFAnnot_GetFormFieldRawValue",
1457      "_EPDFAnnot_GetIntent",
1458      "_EPDFAnnot_GetLineEndings",
1459      "_EPDFAnnot_GetMKColor",
1460      "_EPDFAnnot_GetName",
1461      "_EPDFAnnot_GetOpacity",
1462      "_EPDFAnnot_GetOverlayText",
1463      "_EPDFAnnot_GetOverlayTextRepeat",
1464      "_EPDFAnnot_GetRect",
1465      "_EPDFAnnot_GetRectangleDifferences",
1466      "_EPDFAnnot_GetReplyType",
1467      "_EPDFAnnot_GetRichContent",
1468      "_EPDFAnnot_GetRotate",
1469      "_EPDFAnnot_GetTextAlignment",
1470      "_EPDFAnnot_GetUnrotatedRect",
1471      "_EPDFAnnot_GetVerticalAlignment",
1472      "_EPDFAnnot_HasAppearanceStream",
1473      "_EPDFAnnot_SetAction",
1474      "_EPDFAnnot_SetAPMatrix",
1475      "_EPDFAnnot_SetAppearanceFromPage",
1476      "_EPDFAnnot_SetBorderDashPattern",
1477      "_EPDFAnnot_SetBorderEffect",
1478      "_EPDFAnnot_SetBorderStyle",
1479      "_EPDFAnnot_SetCalloutLine",
1480      "_EPDFAnnot_SetColor",
1481      "_EPDFAnnot_SetDefaultAppearance",
1482      "_EPDFAnnot_SetExtendedRotation",
1483      "_EPDFAnnot_SetFormFieldName",
1484      "_EPDFAnnot_SetFormFieldOptions",
1485      "_EPDFAnnot_SetFormFieldValue",
1486      "_EPDFAnnot_SetIntent",
1487      "_EPDFAnnot_SetLine",
1488      "_EPDFAnnot_SetLineEndings",
1489      "_EPDFAnnot_SetLinkedAnnot",
1490      "_EPDFAnnot_SetMKColor",
1491      "_EPDFAnnot_SetName",
1492      "_EPDFAnnot_SetNumberValue",
1493      "_EPDFAnnot_SetOpacity",
1494      "_EPDFAnnot_SetOverlayText",
1495      "_EPDFAnnot_SetOverlayTextRepeat",
1496      "_EPDFAnnot_SetRectangleDifferences",
1497      "_EPDFAnnot_SetReplyType",
1498      "_EPDFAnnot_SetRotate",
1499      "_EPDFAnnot_SetTextAlignment",
1500      "_EPDFAnnot_SetUnrotatedRect",
1501      "_EPDFAnnot_SetVerticalAlignment",
1502      "_EPDFAnnot_SetVertices",
1503      "_EPDFAnnot_ShareFormField",
1504      "_EPDFAnnot_UpdateAppearanceToRect",
1505      "_EPDFAttachment_GetDescription",
1506      "_EPDFAttachment_GetIntegerValue",
1507      "_EPDFAttachment_SetDescription",
1508      "_EPDFAttachment_SetSubtype",
1509      "_EPDFBookmark_AppendChild",
1510      "_EPDFBookmark_Clear",
1511      "_EPDFBookmark_ClearTarget",
1512      "_EPDFBookmark_Create",
1513      "_EPDFBookmark_Delete",
1514      "_EPDFBookmark_InsertAfter",
1515      "_EPDFBookmark_SetAction",
1516      "_EPDFBookmark_SetDest",
1517      "_EPDFBookmark_SetTitle",
1518      "_EPDFCatalog_GetLanguage",
1519      "_EPDFDest_CreateRemoteView",
1520      "_EPDFDest_CreateRemoteXYZ",
1521      "_EPDFDest_CreateView",
1522      "_EPDFDest_CreateXYZ",
1523      "_EPDFImageObj_SetJpeg",
1524      "_EPDFImageObj_SetPng",
1525      "_EPDFNamedDest_Remove",
1526      "_EPDFNamedDest_SetDest",
1527      "_EPDFPage_ApplyRedactions",
1528      "_EPDFPage_CreateAnnot",
1529      "_EPDFPage_CreateFormField",
1530      "_EPDFPage_GetAnnotByName",
1531      "_EPDFPage_GetAnnotCountRaw",
1532      "_EPDFPage_GetAnnotRaw",
1533      "_EPDFPage_RemoveAnnotByName",
1534      "_EPDFPage_RemoveAnnotRaw",
1535      "_EPDFText_RedactInQuads",
1536      "_EPDFText_RedactInRect",
1537      "_FORM_CanRedo",
1538      "_FORM_CanUndo",
1539      "_FORM_DoDocumentAAction",
1540      "_FORM_DoDocumentJSAction",
1541      "_FORM_DoDocumentOpenAction",
1542      "_FORM_DoPageAAction",
1543      "_FORM_ForceToKillFocus",
1544      "_FORM_GetFocusedAnnot",
1545      "_FORM_GetFocusedText",
1546      "_FORM_GetSelectedText",
1547      "_FORM_IsIndexSelected",
1548      "_FORM_OnAfterLoadPage",
1549      "_FORM_OnBeforeClosePage",
1550      "_FORM_OnChar",
1551      "_FORM_OnFocus",
1552      "_FORM_OnKeyDown",
1553      "_FORM_OnKeyUp",
1554      "_FORM_OnLButtonDoubleClick",
1555      "_FORM_OnLButtonDown",
1556      "_FORM_OnLButtonUp",
1557      "_FORM_OnMouseMove",
1558      "_FORM_OnMouseWheel",
1559      "_FORM_OnRButtonDown",
1560      "_FORM_OnRButtonUp",
1561      "_FORM_Redo",
1562      "_FORM_ReplaceAndKeepSelection",
1563      "_FORM_ReplaceSelection",
1564      "_FORM_SelectAllText",
1565      "_FORM_SetFocusedAnnot",
1566      "_FORM_SetIndexSelected",
1567      "_FORM_Undo",
1568      "_FPDF_AddInstalledFont",
1569      "_FPDF_CloseDocument",
1570      "_FPDF_ClosePage",
1571      "_FPDF_CloseXObject",
1572      "_FPDF_CopyViewerPreferences",
1573      "_FPDF_CountNamedDests",
1574      "_FPDF_CreateClipPath",
1575      "_FPDF_CreateNewDocument",
1576      "_FPDF_DestroyClipPath",
1577      "_FPDF_DestroyLibrary",
1578      "_FPDF_DeviceToPage",
1579      "_FPDF_DocumentHasValidCrossReferenceTable",
1580      "_FPDF_FFLDraw",
1581      "_FPDF_FreeDefaultSystemFontInfo",
1582      "_FPDF_GetDefaultSystemFontInfo",
1583      "_FPDF_GetDefaultTTFMap",
1584      "_FPDF_GetDefaultTTFMapCount",
1585      "_FPDF_GetDefaultTTFMapEntry",
1586      "_FPDF_GetDocPermissions",
1587      "_FPDF_GetDocUserPermissions",
1588      "_FPDF_GetFileIdentifier",
1589      "_FPDF_GetFileVersion",
1590      "_FPDF_GetFormType",
1591      "_FPDF_GetLastError",
1592      "_FPDF_GetMetaText",
1593      "_FPDF_GetNamedDest",
1594      "_FPDF_GetNamedDestByName",
1595      "_FPDF_GetPageAAction",
1596      "_FPDF_GetPageBoundingBox",
1597      "_FPDF_GetPageCount",
1598      "_FPDF_GetPageHeight",
1599      "_FPDF_GetPageHeightF",
1600      "_FPDF_GetPageLabel",
1601      "_FPDF_GetPageSizeByIndex",
1602      "_FPDF_GetPageSizeByIndexF",
1603      "_FPDF_GetPageWidth",
1604      "_FPDF_GetPageWidthF",
1605      "_FPDF_GetSecurityHandlerRevision",
1606      "_FPDF_GetSignatureCount",
1607      "_FPDF_GetSignatureObject",
1608      "_FPDF_GetTrailerEnds",
1609      "_FPDF_GetXFAPacketContent",
1610      "_FPDF_GetXFAPacketCount",
1611      "_FPDF_GetXFAPacketName",
1612      "_FPDF_ImportNPagesToOne",
1613      "_FPDF_ImportPages",
1614      "_FPDF_ImportPagesByIndex",
1615      "_FPDF_InitLibrary",
1616      "_FPDF_InitLibraryWithConfig",
1617      "_FPDF_LoadCustomDocument",
1618      "_FPDF_LoadDocument",
1619      "_FPDF_LoadMemDocument",
1620      "_FPDF_LoadMemDocument64",
1621      "_FPDF_LoadPage",
1622      "_FPDF_LoadXFA",
1623      "_FPDF_MovePages",
1624      "_FPDF_NewFormObjectFromXObject",
1625      "_FPDF_NewXObjectFromPage",
1626      "_FPDF_PageToDevice",
1627      "_FPDF_RemoveFormFieldHighlight",
1628      "_FPDF_RenderPage_Close",
1629      "_FPDF_RenderPage_Continue",
1630      "_FPDF_RenderPageBitmap",
1631      "_FPDF_RenderPageBitmap_Start",
1632      "_FPDF_RenderPageBitmapWithColorScheme_Start",
1633      "_FPDF_RenderPageBitmapWithMatrix",
1634      "_FPDF_SaveAsCopy",
1635      "_FPDF_SaveWithVersion",
1636      "_FPDF_SetFormFieldHighlightAlpha",
1637      "_FPDF_SetFormFieldHighlightColor",
1638      "_FPDF_SetSandBoxPolicy",
1639      "_FPDF_SetSystemFontInfo",
1640      "_FPDF_StructElement_Attr_CountChildren",
1641      "_FPDF_StructElement_Attr_GetBlobValue",
1642      "_FPDF_StructElement_Attr_GetBooleanValue",
1643      "_FPDF_StructElement_Attr_GetChildAtIndex",
1644      "_FPDF_StructElement_Attr_GetCount",
1645      "_FPDF_StructElement_Attr_GetName",
1646      "_FPDF_StructElement_Attr_GetNumberValue",
1647      "_FPDF_StructElement_Attr_GetStringValue",
1648      "_FPDF_StructElement_Attr_GetType",
1649      "_FPDF_StructElement_Attr_GetValue",
1650      "_FPDF_StructElement_CountChildren",
1651      "_FPDF_StructElement_GetActualText",
1652      "_FPDF_StructElement_GetAltText",
1653      "_FPDF_StructElement_GetAttributeAtIndex",
1654      "_FPDF_StructElement_GetAttributeCount",
1655      "_FPDF_StructElement_GetChildAtIndex",
1656      "_FPDF_StructElement_GetChildMarkedContentID",
1657      "_FPDF_StructElement_GetID",
1658      "_FPDF_StructElement_GetLang",
1659      "_FPDF_StructElement_GetMarkedContentID",
1660      "_FPDF_StructElement_GetMarkedContentIdAtIndex",
1661      "_FPDF_StructElement_GetMarkedContentIdCount",
1662      "_FPDF_StructElement_GetObjType",
1663      "_FPDF_StructElement_GetParent",
1664      "_FPDF_StructElement_GetStringAttribute",
1665      "_FPDF_StructElement_GetTitle",
1666      "_FPDF_StructElement_GetType",
1667      "_FPDF_StructTree_Close",
1668      "_FPDF_StructTree_CountChildren",
1669      "_FPDF_StructTree_GetChildAtIndex",
1670      "_FPDF_StructTree_GetForPage",
1671      "_FPDF_VIEWERREF_GetDuplex",
1672      "_FPDF_VIEWERREF_GetName",
1673      "_FPDF_VIEWERREF_GetNumCopies",
1674      "_FPDF_VIEWERREF_GetPrintPageRange",
1675      "_FPDF_VIEWERREF_GetPrintPageRangeCount",
1676      "_FPDF_VIEWERREF_GetPrintPageRangeElement",
1677      "_FPDF_VIEWERREF_GetPrintScaling",
1678      "_FPDFAction_GetDest",
1679      "_FPDFAction_GetFilePath",
1680      "_FPDFAction_GetType",
1681      "_FPDFAction_GetURIPath",
1682      "_FPDFAnnot_AddFileAttachment",
1683      "_FPDFAnnot_AddInkStroke",
1684      "_FPDFAnnot_AppendAttachmentPoints",
1685      "_FPDFAnnot_AppendObject",
1686      "_FPDFAnnot_CountAttachmentPoints",
1687      "_FPDFAnnot_GetAP",
1688      "_FPDFAnnot_GetAttachmentPoints",
1689      "_FPDFAnnot_GetBorder",
1690      "_FPDFAnnot_GetColor",
1691      "_FPDFAnnot_GetFileAttachment",
1692      "_FPDFAnnot_GetFlags",
1693      "_FPDFAnnot_GetFocusableSubtypes",
1694      "_FPDFAnnot_GetFocusableSubtypesCount",
1695      "_FPDFAnnot_GetFontColor",
1696      "_FPDFAnnot_GetFontSize",
1697      "_FPDFAnnot_GetFormAdditionalActionJavaScript",
1698      "_FPDFAnnot_GetFormControlCount",
1699      "_FPDFAnnot_GetFormControlIndex",
1700      "_FPDFAnnot_GetFormFieldAlternateName",
1701      "_FPDFAnnot_GetFormFieldAtPoint",
1702      "_FPDFAnnot_GetFormFieldExportValue",
1703      "_FPDFAnnot_GetFormFieldFlags",
1704      "_FPDFAnnot_GetFormFieldName",
1705      "_FPDFAnnot_GetFormFieldType",
1706      "_FPDFAnnot_GetFormFieldValue",
1707      "_FPDFAnnot_GetInkListCount",
1708      "_FPDFAnnot_GetInkListPath",
1709      "_FPDFAnnot_GetLine",
1710      "_FPDFAnnot_GetLink",
1711      "_FPDFAnnot_GetLinkedAnnot",
1712      "_FPDFAnnot_GetNumberValue",
1713      "_FPDFAnnot_GetObject",
1714      "_FPDFAnnot_GetObjectCount",
1715      "_FPDFAnnot_GetOptionCount",
1716      "_FPDFAnnot_GetOptionLabel",
1717      "_FPDFAnnot_GetRect",
1718      "_FPDFAnnot_GetStringValue",
1719      "_FPDFAnnot_GetSubtype",
1720      "_FPDFAnnot_GetValueType",
1721      "_FPDFAnnot_GetVertices",
1722      "_FPDFAnnot_HasAttachmentPoints",
1723      "_FPDFAnnot_HasKey",
1724      "_FPDFAnnot_IsChecked",
1725      "_FPDFAnnot_IsObjectSupportedSubtype",
1726      "_FPDFAnnot_IsOptionSelected",
1727      "_FPDFAnnot_IsSupportedSubtype",
1728      "_FPDFAnnot_RemoveInkList",
1729      "_FPDFAnnot_RemoveObject",
1730      "_FPDFAnnot_SetAP",
1731      "_FPDFAnnot_SetAttachmentPoints",
1732      "_FPDFAnnot_SetBorder",
1733      "_FPDFAnnot_SetColor",
1734      "_FPDFAnnot_SetFlags",
1735      "_FPDFAnnot_SetFocusableSubtypes",
1736      "_FPDFAnnot_SetFontColor",
1737      "_FPDFAnnot_SetFormFieldFlags",
1738      "_FPDFAnnot_SetRect",
1739      "_FPDFAnnot_SetStringValue",
1740      "_FPDFAnnot_SetURI",
1741      "_FPDFAnnot_UpdateObject",
1742      "_FPDFAttachment_GetFile",
1743      "_FPDFAttachment_GetName",
1744      "_FPDFAttachment_GetStringValue",
1745      "_FPDFAttachment_GetSubtype",
1746      "_FPDFAttachment_GetValueType",
1747      "_FPDFAttachment_HasKey",
1748      "_FPDFAttachment_SetFile",
1749      "_FPDFAttachment_SetStringValue",
1750      "_FPDFAvail_Create",
1751      "_FPDFAvail_Destroy",
1752      "_FPDFAvail_GetDocument",
1753      "_FPDFAvail_GetFirstPageNum",
1754      "_FPDFAvail_IsDocAvail",
1755      "_FPDFAvail_IsFormAvail",
1756      "_FPDFAvail_IsLinearized",
1757      "_FPDFAvail_IsPageAvail",
1758      "_FPDFBitmap_Create",
1759      "_FPDFBitmap_CreateEx",
1760      "_FPDFBitmap_Destroy",
1761      "_FPDFBitmap_FillRect",
1762      "_FPDFBitmap_GetBuffer",
1763      "_FPDFBitmap_GetFormat",
1764      "_FPDFBitmap_GetHeight",
1765      "_FPDFBitmap_GetStride",
1766      "_FPDFBitmap_GetWidth",
1767      "_FPDFBookmark_Find",
1768      "_FPDFBookmark_GetAction",
1769      "_FPDFBookmark_GetCount",
1770      "_FPDFBookmark_GetDest",
1771      "_FPDFBookmark_GetFirstChild",
1772      "_FPDFBookmark_GetNextSibling",
1773      "_FPDFBookmark_GetTitle",
1774      "_FPDFCatalog_GetLanguage",
1775      "_FPDFCatalog_IsTagged",
1776      "_FPDFCatalog_SetLanguage",
1777      "_FPDFClipPath_CountPaths",
1778      "_FPDFClipPath_CountPathSegments",
1779      "_FPDFClipPath_GetPathSegment",
1780      "_FPDFDest_GetDestPageIndex",
1781      "_FPDFDest_GetLocationInPage",
1782      "_FPDFDest_GetView",
1783      "_FPDFDoc_AddAttachment",
1784      "_FPDFDoc_CloseJavaScriptAction",
1785      "_FPDFDoc_DeleteAttachment",
1786      "_FPDFDOC_ExitFormFillEnvironment",
1787      "_FPDFDoc_GetAttachment",
1788      "_FPDFDoc_GetAttachmentCount",
1789      "_FPDFDoc_GetJavaScriptAction",
1790      "_FPDFDoc_GetJavaScriptActionCount",
1791      "_FPDFDoc_GetPageMode",
1792      "_FPDFDOC_InitFormFillEnvironment",
1793      "_FPDFFont_Close",
1794      "_FPDFFont_GetAscent",
1795      "_FPDFFont_GetBaseFontName",
1796      "_FPDFFont_GetDescent",
1797      "_FPDFFont_GetFamilyName",
1798      "_FPDFFont_GetFlags",
1799      "_FPDFFont_GetFontData",
1800      "_FPDFFont_GetGlyphPath",
1801      "_FPDFFont_GetGlyphWidth",
1802      "_FPDFFont_GetIsEmbedded",
1803      "_FPDFFont_GetItalicAngle",
1804      "_FPDFFont_GetWeight",
1805      "_FPDFFormObj_CountObjects",
1806      "_FPDFFormObj_GetObject",
1807      "_FPDFFormObj_RemoveObject",
1808      "_FPDFGlyphPath_CountGlyphSegments",
1809      "_FPDFGlyphPath_GetGlyphPathSegment",
1810      "_FPDFImageObj_GetBitmap",
1811      "_FPDFImageObj_GetIccProfileDataDecoded",
1812      "_FPDFImageObj_GetImageDataDecoded",
1813      "_FPDFImageObj_GetImageDataRaw",
1814      "_FPDFImageObj_GetImageFilter",
1815      "_FPDFImageObj_GetImageFilterCount",
1816      "_FPDFImageObj_GetImageMetadata",
1817      "_FPDFImageObj_GetImagePixelSize",
1818      "_FPDFImageObj_GetRenderedBitmap",
1819      "_FPDFImageObj_LoadJpegFile",
1820      "_FPDFImageObj_LoadJpegFileInline",
1821      "_FPDFImageObj_SetBitmap",
1822      "_FPDFImageObj_SetMatrix",
1823      "_FPDFJavaScriptAction_GetName",
1824      "_FPDFJavaScriptAction_GetScript",
1825      "_FPDFLink_CloseWebLinks",
1826      "_FPDFLink_CountQuadPoints",
1827      "_FPDFLink_CountRects",
1828      "_FPDFLink_CountWebLinks",
1829      "_FPDFLink_Enumerate",
1830      "_FPDFLink_GetAction",
1831      "_FPDFLink_GetAnnot",
1832      "_FPDFLink_GetAnnotRect",
1833      "_FPDFLink_GetDest",
1834      "_FPDFLink_GetLinkAtPoint",
1835      "_FPDFLink_GetLinkZOrderAtPoint",
1836      "_FPDFLink_GetQuadPoints",
1837      "_FPDFLink_GetRect",
1838      "_FPDFLink_GetTextRange",
1839      "_FPDFLink_GetURL",
1840      "_FPDFLink_LoadWebLinks",
1841      "_FPDFPage_CloseAnnot",
1842      "_FPDFPage_CountObjects",
1843      "_FPDFPage_CreateAnnot",
1844      "_FPDFPage_Delete",
1845      "_FPDFPage_Flatten",
1846      "_FPDFPage_FormFieldZOrderAtPoint",
1847      "_FPDFPage_GenerateContent",
1848      "_FPDFPage_GetAnnot",
1849      "_FPDFPage_GetAnnotCount",
1850      "_FPDFPage_GetAnnotIndex",
1851      "_FPDFPage_GetArtBox",
1852      "_FPDFPage_GetBleedBox",
1853      "_FPDFPage_GetCropBox",
1854      "_FPDFPage_GetDecodedThumbnailData",
1855      "_FPDFPage_GetMediaBox",
1856      "_FPDFPage_GetObject",
1857      "_FPDFPage_GetRawThumbnailData",
1858      "_FPDFPage_GetRotation",
1859      "_FPDFPage_GetThumbnailAsBitmap",
1860      "_FPDFPage_GetTrimBox",
1861      "_FPDFPage_HasFormFieldAtPoint",
1862      "_FPDFPage_HasTransparency",
1863      "_FPDFPage_InsertClipPath",
1864      "_FPDFPage_InsertObject",
1865      "_FPDFPage_InsertObjectAtIndex",
1866      "_FPDFPage_New",
1867      "_FPDFPage_RemoveAnnot",
1868      "_FPDFPage_RemoveObject",
1869      "_FPDFPage_SetArtBox",
1870      "_FPDFPage_SetBleedBox",
1871      "_FPDFPage_SetCropBox",
1872      "_FPDFPage_SetMediaBox",
1873      "_FPDFPage_SetRotation",
1874      "_FPDFPage_SetTrimBox",
1875      "_FPDFPage_TransformAnnots",
1876      "_FPDFPage_TransFormWithClip",
1877      "_FPDFPageObj_AddMark",
1878      "_FPDFPageObj_CountMarks",
1879      "_FPDFPageObj_CreateNewPath",
1880      "_FPDFPageObj_CreateNewRect",
1881      "_FPDFPageObj_CreateTextObj",
1882      "_FPDFPageObj_Destroy",
1883      "_FPDFPageObj_GetBounds",
1884      "_FPDFPageObj_GetClipPath",
1885      "_FPDFPageObj_GetDashArray",
1886      "_FPDFPageObj_GetDashCount",
1887      "_FPDFPageObj_GetDashPhase",
1888      "_FPDFPageObj_GetFillColor",
1889      "_FPDFPageObj_GetIsActive",
1890      "_FPDFPageObj_GetLineCap",
1891      "_FPDFPageObj_GetLineJoin",
1892      "_FPDFPageObj_GetMark",
1893      "_FPDFPageObj_GetMarkedContentID",
1894      "_FPDFPageObj_GetMatrix",
1895      "_FPDFPageObj_GetRotatedBounds",
1896      "_FPDFPageObj_GetStrokeColor",
1897      "_FPDFPageObj_GetStrokeWidth",
1898      "_FPDFPageObj_GetType",
1899      "_FPDFPageObj_HasTransparency",
1900      "_FPDFPageObj_NewImageObj",
1901      "_FPDFPageObj_NewTextObj",
1902      "_FPDFPageObj_RemoveMark",
1903      "_FPDFPageObj_SetBlendMode",
1904      "_FPDFPageObj_SetDashArray",
1905      "_FPDFPageObj_SetDashPhase",
1906      "_FPDFPageObj_SetFillColor",
1907      "_FPDFPageObj_SetIsActive",
1908      "_FPDFPageObj_SetLineCap",
1909      "_FPDFPageObj_SetLineJoin",
1910      "_FPDFPageObj_SetMatrix",
1911      "_FPDFPageObj_SetStrokeColor",
1912      "_FPDFPageObj_SetStrokeWidth",
1913      "_FPDFPageObj_Transform",
1914      "_FPDFPageObj_TransformClipPath",
1915      "_FPDFPageObj_TransformF",
1916      "_FPDFPageObjMark_CountParams",
1917      "_FPDFPageObjMark_GetName",
1918      "_FPDFPageObjMark_GetParamBlobValue",
1919      "_FPDFPageObjMark_GetParamFloatValue",
1920      "_FPDFPageObjMark_GetParamIntValue",
1921      "_FPDFPageObjMark_GetParamKey",
1922      "_FPDFPageObjMark_GetParamStringValue",
1923      "_FPDFPageObjMark_GetParamValueType",
1924      "_FPDFPageObjMark_RemoveParam",
1925      "_FPDFPageObjMark_SetBlobParam",
1926      "_FPDFPageObjMark_SetFloatParam",
1927      "_FPDFPageObjMark_SetIntParam",
1928      "_FPDFPageObjMark_SetStringParam",
1929      "_FPDFPath_BezierTo",
1930      "_FPDFPath_Close",
1931      "_FPDFPath_CountSegments",
1932      "_FPDFPath_GetDrawMode",
1933      "_FPDFPath_GetPathSegment",
1934      "_FPDFPath_LineTo",
1935      "_FPDFPath_MoveTo",
1936      "_FPDFPath_SetDrawMode",
1937      "_FPDFPathSegment_GetClose",
1938      "_FPDFPathSegment_GetPoint",
1939      "_FPDFPathSegment_GetType",
1940      "_FPDFSignatureObj_GetByteRange",
1941      "_FPDFSignatureObj_GetContents",
1942      "_FPDFSignatureObj_GetDocMDPPermission",
1943      "_FPDFSignatureObj_GetReason",
1944      "_FPDFSignatureObj_GetSubFilter",
1945      "_FPDFSignatureObj_GetTime",
1946      "_FPDFText_ClosePage",
1947      "_FPDFText_CountChars",
1948      "_FPDFText_CountRects",
1949      "_FPDFText_FindClose",
1950      "_FPDFText_FindNext",
1951      "_FPDFText_FindPrev",
1952      "_FPDFText_FindStart",
1953      "_FPDFText_GetBoundedText",
1954      "_FPDFText_GetCharAngle",
1955      "_FPDFText_GetCharBox",
1956      "_FPDFText_GetCharIndexAtPos",
1957      "_FPDFText_GetCharIndexFromTextIndex",
1958      "_FPDFText_GetCharOrigin",
1959      "_FPDFText_GetFillColor",
1960      "_FPDFText_GetFontInfo",
1961      "_FPDFText_GetFontSize",
1962      "_FPDFText_GetFontWeight",
1963      "_FPDFText_GetLooseCharBox",
1964      "_FPDFText_GetMatrix",
1965      "_FPDFText_GetRect",
1966      "_FPDFText_GetSchCount",
1967      "_FPDFText_GetSchResultIndex",
1968      "_FPDFText_GetStrokeColor",
1969      "_FPDFText_GetText",
1970      "_FPDFText_GetTextIndexFromCharIndex",
1971      "_FPDFText_GetTextObject",
1972      "_FPDFText_GetUnicode",
1973      "_FPDFText_HasUnicodeMapError",
1974      "_FPDFText_IsGenerated",
1975      "_FPDFText_IsHyphen",
1976      "_FPDFText_LoadCidType2Font",
1977      "_FPDFText_LoadFont",
1978      "_FPDFText_LoadPage",
1979      "_FPDFText_LoadStandardFont",
1980      "_FPDFText_SetCharcodes",
1981      "_FPDFText_SetText",
1982      "_FPDFTextObj_GetFont",
1983      "_FPDFTextObj_GetFontSize",
1984      "_FPDFTextObj_GetRenderedBitmap",
1985      "_FPDFTextObj_GetText",
1986      "_FPDFTextObj_GetTextRenderMode",
1987      "_FPDFTextObj_SetTextRenderMode",
1988      "_PDFiumExt_CloseFileWriter",
1989      "_PDFiumExt_CloseFormFillInfo",
1990      "_PDFiumExt_ExitFormFillEnvironment",
1991      "_PDFiumExt_GetFileWriterData",
1992      "_PDFiumExt_GetFileWriterSize",
1993      "_PDFiumExt_Init",
1994      "_PDFiumExt_InitFormFillEnvironment",
1995      "_PDFiumExt_OpenFileWriter",
1996      "_PDFiumExt_OpenFormFillInfo",
1997      "_PDFiumExt_SaveAsCopy",
1998      "_malloc",
1999      "_free",
2000      "_memory",
2001      "___indirect_function_table",
2002      "onRuntimeInitialized"
2003    ].forEach((prop) => {
2004      if (!Object.getOwnPropertyDescriptor(readyPromise, prop)) {
2005        Object.defineProperty(readyPromise, prop, {
2006          get: () => abort(
2007            "You are getting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"
2008          ),
2009          set: () => abort(
2010            "You are setting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"
2011          )
2012        });
2013      }
2014    });
2015    var ENVIRONMENT_IS_WEB = typeof window == "object";
2016    var ENVIRONMENT_IS_WORKER = typeof importScripts == "function";
2017    typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string" && process.type != "renderer";
2018    var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && true && !ENVIRONMENT_IS_WORKER;
2019    var moduleOverrides = Object.assign({}, Module);
2020    var thisProgram = "./this.program";
2021    var scriptDirectory = "";
2022    function locateFile(path) {
2023      if (Module["locateFile"]) {
2024        return Module["locateFile"](path, scriptDirectory);
2025      }
2026      return scriptDirectory + path;
2027    }
2028    var readAsync, readBinary;
2029    if (ENVIRONMENT_IS_SHELL) {
2030      if (typeof window == "object" || typeof importScripts == "function")
2031        throw new Error(
2032          "not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"
2033        );
2034      readBinary = (f) => {
2035        if (typeof readbuffer == "function") {
2036          return new Uint8Array(readbuffer(f));
2037        }
2038        let data = read(f, "binary");
2039        assert(typeof data == "object");
2040        return data;
2041      };
2042      readAsync = (f) => {
2043        return new Promise((resolve, reject) => {
2044          setTimeout(() => resolve(readBinary(f)));
2045        });
2046      };
2047      globalThis.clearTimeout ?? (globalThis.clearTimeout = (id) => {
2048      });
2049      globalThis.setTimeout ?? (globalThis.setTimeout = (f) => typeof f == "function" ? f() : abort());
2050      if (typeof print != "undefined") {
2051        globalThis.console ?? (globalThis.console = /** @type{!Console} */
2052        {});
2053        console.log = /** @type{!function(this:Console, ...*): undefined} */
2054        print;
2055        console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */
2056        globalThis.printErr ?? print;
2057      }
2058    } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
2059      if (ENVIRONMENT_IS_WORKER) {
2060        scriptDirectory = self.location.href;
2061      } else if (typeof document != "undefined" && document.currentScript) {
2062        scriptDirectory = document.currentScript.src;
2063      }
2064      if (_scriptName) {
2065        scriptDirectory = _scriptName;
2066      }
2067      if (scriptDirectory.startsWith("blob:")) {
2068        scriptDirectory = "";
2069      } else {
2070        scriptDirectory = scriptDirectory.substr(
2071          0,
2072          scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1
2073        );
2074      }
2075      if (!(typeof window == "object" || typeof importScripts == "function"))
2076        throw new Error(
2077          "not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"
2078        );
2079      {
2080        if (ENVIRONMENT_IS_WORKER) {
2081          readBinary = (url) => {
2082            var xhr = new XMLHttpRequest();
2083            xhr.open("GET", url, false);
2084            xhr.responseType = "arraybuffer";
2085            xhr.send(null);
2086            return new Uint8Array(
2087              /** @type{!ArrayBuffer} */
2088              xhr.response
2089            );
2090          };
2091        }
2092        readAsync = (url) => {
2093          assert(!isFileURI(url), "readAsync does not work with file:// URLs");
2094          return fetch(url, { credentials: "same-origin" }).then((response) => {
2095            if (response.ok) {
2096              return response.arrayBuffer();
2097            }
2098            return Promise.reject(new Error(response.status + " : " + response.url));
2099          });
2100        };
2101      }
2102    } else {
2103      throw new Error("environment detection error");
2104    }
2105    var out = Module["print"] || console.log.bind(console);
2106    var err = Module["printErr"] || console.error.bind(console);
2107    Object.assign(Module, moduleOverrides);
2108    moduleOverrides = null;
2109    checkIncomingModuleAPI();
2110    if (Module["arguments"]) Module["arguments"];
2111    legacyModuleProp("arguments", "arguments_");
2112    if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
2113    legacyModuleProp("thisProgram", "thisProgram");
2114    assert(
2115      typeof Module["memoryInitializerPrefixURL"] == "undefined",
2116      "Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"
2117    );
2118    assert(
2119      typeof Module["pthreadMainPrefixURL"] == "undefined",
2120      "Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"
2121    );
2122    assert(
2123      typeof Module["cdInitializerPrefixURL"] == "undefined",
2124      "Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"
2125    );
2126    assert(
2127      typeof Module["filePackagePrefixURL"] == "undefined",
2128      "Module.filePackagePrefixURL option was removed, use Module.locateFile instead"
2129    );
2130    assert(typeof Module["read"] == "undefined", "Module.read option was removed");
2131    assert(
2132      typeof Module["readAsync"] == "undefined",
2133      "Module.readAsync option was removed (modify readAsync in JS)"
2134    );
2135    assert(
2136      typeof Module["readBinary"] == "undefined",
2137      "Module.readBinary option was removed (modify readBinary in JS)"
2138    );
2139    assert(
2140      typeof Module["setWindowTitle"] == "undefined",
2141      "Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"
2142    );
2143    assert(
2144      typeof Module["TOTAL_MEMORY"] == "undefined",
2145      "Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"
2146    );
2147    legacyModuleProp("asm", "wasmExports");
2148    legacyModuleProp("readAsync", "readAsync");
2149    legacyModuleProp("readBinary", "readBinary");
2150    legacyModuleProp("setWindowTitle", "setWindowTitle");
2151    var wasmBinary = Module["wasmBinary"];
2152    legacyModuleProp("wasmBinary", "wasmBinary");
2153    if (typeof WebAssembly != "object") {
2154      err("no native wasm support detected");
2155    }
2156    var wasmMemory;
2157    var ABORT = false;
2158    function assert(condition, text) {
2159      if (!condition) {
2160        abort("Assertion failed" + (text ? ": " + text : ""));
2161      }
2162    }
2163    var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
2164    function updateMemoryViews() {
2165      var b = wasmMemory.buffer;
2166      Module["HEAP8"] = HEAP8 = new Int8Array(b);
2167      Module["HEAP16"] = HEAP16 = new Int16Array(b);
2168      Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);
2169      Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);
2170      Module["HEAP32"] = HEAP32 = new Int32Array(b);
2171      Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);
2172      Module["HEAPF32"] = HEAPF32 = new Float32Array(b);
2173      Module["HEAPF64"] = HEAPF64 = new Float64Array(b);
2174    }
2175    assert(
2176      !Module["STACK_SIZE"],
2177      "STACK_SIZE can no longer be set at runtime.  Use -sSTACK_SIZE at link time"
2178    );
2179    assert(
2180      typeof Int32Array != "undefined" && typeof Float64Array !== "undefined" && Int32Array.prototype.subarray != void 0 && Int32Array.prototype.set != void 0,
2181      "JS engine does not provide full typed array support"
2182    );
2183    assert(
2184      !Module["wasmMemory"],
2185      "Use of \`wasmMemory\` detected.  Use -sIMPORTED_MEMORY to define wasmMemory externally"
2186    );
2187    assert(
2188      !Module["INITIAL_MEMORY"],
2189      "Detected runtime INITIAL_MEMORY setting.  Use -sIMPORTED_MEMORY to define wasmMemory dynamically"
2190    );
2191    function writeStackCookie() {
2192      var max = _emscripten_stack_get_end();
2193      assert((max & 3) == 0);
2194      if (max == 0) {
2195        max += 4;
2196      }
2197      HEAPU32[max >> 2] = 34821223;
2198      HEAPU32[max + 4 >> 2] = 2310721022;
2199      HEAPU32[0 >> 2] = 1668509029;
2200    }
2201    function checkStackCookie() {
2202      if (ABORT) return;
2203      var max = _emscripten_stack_get_end();
2204      if (max == 0) {
2205        max += 4;
2206      }
2207      var cookie1 = HEAPU32[max >> 2];
2208      var cookie2 = HEAPU32[max + 4 >> 2];
2209      if (cookie1 != 34821223 || cookie2 != 2310721022) {
2210        abort(
2211          \`Stack overflow! Stack cookie has been overwritten at \${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received \${ptrToString(cookie2)} \${ptrToString(cookie1)}\`
2212        );
2213      }
2214      if (HEAPU32[0 >> 2] != 1668509029) {
2215        abort("Runtime error: The application has corrupted its heap memory area (address zero)!");
2216      }
2217    }
2218    var __ATPRERUN__ = [];
2219    var __ATINIT__ = [];
2220    var __ATPOSTRUN__ = [];
2221    var runtimeInitialized = false;
vendor: 8,020 bytes, lines 2222-2445
2222    function preRun() {
2223      var preRuns = Module["preRun"];
2224      if (preRuns) {
2225        if (typeof preRuns == "function") preRuns = [preRuns];
2226        preRuns.forEach(addOnPreRun);
2227      }
2228      callRuntimeCallbacks(__ATPRERUN__);
2229    }
2230    function initRuntime() {
2231      assert(!runtimeInitialized);
2232      runtimeInitialized = true;
2233      checkStackCookie();
2234      if (!Module["noFSInit"] && !FS.initialized) FS.init();
2235      FS.ignorePermissions = false;
2236      callRuntimeCallbacks(__ATINIT__);
2237    }
2238    function postRun() {
2239      checkStackCookie();
2240      var postRuns = Module["postRun"];
2241      if (postRuns) {
2242        if (typeof postRuns == "function") postRuns = [postRuns];
2243        postRuns.forEach(addOnPostRun);
2244      }
2245      callRuntimeCallbacks(__ATPOSTRUN__);
2246    }
2247    function addOnPreRun(cb) {
2248      __ATPRERUN__.unshift(cb);
2249    }
2250    function addOnInit(cb) {
2251      __ATINIT__.unshift(cb);
2252    }
2253    function addOnPostRun(cb) {
2254      __ATPOSTRUN__.unshift(cb);
2255    }
2256    assert(
2257      Math.imul,
2258      "This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"
2259    );
2260    assert(
2261      Math.fround,
2262      "This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"
2263    );
2264    assert(
2265      Math.clz32,
2266      "This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"
2267    );
2268    assert(
2269      Math.trunc,
2270      "This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"
2271    );
2272    var runDependencies = 0;
2273    var runDependencyWatcher = null;
2274    var dependenciesFulfilled = null;
2275    var runDependencyTracking = {};
2276    function getUniqueRunDependency(id) {
2277      var orig = id;
2278      while (1) {
2279        if (!runDependencyTracking[id]) return id;
2280        id = orig + Math.random();
2281      }
2282    }
2283    function addRunDependency(id) {
2284      var _a;
2285      runDependencies++;
2286      (_a = Module["monitorRunDependencies"]) == null ? void 0 : _a.call(Module, runDependencies);
2287      if (id) {
2288        assert(!runDependencyTracking[id]);
2289        runDependencyTracking[id] = 1;
2290        if (runDependencyWatcher === null && typeof setInterval != "undefined") {
2291          runDependencyWatcher = setInterval(() => {
2292            if (ABORT) {
2293              clearInterval(runDependencyWatcher);
2294              runDependencyWatcher = null;
2295              return;
2296            }
2297            var shown = false;
2298            for (var dep in runDependencyTracking) {
2299              if (!shown) {
2300                shown = true;
2301                err("still waiting on run dependencies:");
2302              }
2303              err(\`dependency: \${dep}\`);
2304            }
2305            if (shown) {
2306              err("(end of list)");
2307            }
2308          }, 1e4);
2309        }
2310      } else {
2311        err("warning: run dependency added without ID");
2312      }
2313    }
2314    function removeRunDependency(id) {
2315      var _a;
2316      runDependencies--;
2317      (_a = Module["monitorRunDependencies"]) == null ? void 0 : _a.call(Module, runDependencies);
2318      if (id) {
2319        assert(runDependencyTracking[id]);
2320        delete runDependencyTracking[id];
2321      } else {
2322        err("warning: run dependency removed without ID");
2323      }
2324      if (runDependencies == 0) {
2325        if (runDependencyWatcher !== null) {
2326          clearInterval(runDependencyWatcher);
2327          runDependencyWatcher = null;
2328        }
2329        if (dependenciesFulfilled) {
2330          var callback = dependenciesFulfilled;
2331          dependenciesFulfilled = null;
2332          callback();
2333        }
2334      }
2335    }
2336    function abort(what) {
2337      var _a;
2338      (_a = Module["onAbort"]) == null ? void 0 : _a.call(Module, what);
2339      what = "Aborted(" + what + ")";
2340      err(what);
2341      ABORT = true;
2342      var e = new WebAssembly.RuntimeError(what);
2343      readyPromiseReject(e);
2344      throw e;
2345    }
2346    var dataURIPrefix = "data:application/octet-stream;base64,";
2347    var isDataURI = (filename) => filename.startsWith(dataURIPrefix);
2348    var isFileURI = (filename) => filename.startsWith("file://");
2349    function createExportWrapper(name, nargs) {
2350      return (...args) => {
2351        assert(
2352          runtimeInitialized,
2353          \`native function \\\`\${name}\\\` called before runtime initialization\`
2354        );
2355        var f = wasmExports[name];
2356        assert(f, \`exported native function \\\`\${name}\\\` not found\`);
2357        assert(
2358          args.length <= nargs,
2359          \`native function \\\`\${name}\\\` called with \${args.length} args but expects \${nargs}\`
2360        );
2361        return f(...args);
2362      };
2363    }
2364    function findWasmBinary() {
2365      if (Module["locateFile"]) {
2366        var f = "pdfium.wasm";
2367        if (!isDataURI(f)) {
2368          return locateFile(f);
2369        }
2370        return f;
2371      }
2372      if (ENVIRONMENT_IS_SHELL) return "pdfium.wasm";
2373      return "pdfium.wasm";
2374    }
2375    var wasmBinaryFile;
2376    function getBinarySync(file) {
2377      if (file == wasmBinaryFile && wasmBinary) {
2378        return new Uint8Array(wasmBinary);
2379      }
2380      if (readBinary) {
2381        return readBinary(file);
2382      }
2383      throw "both async and sync fetching of the wasm failed";
2384    }
2385    function getBinaryPromise(binaryFile) {
2386      if (!wasmBinary) {
2387        return readAsync(binaryFile).then(
2388          (response) => new Uint8Array(
2389            /** @type{!ArrayBuffer} */
2390            response
2391          ),
2392          // Fall back to getBinarySync if readAsync fails
2393          () => getBinarySync(binaryFile)
2394        );
2395      }
2396      return Promise.resolve().then(() => getBinarySync(binaryFile));
2397    }
2398    function instantiateArrayBuffer(binaryFile, imports, receiver) {
2399      return getBinaryPromise(binaryFile).then((binary) => {
2400        return WebAssembly.instantiate(binary, imports);
2401      }).then(receiver, (reason) => {
2402        err(\`failed to asynchronously prepare wasm: \${reason}\`);
2403        if (isFileURI(wasmBinaryFile)) {
2404          err(
2405            \`warning: Loading from a file URI (\${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing\`
2406          );
2407        }
2408        abort(reason);
2409      });
2410    }
2411    function instantiateAsync(binary, binaryFile, imports, callback) {
2412      if (!binary && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && // Avoid instantiateStreaming() on Node.js environment for now, as while
2413      // Node.js v18.1.0 implements it, it does not have a full fetch()
2414      // implementation yet.
2415      //
2416      // Reference:
2417      //   https://github.com/emscripten-core/emscripten/pull/16917
2418      true && typeof fetch == "function") {
2419        return fetch(binaryFile, { credentials: "same-origin" }).then((response) => {
2420          var result = WebAssembly.instantiateStreaming(response, imports);
2421          return result.then(callback, function(reason) {
2422            err(\`wasm streaming compile failed: \${reason}\`);
2423            err("falling back to ArrayBuffer instantiation");
2424            return instantiateArrayBuffer(binaryFile, imports, callback);
2425          });
2426        });
2427      }
2428      return instantiateArrayBuffer(binaryFile, imports, callback);
2429    }
2430    function getWasmImports() {
2431      return {
2432        env: wasmImports,
2433        wasi_snapshot_preview1: wasmImports
2434      };
2435    }
2436    function createWasm() {
2437      var info = getWasmImports();
2438      function receiveInstance(instance, module) {
2439        wasmExports = instance.exports;
2440        Module["wasmExports"] = wasmExports;
2441        wasmMemory = wasmExports["memory"];
2442        assert(wasmMemory, "memory not found in wasm exports");
2443        updateMemoryViews();
2444        wasmTable = wasmExports["__indirect_function_table"];
2445        assert(wasmTable, "table not found in wasm exports");
2446        addOnInit(wasmExports["__wasm_call_ctors"]);
2447        removeRunDependency("wasm-instantiate");
2448        return wasmExports;
2449      }
2450      addRunDependency("wasm-instantiate");
2451      var trueModule = Module;
2452      function receiveInstantiationResult(result) {
2453        assert(
2454          Module === trueModule,
2455          "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"
2456        );
2457        trueModule = null;
2458        receiveInstance(result["instance"]);
2459      }
2460      if (Module["instantiateWasm"]) {
2461        try {
2462          return Module["instantiateWasm"](info, receiveInstance);
2463        } catch (e) {
2464          err(\`Module.instantiateWasm callback failed with error: \${e}\`);
2465          readyPromiseReject(e);
2466        }
2467      }
2468      wasmBinaryFile ?? (wasmBinaryFile = findWasmBinary());
2469      instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult).catch(
2470        readyPromiseReject
2471      );
2472      return {};
2473    }
2474    var tempDouble;
2475    var tempI64;
2476    (() => {
2477      var h16 = new Int16Array(1);
2478      var h8 = new Int8Array(h16.buffer);
2479      h16[0] = 25459;
2480      if (h8[0] !== 115 || h8[1] !== 99)
2481        throw "Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)";
2482    })();
2483    if (Module["ENVIRONMENT"]) {
2484      throw new Error(
2485        "Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)"
2486      );
2487    }
2488    function legacyModuleProp(prop, newName, incoming = true) {
2489      if (!Object.getOwnPropertyDescriptor(Module, prop)) {
2490        Object.defineProperty(Module, prop, {
2491          configurable: true,
2492          get() {
2493            let extra = incoming ? " (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)" : "";
2494            abort(\`\\\`Module.\${prop}\\\` has been replaced by \\\`\${newName}\\\`\` + extra);
2495          }
2496        });
2497      }
2498    }
2499    function ignoredModuleProp(prop) {
2500      if (Object.getOwnPropertyDescriptor(Module, prop)) {
2501        abort(
2502          \`\\\`Module.\${prop}\\\` was supplied but \\\`\${prop}\\\` not included in INCOMING_MODULE_JS_API\`
2503        );
2504      }
2505    }
2506    function isExportedByForceFilesystem(name) {
2507      return name === "FS_createPath" || name === "FS_createDataFile" || name === "FS_createPreloadedFile" || name === "FS_unlink" || name === "addRunDependency" || // The old FS has some functionality that WasmFS lacks.
2508      name === "FS_createLazyFile" || name === "FS_createDevice" || name === "removeRunDependency";
2509    }
2510    function hookGlobalSymbolAccess(sym, func) {
2511      if (typeof globalThis != "undefined" && !Object.getOwnPropertyDescriptor(globalThis, sym)) {
2512        Object.defineProperty(globalThis, sym, {
2513          configurable: true,
2514          get() {
2515            func();
2516            return void 0;
2517          }
2518        });
2519      }
2520    }
2521    function missingGlobal(sym, msg) {
2522      hookGlobalSymbolAccess(sym, () => {
2523        warnOnce(\`\\\`\${sym}\\\` is not longer defined by emscripten. \${msg}\`);
2524      });
2525    }
2526    missingGlobal("buffer", "Please use HEAP8.buffer or wasmMemory.buffer");
2527    missingGlobal("asm", "Please use wasmExports instead");
2528    function missingLibrarySymbol(sym) {
2529      hookGlobalSymbolAccess(sym, () => {
2530        var msg = \`\\\`\${sym}\\\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line\`;
2531        var librarySymbol = sym;
2532        if (!librarySymbol.startsWith("_")) {
2533          librarySymbol = "$" + sym;
2534        }
2535        msg += \` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='\${librarySymbol}')\`;
2536        if (isExportedByForceFilesystem(sym)) {
2537          msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";
2538        }
2539        warnOnce(msg);
2540      });
2541      unexportedRuntimeSymbol(sym);
2542    }
2543    function unexportedRuntimeSymbol(sym) {
2544      if (!Object.getOwnPropertyDescriptor(Module, sym)) {
2545        Object.defineProperty(Module, sym, {
2546          configurable: true,
2547          get() {
2548            var msg = \`'\${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)\`;
2549            if (isExportedByForceFilesystem(sym)) {
2550              msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";
2551            }
2552            abort(msg);
2553          }
2554        });
2555      }
2556    }
2557    var callRuntimeCallbacks = (callbacks) => {
2558      callbacks.forEach((f) => f(Module));
2559    };
2560    function getValue(ptr, type = "i8") {
2561      if (type.endsWith("*")) type = "*";
2562      switch (type) {
2563        case "i1":
2564          return HEAP8[ptr];
2565        case "i8":
2566          return HEAP8[ptr];
2567        case "i16":
2568          return HEAP16[ptr >> 1];
2569        case "i32":
2570          return HEAP32[ptr >> 2];
2571        case "i64":
2572          abort("to do getValue(i64) use WASM_BIGINT");
2573        case "float":
2574          return HEAPF32[ptr >> 2];
2575        case "double":
2576          return HEAPF64[ptr >> 3];
2577        case "*":
2578          return HEAPU32[ptr >> 2];
2579        default:
2580          abort(\`invalid type for getValue: \${type}\`);
2581      }
2582    }
2583    Module["noExitRuntime"] || true;
2584    var ptrToString = (ptr) => {
2585      assert(typeof ptr === "number");
2586      ptr >>>= 0;
2587      return "0x" + ptr.toString(16).padStart(8, "0");
2588    };
2589    function setValue(ptr, value, type = "i8") {
2590      if (type.endsWith("*")) type = "*";
2591      switch (type) {
2592        case "i1":
2593          HEAP8[ptr] = value;
2594          break;
2595        case "i8":
2596          HEAP8[ptr] = value;
2597          break;
2598        case "i16":
2599          HEAP16[ptr >> 1] = value;
2600          break;
2601        case "i32":
2602          HEAP32[ptr >> 2] = value;
2603          break;
2604        case "i64":
2605          abort("to do setValue(i64) use WASM_BIGINT");
2606        case "float":
2607          HEAPF32[ptr >> 2] = value;
2608          break;
2609        case "double":
2610          HEAPF64[ptr >> 3] = value;
2611          break;
2612        case "*":
2613          HEAPU32[ptr >> 2] = value;
2614          break;
2615        default:
2616          abort(\`invalid type for setValue: \${type}\`);
2617      }
2618    }
2619    var stackRestore = (val) => __emscripten_stack_restore(val);
2620    var stackSave = () => _emscripten_stack_get_current();
2621    var warnOnce = (text) => {
2622      warnOnce.shown || (warnOnce.shown = {});
2623      if (!warnOnce.shown[text]) {
2624        warnOnce.shown[text] = 1;
2625        err(text);
2626      }
2627    };
2628    var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;
2629    var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => {
2630      var endIdx = idx + maxBytesToRead;
2631      var endPtr = idx;
2632      while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
2633      if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
2634        return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
2635      }
2636      var str = "";
2637      while (idx < endPtr) {
2638        var u0 = heapOrArray[idx++];
2639        if (!(u0 & 128)) {
2640          str += String.fromCharCode(u0);
2641          continue;
2642        }
2643        var u1 = heapOrArray[idx++] & 63;
2644        if ((u0 & 224) == 192) {
2645          str += String.fromCharCode((u0 & 31) << 6 | u1);
2646          continue;
2647        }
2648        var u2 = heapOrArray[idx++] & 63;
2649        if ((u0 & 240) == 224) {
2650          u0 = (u0 & 15) << 12 | u1 << 6 | u2;
2651        } else {
2652          if ((u0 & 248) != 240)
2653            warnOnce(
2654              "Invalid UTF-8 leading byte " + ptrToString(u0) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!"
2655            );
2656          u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
2657        }
2658        if (u0 < 65536) {
2659          str += String.fromCharCode(u0);
2660        } else {
2661          var ch = u0 - 65536;
2662          str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
2663        }
2664      }
2665      return str;
2666    };
2667    var UTF8ToString = (ptr, maxBytesToRead) => {
2668      assert(typeof ptr == "number", \`UTF8ToString expects a number (got \${typeof ptr})\`);
2669      return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
2670    };
2671    var ___assert_fail = (condition, filename, line, func) => {
2672      abort(
2673        \`Assertion failed: \${UTF8ToString(condition)}, at: \` + [
2674          filename ? UTF8ToString(filename) : "unknown filename",
2675          line,
2676          func ? UTF8ToString(func) : "unknown function"
2677        ]
2678      );
2679    };
2680    function syscallGetVarargI() {
2681      assert(SYSCALLS.varargs != void 0);
2682      var ret = HEAP32[+SYSCALLS.varargs >> 2];
2683      SYSCALLS.varargs += 4;
2684      return ret;
2685    }
2686    var syscallGetVarargP = syscallGetVarargI;
2687    var PATH = {
2688      isAbs: (path) => path.charAt(0) === "/",
2689      splitPath: (filename) => {
2690        var splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;
2691        return splitPathRe.exec(filename).slice(1);
2692      },
2693      normalizeArray: (parts, allowAboveRoot) => {
2694        var up = 0;
2695        for (var i = parts.length - 1; i >= 0; i--) {
2696          var last = parts[i];
2697          if (last === ".") {
2698            parts.splice(i, 1);
2699          } else if (last === "..") {
2700            parts.splice(i, 1);
2701            up++;
2702          } else if (up) {
2703            parts.splice(i, 1);
2704            up--;
2705          }
2706        }
2707        if (allowAboveRoot) {
2708          for (; up; up--) {
2709            parts.unshift("..");
2710          }
2711        }
2712        return parts;
2713      },
2714      normalize: (path) => {
2715        var isAbsolute = PATH.isAbs(path), trailingSlash = path.substr(-1) === "/";
2716        path = PATH.normalizeArray(
2717          path.split("/").filter((p) => !!p),
2718          !isAbsolute
2719        ).join("/");
2720        if (!path && !isAbsolute) {
2721          path = ".";
2722        }
2723        if (path && trailingSlash) {
2724          path += "/";
2725        }
2726        return (isAbsolute ? "/" : "") + path;
2727      },
2728      dirname: (path) => {
2729        var result = PATH.splitPath(path), root = result[0], dir = result[1];
2730        if (!root && !dir) {
2731          return ".";
2732        }
2733        if (dir) {
2734          dir = dir.substr(0, dir.length - 1);
2735        }
2736        return root + dir;
2737      },
2738      basename: (path) => {
2739        if (path === "/") return "/";
2740        path = PATH.normalize(path);
2741        path = path.replace(/\\/$/, "");
2742        var lastSlash = path.lastIndexOf("/");
2743        if (lastSlash === -1) return path;
2744        return path.substr(lastSlash + 1);
2745      },
2746      join: (...paths) => PATH.normalize(paths.join("/")),
2747      join2: (l, r) =>
2747 PATH.normalize(l + "/" + r)
2748    };
2749    var initRandomFill = () => {
2750      if (typeof crypto == "object" && typeof crypto["getRandomValues"] == "function") {
2751        return (view) => crypto.getRandomValues(view);
2752      }
2753      abort(
2754        "no cryptographic support found for randomDevice. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: (array) => { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };"
2755      );
2756    };
2757    var randomFill = (view) => {
2758      return (randomFill = initRandomFill())(view);
2759    };
2760    var PATH_FS = {
2761      resolve: (...args) => {
2762        var resolvedPath = "", resolvedAbsolute = false;
2763        for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
2764          var path = i >= 0 ? args[i] : FS.cwd();
2765          if (typeof path != "string") {
2766            throw new TypeError("Arguments to path.resolve must be strings");
2767          } else if (!path) {
2768            return "";
2769          }
2770          resolvedPath = path + "/" + resolvedPath;
2771          resolvedAbsolute = PATH.isAbs(path);
2772        }
2773        resolvedPath = PATH.normalizeArray(
2774          resolvedPath.split("/").filter((p) => !!p),
2775          !resolvedAbsolute
2776        ).join("/");
2777        return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
2778      },
2779      relative: (from, to) => {
2780        from = PATH_FS.resolve(from).substr(1);
2781        to = PATH_FS.resolve(to).substr(1);
2782        function trim(arr) {
2783          var start = 0;
2784          for (; start < arr.length; start++) {
2785            if (arr[start] !== "") break;
2786          }
2787          var end = arr.length - 1;
2788          for (; end >= 0; end--) {
2789            if (arr[end] !== "") break;
2790          }
2791          if (start > end) return [];
2792          return arr.slice(start, end - start + 1);
2793        }
2794        var fromParts = trim(from.split("/"));
2795        var toParts = trim(to.split("/"));
2796        var length = Math.min(fromParts.length, toParts.length);
2797        var samePartsLength = length;
2798        for (var i = 0; i < length; i++) {
2799          if (fromParts[i] !== toParts[i]) {
2800            samePartsLength = i;
2801            break;
2802          }
2803        }
2804        var outputParts = [];
2805        for (var i = samePartsLength; i < fromParts.length; i++) {
2806          outputParts.push("..");
2807        }
2808        outputParts = outputParts.concat(toParts.slice(samePartsLength));
2809        return outputParts.join("/");
2810      }
2811    };
2812    var FS_stdin_getChar_buffer = [];
2813    var lengthBytesUTF8 = (str) => {
2814      var len = 0;
2815      for (var i = 0; i < str.length; ++i) {
2816        var c = str.charCodeAt(i);
2817        if (c <= 127) {
2818          len++;
2819        } else if (c <= 2047) {
2820          len += 2;
2821        } else if (c >= 55296 && c <= 57343) {
2822          len += 4;
2823          ++i;
2824        } else {
2825          len += 3;
2826        }
2827      }
2828      return len;
2829    };
2830    var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
2831      assert(typeof str === "string", \`stringToUTF8Array expects a string (got \${typeof str})\`);
2832      if (!(maxBytesToWrite > 0)) return 0;
2833      var startIdx = outIdx;
2834      var endIdx = outIdx + maxBytesToWrite - 1;
2835      for (var i = 0; i < str.length; ++i) {
2836        var u = str.charCodeAt(i);
2837        if (u >= 55296 && u <= 57343) {
2838          var u1 = str.charCodeAt(++i);
2839          u = 65536 + ((u & 1023) << 10) | u1 & 1023;
2840        }
2841        if (u <= 127) {
2842          if (outIdx >= endIdx) break;
2843          heap[outIdx++] = u;
2844        } else if (u <= 2047) {
2845          if (outIdx + 1 >= endIdx) break;
2846          heap[outIdx++] = 192 | u >> 6;
2847          heap[outIdx++] = 128 | u & 63;
2848        } else if (u <= 65535) {
2849          if (outIdx + 2 >= endIdx) break;
2850          heap[outIdx++] = 224 | u >> 12;
2851          heap[outIdx++] = 128 | u >> 6 & 63;
2852          heap[outIdx++] = 128 | u & 63;
2853        } else {
2854          if (outIdx + 3 >= endIdx) break;
2855          if (u > 1114111)
2856            warnOnce(
2857              "Invalid Unicode code point " + ptrToString(u) + " encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."
2858            );
2859          heap[outIdx++] = 240 | u >> 18;
2860          heap[outIdx++] = 128 | u >>
2860 12 & 63;
2861          heap[outIdx++] = 128 | u >> 6 & 63;
2862          heap[outIdx++] = 128 | u & 63;
2863        }
2864      }
2865      heap[outIdx] = 0;
2866      return outIdx - startIdx;
2867    };
2868    function intArrayFromString(stringy, dontAddNull, length) {
2869      var len = lengthBytesUTF8(stringy) + 1;
2870      var u8array = new Array(len);
2871      var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
2872      u8array.length = numBytesWritten;
2873      return u8array;
2874    }
2875    var FS_stdin_getChar = () => {
2876      if (!FS_stdin_getChar_buffer.length) {
2877        var result = null;
2878        if (typeof window != "undefined" && typeof window.prompt == "function") {
2879          result = window.prompt("Input: ");
2880          if (result !== null) {
2881            result += "\\n";
2882          }
2883        } else if (typeof readline == "function") {
2884          result = readline();
2885          if (result) {
2886            result += "\\n";
2887          }
2888        } else ;
2889        if (!result) {
2890          return null;
2891        }
2892        FS_stdin_getChar_buffer = intArrayFromString(result);
2893      }
2894      return FS_stdin_getChar_buffer.shift();
2895    };
2896    var TTY = {
2897      ttys: [],
2898      init() {
2899      },
2900      shutdown() {
2901      },
2902      register(dev, ops) {
2903        TTY.ttys[dev] = { input: [], output: [], ops };
2904        FS.registerDevice(dev, TTY.stream_ops);
2905      },
2906      stream_ops: {
2907        open(stream) {
2908          var tty = TTY.ttys[stream.node.rdev];
2909          if (!tty) {
2910            throw new FS.ErrnoError(43);
2911          }
2912          stream.tty = tty;
2913          stream.seekable = false;
2914        },
2915        close(stream) {
2916          stream.tty.ops.fsync(stream.tty);
2917        },
2918        fsync(stream) {
2919          stream.tty.ops.fsync(stream.tty);
2920        },
2921        read(stream, buffer, offset, length, pos) {
2922          if (!stream.tty || !stream.tty.ops.get_char) {
2923            throw new FS.ErrnoError(60);
2924          }
2925          var bytesRead = 0;
2926          for (var i = 0; i < length; i++) {
2927            var result;
2928            try {
2929              result = stream.tty.ops.get_char(stream.tty);
2930            } catch (e) {
2931              throw new FS.ErrnoError(29);
2932            }
2933            if (result === void 0 && bytesRead === 0) {
2934              throw new FS.ErrnoError(6);
2935            }
2936            if (result === null || result === void 0) break;
2937            bytesRead++;
2938            buffer[offset + i] = result;
2939          }
2940          if (bytesRead) {
2941            stream.node.timestamp = Date.now();
2942          }
2943          return bytesRead;
2944        },
2945        write(stream, buffer, offset, length, pos) {
2946          if (!stream.tty || !stream.tty.ops.put_char) {
2947            throw new FS.ErrnoError(60);
2948          }
2949          try {
2950            for (var i = 0; i < length; i++) {
2951              stream.tty.ops.put_char(stream.tty, buffer[offset + i]);
2952            }
2953          } catch (e) {
2954            throw new FS.ErrnoError(29);
2955          }
2956          if (length) {
2957            stream.node.timestamp = Date.now();
2958          }
2959          return i;
2960        }
2961      },
2962      default_tty_ops: {
2963        get_char(tty) {
2964          return FS_stdin_getChar();
2965        },
2966        put_char(tty, val) {
2967          if (val === null || val === 10) {
2968            out(UTF8ArrayToString(tty.output));
2969            tty.output = [];
2970          } else {
2971            if (val != 0) tty.output.push(val);
2972          }
2973        },
2974        fsync(tty) {
2975          if (tty.output && tty.output.length > 0) {
2976            out(UTF8ArrayToString(tty.output));
2977            tty.output = [];
2978          }
2979        },
2980        ioctl_tcgets(tty) {
2981          return {
2982            c_iflag: 25856,
2983            c_oflag: 5,
2984            c_cflag: 191,
2985            c_lflag: 35387,
2986            c_cc: [
2987              3,
2988              28,
2989              127,
2990              21,
2991              4,
2992              0,
2993              1,
2994              0,
2995              17,
2996              19,
2997              26,
2998              0,
2999              18,
3000              15,
3001              23,
3002              22,
3003              0,
3004              0,
3005              0,
3006              0,
3007              0,
3008              0,
3009              0,
3010              0,
3011              0,
3012              0,
3013              0,
3014              0,
3015              0,
3016              0,
3017              0,
3018              0
3019            ]
3020          };
3021        },
3022        ioctl_tcsets(tty, optional_actions, data) {
3023          return 0;
3024        },
3025        ioctl_tiocgwinsz(tty) {
3026          return [24, 80];
3027        }
3028      },
3029      default_tty1_ops: {
3030        put_char(tty, val) {
3031          if (val === null || val === 10) {
3032            err(UTF8ArrayToString(tty.output));
3033            tty.output = [];
3034          } else {
3035            if (val != 0) tty.output.push(val);
3036          }
3037        },
3038        fsync(tty) {
3039          if (tty.output && tty.output.length > 0) {
3040            err(UTF8ArrayToString(tty.output));
3041            tty.output = [];
3042          }
3043        }
3044      }
3045    };
3046    var zeroMemory = (address, size) => {
3047      HEAPU8.fill(0, address, address + size);
3048    };
3049    var alignMemory = (size, alignment) => {
3050      assert(alignment, "alignment argument is required");
3051      return Math.ceil(size / alignment) * alignment;
3052    };
3053    var mmapAlloc = (size) => {
3054      size = alignMemory(size, 65536);
3055      var ptr = _emscripten_builtin_memalign(65536, size);
3056      if (ptr) zeroMemory(ptr, size);
3057      return ptr;
3058    };
3059    var MEMFS = {
3060      ops_table: null,
3061      mount(mount) {
3062        return MEMFS.createNode(null, "/", 16384 | 511, 0);
3063      },
3064      createNode(parent, name, mode, dev) {
3065        if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
3066          throw new FS.ErrnoError(63);
3067        }
3068        MEMFS.ops_table || (MEMFS.ops_table = {
3069          dir: {
3070            node: {
3071              getattr: MEMFS.node_ops.getattr,
3072              setattr: MEMFS.node_ops.setattr,
3073              lookup: MEMFS.node_ops.lookup,
3074              mknod: MEMFS.node_ops.mknod,
3075              rename: MEMFS.node_ops.rename,
3076              unlink: MEMFS.node_ops.unlink,
3077              rmdir: MEMFS.node_ops.rmdir,
3078              readdir: MEMFS.node_ops.readdir,
3079              symlink: MEMFS.node_ops.symlink
3080            },
3081            stream: {
3082              llseek: MEMFS.stream_ops.llseek
3083            }
3084          },
3085          file: {
3086            node: {
3087              getattr: MEMFS.node_ops.getattr,
3088              setattr: MEMFS.node_ops.setattr
3089            },
3090            stream: {
3091              llseek: MEMFS.stream_ops.llseek,
3092              read: MEMFS.stream_ops.read,
3093              write: MEMFS.stream_ops.write,
3094              allocate: MEMFS.stream_ops.allocate,
3095              mmap: MEMFS.stream_ops.mmap,
3096              msync: MEMFS.stream_ops.msync
3097            }
3098          },
3099          link: {
3100            node: {
3101              getattr: MEMFS.node_ops.getattr,
3102              setattr: MEMFS.node_ops.setattr,
3103              readlink: MEMFS.node_ops.readlink
3104            },
3105            stream: {}
3106          },
3107          chrdev: {
3108            node: {
3109              getattr: MEMFS.node_ops.getattr,
3110              setattr: MEMFS.node_ops.setattr
3111            },
3112            stream: FS.chrdev_stream_ops
3113          }
3114        });
3115        var node = FS.createNode(parent, name, mode, dev);
3116        if (FS.isDir(node.mode)) {
3117          node.node_ops = MEMFS.ops_table.dir.node;
3118          node.stream_ops = MEMFS.ops_table.dir.stream;
3119          node.contents = {};
3120        } else if (FS.isFile(node.mode)) {
3121          node.node_ops = MEMFS.ops_table.file.node;
3122          node.stream_ops = MEMFS.ops_table.file.stream;
3123          node.usedBytes = 0;
3124          node.contents = null;
3125        } else if (FS.isLink(node.mode)) {
3126          node.node_ops = MEMFS.ops_table.link.node;
3127          node.stream_ops = MEMFS.ops_table.link.stream;
3128        } else if (FS.isChrdev(node.mode)) {
3129          node.node_ops = MEMFS.ops_table.chrdev.node;
3130          node.stream_ops = MEMFS.ops_table.chrdev.stream;
3131        }
3132        node.timestamp = Date.now();
3133        if (parent) {
3134          parent.contents[name] = node;
3135          parent.timestamp = node.timestamp;
3136        }
3137        return node;
3138      },
3139      getFileDataAsTypedArray(node) {
3140        if (!node.contents) return new Uint8Array(0);
3141        if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes);
3142        return new Uint8Array(node.contents);
3143      },
3144      expandFileStorage(node, newCapacity) {
3145        var prevCapacity = node.contents ? node.contents.length : 0;
3146        if (prevCapacity >= newCapacity) return;
3147        var CAPACITY_DOUBLING_MAX = 1024 * 1024;
3148        newCapacity = Math.max(
3149          newCapacity,
3150          prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0
3151        );
3152        if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256);
3153        var oldContents = node.contents;
3154        node.contents = new Uint8Array(newCapacity);
3155        if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0);
3156      },
3157      resizeFileStorage(node, newSize) {
3158        if (node.usedBytes == newSize) return;
3159        if (newSize == 0) {
3160          node.contents = null;
3161          node.usedBytes = 0;
3162        } else {
3163          var oldContents = node.contents;
3164          node.contents = new Uint8Array(newSize);
3165          if (oldContents) {
3166            node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));
3167          }
3168          node.usedBytes = newSize;
3169        }
3170      },
3171      node_ops: {
3172        getattr(node) {
3173          var attr = {};
3174          attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
3175          attr.ino = node.id;
3176          attr.mode = node.mode;
3177          attr.nlink = 1;
3178          attr.uid = 0;
3179          attr.gid = 0;
3180          attr.rdev = node.rdev;
3181          if (FS.isDir(node.mode)) {
3182            attr.size = 4096;
3183          } else if (FS.isFile(node.mode)) {
3184            attr.size = node.usedBytes;
3185          } else if (FS.isLink(node.mode)) {
3186            attr.size = node.link.length;
3187          } else {
3188            attr.size = 0;
3189          }
3190          attr.atime = new Date(node.timestamp);
3191          attr.mtime = new Date(node.timestamp);
3192          attr.ctime = new Date(node.timestamp);
3193          attr.blksize = 4096;
3194          attr.blocks = Math.ceil(attr.size / attr.blksize);
3195          return attr;
3196        },
3197        setattr(node, attr) {
3198          if (attr.mode !== void 0) {
3199            node.mode = attr.mode;
3200          }
3201          if (attr.timestamp !== void 0) {
3202            node.timestamp = attr.timestamp;
3203          }
3204          if (attr.size !== void 0) {
3205            MEMFS.resizeFileStorage(node, attr.size);
3206          }
3207        },
3208        lookup(parent, name) {
3209          throw FS.genericErrors[44];
3210        },
3211        mknod(parent, name, mode, dev) {
3212          return MEMFS.createNode(parent, name, mode, dev);
3213        },
3214        rename(old_node, new_dir, new_name) {
3215          if (FS.isDir(old_node.mode)) {
3216            var new_node;
3217            try {
vendor: 4,519 bytes, lines 3218-3337
3218              new_node = FS.lookupNode(new_dir, new_name);
3219            } catch (e) {
3220            }
3221            if (new_node) {
3222              for (var i in new_node.contents) {
3223                throw new FS.ErrnoError(55);
3224              }
3225            }
3226          }
3227          delete old_node.parent.contents[old_node.name];
3228          old_node.parent.timestamp = Date.now();
3229          old_node.name = new_name;
3230          new_dir.contents[new_name] = old_node;
3231          new_dir.timestamp = old_node.parent.timestamp;
3232        },
3233        unlink(parent, name) {
3234          delete parent.contents[name];
3235          parent.timestamp = Date.now();
3236        },
3237        rmdir(parent, name) {
3238          var node = FS.lookupNode(parent, name);
3239          for (var i in node.contents) {
3240            throw new FS.ErrnoError(55);
3241          }
3242          delete parent.contents[name];
3243          parent.timestamp = Date.now();
3244        },
3245        readdir(node) {
3246          var entries = [".", ".."];
3247          for (var key of Object.keys(node.contents)) {
3248            entries.push(key);
3249          }
3250          return entries;
3251        },
3252        symlink(parent, newname, oldpath) {
3253          var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);
3254          node.link = oldpath;
3255          return node;
3256        },
3257        readlink(node) {
3258          if (!FS.isLink(node.mode)) {
3259            throw new FS.ErrnoError(28);
3260          }
3261          return node.link;
3262        }
3263      },
3264      stream_ops: {
3265        read(stream, buffer, offset, length, position) {
3266          var contents = stream.node.contents;
3267          if (position >= stream.node.usedBytes) return 0;
3268          var size = Math.min(stream.node.usedBytes - position, length);
3269          assert(size >= 0);
3270          if (size > 8 && contents.subarray) {
3271            buffer.set(contents.subarray(position, position + size), offset);
3272          } else {
3273            for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
3274          }
3275          return size;
3276        },
3277        write(stream, buffer, offset, length, position, canOwn) {
3278          assert(!(buffer instanceof ArrayBuffer));
3279          if (buffer.buffer === HEAP8.buffer) {
3280            canOwn = false;
3281          }
3282          if (!length) return 0;
3283          var node = stream.node;
3284          node.timestamp = Date.now();
3285          if (buffer.subarray && (!node.contents || node.contents.subarray)) {
3286            if (canOwn) {
3287              assert(position === 0, "canOwn must imply no weird position inside the file");
3288              node.contents = buffer.subarray(offset, offset + length);
3289              node.usedBytes = length;
3290              return length;
3291            } else if (node.usedBytes === 0 && position === 0) {
3292              node.contents = buffer.slice(offset, offset + length);
3293              node.usedBytes = length;
3294              return length;
3295            } else if (position + length <= node.usedBytes) {
3296              node.contents.set(buffer.subarray(offset, offset + length), position);
3297              return length;
3298            }
3299          }
3300          MEMFS.expandFileStorage(node, position + length);
3301          if (node.contents.subarray && buffer.subarray) {
3302            node.contents.set(buffer.subarray(offset, offset + length), position);
3303          } else {
3304            for (var i = 0; i < length; i++) {
3305              node.contents[position + i] = buffer[offset + i];
3306            }
3307          }
3308          node.usedBytes = Math.max(node.usedBytes, position + length);
3309          return length;
3310        },
3311        llseek(stream, offset, whence) {
3312          var position = offset;
3313          if (whence === 1) {
3314            position += stream.position;
3315          } else if (whence === 2) {
3316            if (FS.isFile(stream.node.mode)) {
3317              position += stream.node.usedBytes;
3318            }
3319          }
3320          if (position < 0) {
3321            throw new FS.ErrnoError(28);
3322          }
3323          return position;
3324        },
3325        allocate(stream, offset, length) {
3326          MEMFS.expandFileStorage(stream.node, offset + length);
3327          stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);
3328        },
3329        mmap(stream, length, position, prot, flags) {
3330          if (!FS.isFile(stream.node.mode)) {
3331            throw new FS.ErrnoError(43);
3332          }
3333          var ptr;
3334          var allocated;
3335          var contents = stream.node.contents;
3336          if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {
3337            allocated = false;
3338            ptr = contents.byteOffset;
3339          } else {
3340            allocated = true;
3341            ptr = mmapAlloc(length);
3342            if (!ptr) {
3343              throw new FS.ErrnoError(48);
3344            }
3345            if (contents) {
3346              if (position > 0 || position + length < contents.length) {
3347                if (contents.subarray) {
3348                  contents = contents.subarray(position, position + length);
3349                } else {
3350                  contents = Array.prototype.slice.call(contents, position, position + length);
3351                }
3352              }
3353              HEAP8.set(contents, ptr);
3354            }
3355          }
3356          return { ptr, allocated };
3357        },
3358        msync(stream, buffer, offset, length, mmapFlags) {
3359          MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
3360          return 0;
3361        }
3362      }
3363    };
3364    var asyncLoad = (url, onload, onerror, noRunDep) => {
3365      var dep = getUniqueRunDependency(\`al \${url}\`);
3366      readAsync(url).then(
3367        (arrayBuffer) => {
3368          assert(arrayBuffer, \`Loading data file "\${url}" failed (no arrayBuffer).\`);
3369          onload(new Uint8Array(arrayBuffer));
3370          if (dep) removeRunDependency(dep);
3371        },
3372        (err2) => {
3373          if (onerror) {
3374            onerror();
3375          } else {
3376            throw \`Loading data file "\${url}" failed.\`;
3377          }
3378        }
3379      );
3380      if (dep) addRunDependency(dep);
3381    };
3382    var FS_createDataFile = (parent, name, fileData, canRead, canWrite, canOwn) => {
3383      FS.createDataFile(parent, name, fileData, canRead, canWrite, canOwn);
3384    };
3385    var preloadPlugins = Module["preloadPlugins"] || [];
3386    var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => {
3387      if (typeof Browser != "undefined") Browser.init();
3388      var handled = false;
3389      preloadPlugins.forEach((plugin) => {
3390        if (handled) return;
3391        if (plugin["canHandle"](fullname)) {
3392          plugin["handle"](byteArray, fullname, finish, onerror);
3393          handled = true;
3394        }
3395      });
3396      return handled;
3397    };
3398    var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
3399      var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
3400      var dep = getUniqueRunDependency(\`cp \${fullname}\`);
3401      function processData(byteArray) {
3402        function finish(byteArray2) {
3403          preFinish == null ? void 0 : preFinish();
3404          if (!dontCreateFile) {
3405            FS_createDataFile(parent, name, byteArray2, canRead, canWrite, canOwn);
3406          }
3407          onload == null ? void 0 : onload();
3408          removeRunDependency(dep);
3409        }
3410        if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => {
3411          onerror == null ? void 0 : onerror();
3412          removeRunDependency(dep);
3413        })) {
3414          return;
3415        }
3416        finish(byteArray);
3417      }
3418      addRunDependency(dep);
3419      if (typeof url == "string") {
3420        asyncLoad(url, processData, onerror);
3421      } else {
3422        processData(url);
3423      }
3424    };
3425    var FS_modeStringToFlags = (str) => {
3426      var flagModes = {
3427        r: 0,
3428        "r+": 2,
3429        w: 512 | 64 | 1,
3430        "w+": 512 | 64 | 2,
3431        a: 1024 | 64 | 1,
3432        "a+": 1024 | 64 | 2
3433      };
3434      var flags = flagModes[str];
3435      if (typeof flags == "undefined") {
3436        throw new Error(\`Unknown file open mode: \${str}\`);
3437      }
3438      return flags;
3439    };
3440    var FS_getMode = (canRead, canWrite) => {
3441      var mode = 0;
3442      if (canRead) mode |= 292 | 73;
3443      if (canWrite) mode |= 146;
3444      return mode;
3445    };
3446    var strError = (errno) => {
3447      return UTF8ToString(_strerror(errno));
3448    };
3449    var ERRNO_CODES = {
3450      EPERM: 63,
3451      ENOENT: 44,
3452      ESRCH: 71,
3453      EINTR: 27,
3454      EIO: 29,
3455      ENXIO: 60,
3456      E2BIG: 1,
3457      ENOEXEC: 45,
3458      EBADF: 8,
3459      ECHILD: 12,
3460      EAGAIN: 6,
3461      EWOULDBLOCK: 6,
3462      ENOMEM: 48,
3463      EACCES: 2,
3464      EFAULT: 21,
3465      ENOTBLK: 105,
3466      EBUSY: 10,
3467      EEXIST: 20,
3468      EXDEV: 75,
3469      ENODEV: 43,
3470      ENOTDIR: 54,
vendor: 4,549 bytes, lines 3471-3655
3471      EISDIR: 31,
3472      EINVAL: 28,
3473      ENFILE: 41,
3474      EMFILE: 33,
3475      ENOTTY: 59,
3476      ETXTBSY: 74,
3477      EFBIG: 22,
3478      ENOSPC: 51,
3479      ESPIPE: 70,
3480      EROFS: 69,
3481      EMLINK: 34,
3482      EPIPE: 64,
3483      EDOM: 18,
3484      ERANGE: 68,
3485      ENOMSG: 49,
3486      EIDRM: 24,
3487      ECHRNG: 106,
3488      EL2NSYNC: 156,
3489      EL3HLT: 107,
3490      EL3RST: 108,
3491      ELNRNG: 109,
3492      EUNATCH: 110,
3493      ENOCSI: 111,
3494      EL2HLT: 112,
3495      EDEADLK: 16,
3496      ENOLCK: 46,
3497      EBADE: 113,
3498      EBADR: 114,
3499      EXFULL: 115,
3500      ENOANO: 104,
3501      EBADRQC: 103,
3502      EBADSLT: 102,
3503      EDEADLOCK: 16,
3504      EBFONT: 101,
3505      ENOSTR: 100,
3506      ENODATA: 116,
3507      ETIME: 117,
3508      ENOSR: 118,
3509      ENONET: 119,
3510      ENOPKG: 120,
3511      EREMOTE: 121,
3512      ENOLINK: 47,
3513      EADV: 122,
3514      ESRMNT: 123,
3515      ECOMM: 124,
3516      EPROTO: 65,
3517      EMULTIHOP: 36,
3518      EDOTDOT: 125,
3519      EBADMSG: 9,
3520      ENOTUNIQ: 126,
3521      EBADFD: 127,
3522      EREMCHG: 128,
3523      ELIBACC: 129,
3524      ELIBBAD: 130,
3525      ELIBSCN: 131,
3526      ELIBMAX: 132,
3527      ELIBEXEC: 133,
3528      ENOSYS: 52,
3529      ENOTEMPTY: 55,
3530      ENAMETOOLONG: 37,
3531      ELOOP: 32,
3532      EOPNOTSUPP: 138,
3533      EPFNOSUPPORT: 139,
3534      ECONNRESET: 15,
3535      ENOBUFS: 42,
3536      EAFNOSUPPORT: 5,
3537      EPROTOTYPE: 67,
3538      ENOTSOCK: 57,
3539      ENOPROTOOPT: 50,
3540      ESHUTDOWN: 140,
3541      ECONNREFUSED: 14,
3542      EADDRINUSE: 3,
3543      ECONNABORTED: 13,
3544      ENETUNREACH: 40,
3545      ENETDOWN: 38,
3546      ETIMEDOUT: 73,
3547      EHOSTDOWN: 142,
3548      EHOSTUNREACH: 23,
3549      EINPROGRESS: 26,
3550      EALREADY: 7,
3551      EDESTADDRREQ: 17,
3552      EMSGSIZE: 35,
3553      EPROTONOSUPPORT: 66,
3554      ESOCKTNOSUPPORT: 137,
3555      EADDRNOTAVAIL: 4,
3556      ENETRESET: 39,
3557      EISCONN: 30,
3558      ENOTCONN: 53,
3559      ETOOMANYREFS: 141,
3560      EUSERS: 136,
3561      EDQUOT: 19,
3562      ESTALE: 72,
3563      ENOTSUP: 138,
3564      ENOMEDIUM: 148,
3565      EILSEQ: 25,
3566      EOVERFLOW: 61,
3567      ECANCELED: 11,
3568      ENOTRECOVERABLE: 56,
3569      EOWNERDEAD: 62,
3570      ESTRPIPE: 135
3571    };
3572    var FS = {
3573      root: null,
3574      mounts: [],
3575      devices: {},
3576      streams: [],
3577      nextInode: 1,
3578      nameTable: null,
3579      currentPath: "/",
3580      initialized: false,
3581      ignorePermissions: true,
3582      ErrnoError: class extends Error {
3583        // We set the \`name\` property to be able to identify \`FS.ErrnoError\`
3584        // - the \`name\` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.
3585        // - when using PROXYFS, an error can come from an underlying FS
3586        // as different FS objects have their own FS.ErrnoError each,
3587        // the test \`err instanceof FS.ErrnoError\` won't detect an error coming from another filesystem, causing bugs.
3588        // we'll use the reliable test \`err.name == "ErrnoError"\` instead
3589        constructor(errno) {
3590          super(runtimeInitialized ? strError(errno) : "");
3591          this.name = "ErrnoError";
3592          this.errno = errno;
3593          for (var key in ERRNO_CODES) {
3594            if (ERRNO_CODES[key] === errno) {
3595              this.code = key;
3596              break;
3597            }
3598          }
3599        }
3600      },
3601      genericErrors: {},
3602      filesystems: null,
3603      syncFSRequests: 0,
3604      readFiles: {},
3605      FSStream: class {
3606        constructor() {
3607          this.shared = {};
3608        }
3609        get object() {
3610          return this.node;
3611        }
3612        set object(val) {
3613          this.node = val;
3614        }
3615        get isRead() {
3616          return (this.flags & 2097155) !== 1;
3617        }
3618        get isWrite() {
3619          return (this.flags & 2097155) !== 0;
3620        }
3621        get isAppend() {
3622          return this.flags & 1024;
3623        }
3624        get flags() {
3625          return this.shared.flags;
3626        }
3627        set flags(val) {
3628          this.shared.flags = val;
3629        }
3630        get position() {
3631          return this.shared.position;
3632        }
3633        set position(val) {
3634          this.shared.position = val;
3635        }
3636      },
3637      FSNode: class {
3638        constructor(parent, name, mode, rdev) {
3639          if (!parent) {
3640            parent = this;
3641          }
3642          this.parent = parent;
3643          this.mount = parent.mount;
3644          this.mounted = null;
3645          this.id = FS.nextInode++;
3646          this.name = name;
3647          this.mode = mode;
3648          this.node_ops = {};
3649          this.stream_ops = {};
3650          this.rdev = rdev;
3651          this.readMode = 292 | 73;
3652          this.writeMode = 146;
3653        }
3654        get read() {
3655          return (this.mode & this.readMode) === this.readMode;
3656        }
3657        set read(val) {
3658          val ? this.mode |= this.readMode : this.mode &= ~this.readMode;
3659        }
3660        get write() {
3661          return (this.mode & this.writeMode) === this.writeMode;
3662        }
3663        set write(val) {
3664          val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;
3665        }
3666        get isFolder() {
3667          return FS.isDir(this.mode);
3668        }
3669        get isDevice() {
3670          return FS.isChrdev(this.mode);
3671        }
3672      },
3673      lookupPath(path, opts = {}) {
3674        path = PATH_FS.resolve(path);
3675        if (!path) return { path: "", node: null };
3676        var defaults = {
3677          follow_mount: true,
3678          recurse_count: 0
3679        };
3680        opts = Object.assign(defaults, opts);
3681        if (opts.recurse_count > 8) {
3682          throw new FS.ErrnoError(32);
3683        }
3684        var parts = path.split("/").filter((p) => !!p);
3685        var current = FS.root;
3686        var current_path = "/";
3687        for (var i = 0; i < parts.length; i++) {
3688          var islast = i === parts.length - 1;
3689          if (islast && opts.parent) {
3690            break;
3691          }
3692          current = FS.lookupNode(current, parts[i]);
3693          current_path = PATH.join2(current_path, parts[i]);
3694          if (FS.isMountpoint(current)) {
3695            if (!islast || islast && opts.follow_mount) {
3696              current = current.mounted.root;
3697            }
3698          }
3699          if (!islast || opts.follow) {
3700            var count = 0;
3701            while (FS.isLink(current.mode)) {
3702              var link = FS.readlink(current_path);
3703              current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
3704              var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count + 1 });
3705              current = lookup.node;
3706              if (count++ > 40) {
3707                throw new FS.ErrnoError(32);
3708              }
3709            }
3710          }
3711        }
3712        return { path: current_path, node: current };
3713      },
3714      getPath(node) {
3715        var path;
3716        while (true) {
3717          if (FS.isRoot(node)) {
3718            var mount = node.mount.mountpoint;
3719            if (!path) return mount;
3720            return mount[mount.length - 1] !== "/" ? \`\${mount}/\${path}\` : mount + path;
3721          }
3722          path = path ? \`\${node.name}/\${path}\` : node.name;
3723          node = node.parent;
3724        }
3725      },
3726      hashName(parentid, name) {
3727        var hash = 0;
3728        for (var i = 0; i < name.length; i++) {
3729          hash = (hash << 5) - hash + name.charCodeAt(i) | 0;
3730        }
3731        return (parentid + hash >>> 0) % FS.nameTable.length;
3732      },
3733      hashAddNode(node) {
3734        var hash = FS.hashName(node.parent.id, node.name);
3735        node.name_next = FS.nameTable[hash];
3736        FS.nameTable[hash] = node;
3737      },
3738      hashRemoveNode(node) {
3739        var hash = FS.hashName(node.parent.id, node.name);
3740        if (FS.nameTable[hash] === node) {
3741          FS.nameTable[hash] = node.name_next;
3742        } else {
3743          var current = FS.nameTable[hash];
3744          while (current) {
3745            if (current.name_next === node) {
3746              current.name_next = node.name_next;
3747              break;
3748            }
3749            current = current.name_next;
3750          }
3751        }
3752      },
3753      lookupNode(parent, name) {
3754        var errCode = FS.mayLookup(parent);
3755        if (errCode) {
3756          throw new FS.ErrnoError(errCode);
3757        }
3758        var hash = FS.hashName(parent.id, name);
3759        for (var node = FS.nameTable[hash]; node; node = node.name_next) {
3760          var nodeName = node.name;
3761          if (node.parent.id === parent.id && nodeName === name) {
3762            return node;
3763          }
3764        }
3765        return FS.lookup(parent, name);
3766      },
3767      createNode(parent, name, mode, rdev) {
3768        assert(typeof parent == "object");
3769        var node = new FS.FSNode(parent, name, mode, rdev);
3770        FS.hashAddNode(node);
3771        return node;
3772      },
3773      destroyNode(node) {
3774        FS.hashRemoveNode(node);
3775      },
3776      isRoot(node) {
3777        return node === node.parent;
3778      },
3779      isMountpoint(node) {
3780        return !!node.mounted;
3781      },
3782      isFile(mode) {
3783        return (mode & 61440) === 32768;
3784      },
3785      isDir(mode) {
3786        return (mode & 61440) === 16384;
3787      },
3788      isLink(mode) {
3789        return (mode & 61440) === 40960;
3790      },
3791      isChrdev(mode) {
3792        return (mode & 61440) === 8192;
3793      },
3794      isBlkdev(mode) {
3795        return (mode & 61440) === 24576;
3796      },
3797      isFIFO(mode) {
3798        return (mode & 61440) === 4096;
3799      },
3800      isSocket(mode) {
3801        return (mode & 49152) === 49152;
3802      },
3803      flagsToPermissionString(flag) {
3804        var perms = ["r", "w", "rw"][flag & 3];
3805        if (flag & 512) {
3806          perms += "w";
3807        }
3808        return perms;
3809      },
3810      nodePermissions(node, perms) {
3811        if (FS.ignorePermissions) {
3812          return 0;
3813        }
3814        if (perms.includes("r") && !(node.mode & 292)) {
3815          return 2;
3816        } else if (perms.includes("w") && !(node.mode & 146)) {
3817          return 2;
3818        } else if (perms.includes("x") && !(node.mode & 73)) {
3819          return 2;
3820        }
3821        return 0;
3822      },
3823      mayLookup(dir) {
3824        if (!FS.isDir(dir.mode)) return 54;
3825        var errCode = FS.nodePermissions(dir, "x");
3826        if (errCode) return errCode;
3827        if (!dir.node_ops.lookup) return 2;
3828        return 0;
3829      },
3830      mayCreate(dir, name) {
3831        try {
3832          var node = FS.lookupNode(dir, name);
3833          return 20;
3834        } catch (e) {
3835        }
3836        return FS.nodePermissions(dir, "wx");
3837      },
3838      mayDelete(dir, name, isdir) {
3839        var node;
3840        try {
3841          node = FS.lookupNode(dir, name);
3842        } catch (e) {
3843          return e.errno;
3844        }
3845        var errCode = FS.nodePermissions(dir, "wx");
3846        if (errCode) {
3847          return errCode;
3848        }
3849        if (isdir) {
3850          if (!FS.isDir(node.mode)) {
3851            return 54;
3852          }
3853          if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
3854            return 10;
3855          }
3856        } else {
3857          if (FS.isDir(node.mode)) {
3858            return 31;
3859          }
3860        }
3861        return 0;
3862      },
3863      mayOpen(node, flags) {
3864        if (!node) {
3865          return 44;
3866        }
3867        if (FS.isLink(node.mode)) {
3868          return 32;
3869        } else if (FS.isDir(node.mode)) {
3870          if (FS.flagsToPermissionString(flags) !== "r" || // opening for write
3871          flags & 512) {
3872            return 31;
3873          }
3874        }
3875        return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
3876      },
3877      MAX_OPEN_FDS: 4096,
3878      nextfd() {
3879        for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {
3880          if (!FS.streams[fd]) {
3881            return fd;
3882          }
3883        }
3884        throw new FS.ErrnoError(33);
3885      },
3886      getStreamChecked(fd) {
3887        var stream = FS.getStream(fd);
3888        if (!stream) {
3889          throw new FS.ErrnoError(8);
3890        }
3891        return stream;
3892      },
3893      getStream: (fd) => FS.streams[fd],
3894      createStream(stream, fd = -1) {
3895        assert(fd >= -1);
3896        stream = Object.assign(new FS.FSStream(), stream);
3897        if (fd == -1) {
3898          fd = FS.nextfd();
3899        }
3900        stream.fd = fd;
3901        FS.streams[fd] = stream;
3902        return stream;
3903      },
3904      closeStream(fd) {
3905        FS.streams[fd] = null;
3906      },
3907      dupStream(origStream, fd = -1) {
3908        var _a, _b;
3909        var stream = FS.createStream(origStream, fd);
3910        (_b = (_a = stream.stream_ops) == null ? void 0 : _a.dup) == null ? void 0 : _b.call(_a, stream);
3911        return stream;
3912      },
3913      chrdev_stream_ops: {
3914        open(stream) {
3915          var _a, _b;
3916          var device = FS.getDevice(stream.node.rdev);
3917          stream.stream_ops = device.stream_ops;
3918          (_b = (_a = stream.stream_ops).open) == null ? void 0 : _b.call(_a, stream);
3919        },
3920        llseek() {
3921          throw new FS.ErrnoError(70);
3922        }
3923      },
3924      major: (dev) => dev >> 8,
3925      minor: (dev) => dev & 255,
3926      makedev: (ma, mi) => ma << 8 | mi,
3927      registerDevice(dev, ops) {
3928        FS.devices[dev] = { stream_ops: ops };
3929      },
3930      getDevice: (dev) => FS.devices[dev],
3931      getMounts(mount) {
3932        var mounts = [];
3933        var check = [mount];
3934        while (check.length) {
3935          var m = check.pop();
3936          mounts.push(m);
3937          check.push(...m.mounts);
3938        }
3939        return mounts;
3940      },
3941      syncfs(populate, callback) {
3942        if (typeof populate == "function") {
3943          callback = populate;
3944          populate = false;
3945        }
3946        FS.syncFSRequests++;
3947        if (FS.syncFSRequests > 1) {
3948          err(
3949            \`warning: \${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work\`
3950          );
3951        }
3952        var mounts = FS.getMounts(FS.root.mount);
3953        var completed = 0;
3954        function doCallback(errCode) {
3955          assert(FS.syncFSRequests > 0);
3956          FS.syncFSRequests--;
3957          return callback(errCode);
3958        }
3959        function done(errCode) {
3960          if (errCode) {
3961            if (!done.errored) {
3962              done.errored = true;
3963              return doCallback(errCode);
3964            }
3965            return;
3966          }
3967          if (++completed >= mounts.length) {
3968            doCallback(null);
3969          }
3970        }
3971        mounts.forEach((mount) => {
3972          if (!mount.type.syncfs) {
3973            return done(null);
3974          }
3975          mount.type.syncfs(mount, populate, done);
3976        });
3977      },
3978      mount(type, opts, mountpoint) {
3979        if (typeof type == "string") {
3980          throw type;
3981        }
3982        var root = mountpoint === "/";
3983        var pseudo = !mountpoint;
3984        var node;
3985        if (root && FS.root) {
3986          throw new FS.ErrnoError(10);
3987        } else if (!root && !pseudo) {
3988          var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
3989          mountpoint = lookup.path;
3990          node = lookup.node;
3991          if (FS.isMountpoint(node)) {
3992            throw new FS.ErrnoError(10);
3993          }
3994          if (!FS.isDir(node.mode)) {
3995            throw new FS.ErrnoError(54);
3996          }
3997        }
3998        var mount = {
3999          type,
4000          opts,
4001          mountpoint,
4002          mounts: []
4003        };
4004        var mountRoot = type.mount(mount);
4005        mountRoot.mount = mount;
4006        mount.root = mountRoot;
4007        if (root) {
4008          FS.root = mountRoot;
4009        } else if (node) {
4010          node.mounted = mount;
4011          if (node.mount) {
4012            node.mount.mounts.push(mount);
4013          }
4014        }
4015        return mountRoot;
4016      },
4017      unmount(mountpoint) {
4018        var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
4019        if (!FS.isMountpoint(lookup.node)) {
4020          throw new FS.ErrnoError(28);
4021        }
4022        var node = lookup.node;
vendor: 25,470 bytes, lines 4023-4807
4023        var mount = node.mounted;
4024        var mounts = FS.getMounts(mount);
4025        Object.keys(FS.nameTable).forEach((hash) => {
4026          var current = FS.nameTable[hash];
4027          while (current) {
4028            var next = current.name_next;
4029            if (mounts.includes(current.mount)) {
4030              FS.destroyNode(current);
4031            }
4032            current = next;
4033          }
4034        });
4035        node.mounted = null;
4036        var idx = node.mount.mounts.indexOf(mount);
4037        assert(idx !== -1);
4038        node.mount.mounts.splice(idx, 1);
4039      },
4040      lookup(parent, name) {
4041        return parent.node_ops.lookup(parent, name);
4042      },
4043      mknod(path, mode, dev) {
4044        var lookup = FS.lookupPath(path, { parent: true });
4045        var parent = lookup.node;
4046        var name = PATH.basename(path);
4047        if (!name || name === "." || name === "..") {
4048          throw new FS.ErrnoError(28);
4049        }
4050        var errCode = FS.mayCreate(parent, name);
4051        if (errCode) {
4052          throw new FS.ErrnoError(errCode);
4053        }
4054        if (!parent.node_ops.mknod) {
4055          throw new FS.ErrnoError(63);
4056        }
4057        return parent.node_ops.mknod(parent, name, mode, dev);
4058      },
4059      create(path, mode) {
4060        mode = mode !== void 0 ? mode : 438;
4061        mode &= 4095;
4062        mode |= 32768;
4063        return FS.mknod(path, mode, 0);
4064      },
4065      mkdir(path, mode) {
4066        mode = mode !== void 0 ? mode : 511;
4067        mode &= 511 | 512;
4068        mode |= 16384;
4069        return FS.mknod(path, mode, 0);
4070      },
4071      mkdirTree(path, mode) {
4072        var dirs = path.split("/");
4073        var d = "";
4074        for (var i = 0; i < dirs.length; ++i) {
4075          if (!dirs[i]) continue;
4076          d += "/" + dirs[i];
4077          try {
4078            FS.mkdir(d, mode);
4079          } catch (e) {
4080            if (e.errno != 20) throw e;
4081          }
4082        }
4083      },
4084      mkdev(path, mode, dev) {
4085        if (typeof dev == "undefined") {
4086          dev = mode;
4087          mode = 438;
4088        }
4089        mode |= 8192;
4090        return FS.mknod(path, mode, dev);
4091      },
4092      symlink(oldpath, newpath) {
4093        if (!PATH_FS.resolve(oldpath)) {
4094          throw new FS.ErrnoError(44);
4095        }
4096        var lookup = FS.lookupPath(newpath, { parent: true });
4097        var parent = lookup.node;
4098        if (!parent) {
4099          throw new FS.ErrnoError(44);
4100        }
4101        var newname = PATH.basename(newpath);
4102        var errCode = FS.mayCreate(parent, newname);
4103        if (errCode) {
4104          throw new FS.ErrnoError(errCode);
4105        }
4106        if (!parent.node_ops.symlink) {
4107          throw new FS.ErrnoError(63);
4108        }
4109        return parent.node_ops.symlink(parent, newname, oldpath);
4110      },
4111      rename(old_path, new_path) {
4112        var old_dirname = PATH.dirname(old_path);
4113        var new_dirname = PATH.dirname(new_path);
4114        var old_name = PATH.basename(old_path);
4115        var new_name = PATH.basename(new_path);
4116        var lookup, old_dir, new_dir;
4117        lookup = FS.lookupPath(old_path, { parent: true });
4118        old_dir = lookup.node;
4119        lookup = FS.lookupPath(new_path, { parent: true });
4120        new_dir = lookup.node;
4121        if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
4122        if (old_dir.mount !== new_dir.mount) {
4123          throw new FS.ErrnoError(75);
4124        }
4125        var old_node = FS.lookupNode(old_dir, old_name);
4126        var relative = PATH_FS.relative(old_path, new_dirname);
4127        if (relative.charAt(0) !== ".") {
4128          throw new FS.ErrnoError(28);
4129        }
4130        relative = PATH_FS.relative(new_path, old_dirname);
4131        if (relative.charAt(0) !== ".") {
4132          throw new FS.ErrnoError(55);
4133        }
4134        var new_node;
4135        try {
4136          new_node = FS.lookupNode(new_dir, new_name);
4137        } catch (e) {
4138        }
4139        if (old_node === new_node) {
4140          return;
4141        }
4142        var isdir = FS.isDir(old_node.mode);
4143        var errCode = FS.mayDelete(old_dir, old_name, isdir);
4144        if (errCode) {
4145          throw new FS.ErrnoError(errCode);
4146        }
4147        errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);
4148        if (errCode) {
4149          throw new FS.ErrnoError(errCode);
4150        }
4151        if (!old_dir.node_ops.rename) {
4152          throw new FS.ErrnoError(63);
4153        }
4154        if (FS.isMountpoint(old_node) || new_node && FS.isMountpoint(new_node)) {
4155          throw new FS.ErrnoError(10);
4156        }
4157        if (new_dir !== old_dir) {
4158          errCode = FS.nodePermissions(old_dir, "w");
4159          if (errCode) {
4160            throw new FS.ErrnoError(errCode);
4161          }
4162        }
4163        FS.hashRemoveNode(old_node);
4164        try {
4165          old_dir.node_ops.rename(old_node, new_dir, new_name);
4166          old_node.parent = new_dir;
4167        } catch (e) {
4168          throw e;
4169        } finally {
4170          FS.hashAddNode(old_node);
4171        }
4172      },
4173      rmdir(path) {
4174        var lookup = FS.lookupPath(path, { parent: true });
4175        var parent = lookup.node;
4176        var name = PATH.basename(path);
4177        var node = FS.lookupNode(parent, name);
4178        var errCode = FS.mayDelete(parent, name, true);
4179        if (errCode) {
4180          throw new FS.ErrnoError(errCode);
4181        }
4182        if (!parent.node_ops.rmdir) {
4183          throw new FS.ErrnoError(63);
4184        }
4185        if (FS.isMountpoint(node)) {
4186          throw new FS.ErrnoError(10);
4187        }
4188        parent.node_ops.rmdir(parent, name);
4189        FS.destroyNode(node);
4190      },
4191      readdir(path) {
4192        var lookup = FS.lookupPath(path, { follow: true });
4193        var node = lookup.node;
4194        if (!node.node_ops.readdir) {
4195          throw new FS.ErrnoError(54);
4196        }
4197        return node.node_ops.readdir(node);
4198      },
4199      unlink(path) {
4200        var lookup = FS.lookupPath(path, { parent: true });
4201        var parent = lookup.node;
4202        if (!parent) {
4203          throw new FS.ErrnoError(44);
4204        }
4205        var name = PATH.basename(path);
4206        var node = FS.lookupNode(parent, name);
4207        var errCode = FS.mayDelete(parent, name, false);
4208        if (errCode) {
4209          throw new FS.ErrnoError(errCode);
4210        }
4211        if (!parent.node_ops.unlink) {
4212          throw new FS.ErrnoError(63);
4213        }
4214        if (FS.isMountpoint(node)) {
4215          throw new FS.ErrnoError(10);
4216        }
4217        parent.node_ops.unlink(parent, name);
4218        FS.destroyNode(node);
4219      },
4220      readlink(path) {
4221        var lookup = FS.lookupPath(path);
4222        var link = lookup.node;
4223        if (!link) {
4224          throw new FS.ErrnoError(44);
4225        }
4226        if (!link.node_ops.readlink) {
4227          throw new FS.ErrnoError(28);
4228        }
4229        return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));
4230      },
4231      stat(path, dontFollow) {
4232        var lookup = FS.lookupPath(path, { follow: !dontFollow });
4233        var node = lookup.node;
4234        if (!node) {
4235          throw new FS.ErrnoError(44);
4236        }
4237        if (!node.node_ops.getattr) {
4238          throw new FS.ErrnoError(63);
4239        }
4240        return node.node_ops.getattr(node);
4241      },
4242      lstat(path) {
4243        return FS.stat(path, true);
4244      },
4245      chmod(path, mode, dontFollow) {
4246        var node;
4247        if (typeof path == "string") {
4248          var lookup = FS.lookupPath(path, { follow: !dontFollow });
4249          node = lookup.node;
4250        } else {
4251          node = path;
4252        }
4253        if (!node.node_ops.setattr) {
4254          throw new FS.ErrnoError(63);
4255        }
4256        node.node_ops.setattr(node, {
4257          mode: mode & 4095 | node.mode & -4096,
4258          timestamp: Date.now()
4259        });
4260      },
4261      lchmod(path, mode) {
4262        FS.chmod(path, mode, true);
4263      },
4264      fchmod(fd, mode) {
4265        var stream = FS.getStreamChecked(fd);
4266        FS.chmod(stream.node, mode);
4267      },
4268      chown(path, uid, gid, dontFollow) {
4269        var node;
4270        if (typeof path == "string") {
4271          var lookup = FS.lookupPath(path, { follow: !dontFollow });
4272          node = lookup.node;
4273        } else {
4274          node = path;
4275        }
4276        if (!node.node_ops.setattr) {
4277          throw new FS.ErrnoError(63);
4278        }
4279        node.node_ops.setattr(node, {
4280          timestamp: Date.now()
4281          // we ignore the uid / gid for now
4282        });
4283      },
4284      lchown(path, uid, gid) {
4285        FS.chown(path, uid, gid, true);
4286      },
4287      fchown(fd, uid, gid) {
4288        var stream = FS.getStreamChecked(fd);
4289        FS.chown(stream.node, uid, gid);
4290      },
4291      truncate(path, len) {
4292        if (len < 0) {
4293          throw new FS.ErrnoError(28);
4294        }
4295        var node;
4296        if (typeof path == "string") {
4297          var lookup = FS.lookupPath(path, { follow: true });
4298          node = lookup.node;
4299        } else {
4300          node = path;
4301        }
4302        if (!node.node_ops.setattr) {
4303          throw new FS.ErrnoError(63);
4304        }
4305        if (FS.isDir(node.mode)) {
4306          throw new FS.ErrnoError(31);
4307        }
4308        if (!FS.isFile(node.mode)) {
4309          throw new FS.ErrnoError(28);
4310        }
4311        var errCode = FS.nodePermissions(node, "w");
4312        if (errCode) {
4313          throw new FS.ErrnoError(errCode);
4314        }
4315        node.node_ops.setattr(node, {
4316          size: len,
4317          timestamp: Date.now()
4318        });
4319      },
4320      ftruncate(fd, len) {
4321        var stream = FS.getStreamChecked(fd);
4322        if ((stream.flags & 2097155) === 0) {
4323          throw new FS.ErrnoError(28);
4324        }
4325        FS.truncate(stream.node, len);
4326      },
4327      utime(path, atime, mtime) {
4328        var lookup = FS.lookupPath(path, { follow: true });
4329        var node = lookup.node;
4330        node.node_ops.setattr(node, {
4331          timestamp: Math.max(atime, mtime)
4332        });
4333      },
4334      open(path, flags, mode) {
4335        if (path === "") {
4336          throw new FS.ErrnoError(44);
4337        }
4338        flags = typeof flags == "string" ? FS_modeStringToFlags(flags) : flags;
4339        if (flags & 64) {
4340          mode = typeof mode == "undefined" ? 438 : mode;
4341          mode = mode & 4095 | 32768;
4342        } else {
4343          mode = 0;
4344        }
4345        var node;
4346        if (typeof path == "object") {
4347          node = path;
4348        } else {
4349          path = PATH.normalize(path);
4350          try {
4351            var lookup = FS.lookupPath(path, {
4352              follow: !(flags & 131072)
4353            });
4354            node = lookup.node;
4355          } catch (e) {
4356          }
4357        }
4358        var created = false;
4359        if (flags & 64) {
4360          if (node) {
4361            if (flags & 128) {
4362              throw new FS.ErrnoError(20);
4363            }
4364          } else {
4365            node = FS.mknod(path, mode, 0);
4366            created = true;
4367          }
4368        }
4369        if (!node) {
4370          throw new FS.ErrnoError(44);
4371        }
4372        if (FS.isChrdev(node.mode)) {
4373          flags &= -513;
4374        }
4375        if (flags & 65536 && !FS.isDir(node.mode)) {
4376          throw new FS.ErrnoError(54);
4377        }
4378        if (!created) {
4379          var errCode = FS.mayOpen(node, flags);
4380          if (errCode) {
4381            throw new FS.ErrnoError(errCode);
4382          }
4383        }
4384        if (flags & 512 && !created) {
4385          FS.truncate(node, 0);
4386        }
4387        flags &= -131713;
4388        var stream = FS.createStream({
4389          node,
4390          path: FS.getPath(node),
4391          // we want the absolute path to the node
4392          flags,
4393          seekable: true,
4394          position: 0,
4395          stream_ops: node.stream_ops,
4396          // used by the file family libc calls (fopen, fwrite, ferror, etc.)
4397          ungotten: [],
4398          error: false
4399        });
4400        if (stream.stream_ops.open) {
4401          stream.stream_ops.open(stream);
4402        }
4403        if (Module["logReadFiles"] && !(flags & 1)) {
4404          if (!(path in FS.readFiles)) {
4405            FS.readFiles[path] = 1;
4406          }
4407        }
4408        return stream;
4409      },
4410      close(stream) {
4411        if (FS.isClosed(stream)) {
4412          throw new FS.ErrnoError(8);
4413        }
4414        if (stream.getdents) stream.getdents = null;
4415        try {
4416          if (stream.stream_ops.close) {
4417            stream.stream_ops.close(stream);
4418          }
4419        } catch (e) {
4420          throw e;
4421        } finally {
4422          FS.closeStream(stream.fd);
4423        }
4424        stream.fd = null;
4425      },
4426      isClosed(stream) {
4427        return stream.fd === null;
4428      },
4429      llseek(stream, offset, whence) {
4430        if (FS.isClosed(stream)) {
4431          throw new FS.ErrnoError(8);
4432        }
4433        if (!stream.seekable || !stream.stream_ops.llseek) {
4434          throw new FS.ErrnoError(70);
4435        }
4436        if (whence != 0 && whence != 1 && whence != 2) {
4437          throw new FS.ErrnoError(28);
4438        }
4439        stream.position = stream.stream_ops.llseek(stream, offset, whence);
4440        stream.ungotten = [];
4441        return stream.position;
4442      },
4443      read(stream, buffer, offset, length, position) {
4444        assert(offset >= 0);
4445        if (length < 0 || position < 0) {
4446          throw new FS.ErrnoError(28);
4447        }
4448        if (FS.isClosed(stream)) {
4449          throw new FS.ErrnoError(8);
4450        }
4451        if ((stream.flags & 2097155) === 1) {
4452          throw new FS.ErrnoError(8);
4453        }
4454        if (FS.isDir(stream.node.mode)) {
4455          throw new FS.ErrnoError(31);
4456        }
4457        if (!stream.stream_ops.read) {
4458          throw new FS.ErrnoError(28);
4459        }
4460        var seeking = typeof position != "undefined";
4461        if (!seeking) {
4462          position = stream.position;
4463        } else if (!stream.seekable) {
4464          throw new FS.ErrnoError(70);
4465        }
4466        var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
4467        if (!seeking) stream.position += bytesRead;
4468        return bytesRead;
4469      },
4470      write(stream, buffer, offset, length, position, canOwn) {
4471        assert(offset >= 0);
4472        if (length < 0 || position < 0) {
4473          throw new FS.ErrnoError(28);
4474        }
4475        if (FS.isClosed(stream)) {
4476          throw new FS.ErrnoError(8);
4477        }
4478        if ((stream.flags & 2097155) === 0) {
4479          throw new FS.ErrnoError(8);
4480        }
4481        if (FS.isDir(stream.node.mode)) {
4482          throw new FS.ErrnoError(31);
4483        }
4484        if (!stream.stream_ops.write) {
4485          throw new FS.ErrnoError(28);
4486        }
4487        if (stream.seekable && stream.flags & 1024) {
4488          FS.llseek(stream, 0, 2);
4489        }
4490        var seeking = typeof position != "undefined";
4491        if (!seeking) {
4492          position = stream.position;
4493        } else if (!stream.seekable) {
4494          throw new FS.ErrnoError(70);
4495        }
4496        var bytesWritten = stream.stream_ops.write(
4497          stream,
4498          buffer,
4499          offset,
4500          length,
4501          position,
4502          canOwn
4503        );
4504        if (!seeking) stream.position += bytesWritten;
4505        return bytesWritten;
4506      },
4507      allocate(stream, offset, length) {
4508        if (FS.isClosed(stream)) {
4509          throw new FS.ErrnoError(8);
4510        }
4511        if (offset < 0 || length <= 0) {
4512          throw new FS.ErrnoError(28);
4513        }
4514        if ((stream.flags & 2097155) === 0) {
4515          throw new FS.ErrnoError(8);
4516        }
4517        if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
4518          throw new FS.ErrnoError(43);
4519        }
4520        if (!stream.stream_ops.allocate) {
4521          throw new FS.ErrnoError(138);
4522        }
4523        stream.stream_ops.allocate(stream, offset, length);
4524      },
4525      mmap(stream, length, position, prot, flags) {
4526        if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {
4527          throw new FS.ErrnoError(2);
4528        }
4529        if ((stream.flags & 2097155) === 1) {
4530          throw new FS.ErrnoError(2);
4531        }
4532        if (!stream.stream_ops.mmap) {
4533          throw new FS.ErrnoError(43);
4534        }
4535        if (!length) {
4536          throw new FS.ErrnoError(28);
4537        }
4538        return stream.stream_ops.mmap(stream, length, position, prot, flags);
4539      },
4540      msync(stream, buffer, offset, length, mmapFlags) {
4541        assert(offset >= 0);
4542        if (!stream.stream_ops.msync) {
4543          return 0;
4544        }
4545        return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
4546      },
4547      ioctl(stream, cmd, arg) {
4548        if (!stream.stream_ops.ioctl) {
4549          throw new FS.ErrnoError(59);
4550        }
4551        return stream.stream_ops.ioctl(stream, cmd, arg);
4552      },
4553      readFile(path, opts = {}) {
4554        opts.flags = opts.flags || 0;
4555        opts.encoding = opts.encoding || "binary";
4556        if (opts.encoding !== "utf8" && opts.encoding !== "binary") {
4557          throw new Error(\`Invalid encoding type "\${opts.encoding}"\`);
4558        }
4559        var ret;
4560        var stream = FS.open(path, opts.flags);
4561        var stat = FS.stat(path);
4562        var length = stat.size;
4563        var buf = new Uint8Array(length);
4564        FS.read(stream, buf, 0, length, 0);
4565        if (opts.encoding === "utf8") {
4566          ret = UTF8ArrayToString(buf);
4567        } else if (opts.encoding === "binary") {
4568          ret = buf;
4569        }
4570        FS.close(stream);
4571        return ret;
4572      },
4573      writeFile(path, data, opts = {}) {
4574        opts.flags = opts.flags || 577;
4575        var stream = FS.open(path, opts.flags, opts.mode);
4576        if (typeof data == "string") {
4577          var buf = new Uint8Array(lengthBytesUTF8(data) + 1);
4578          var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
4579          FS.write(stream, buf, 0, actualNumBytes, void 0, opts.canOwn);
4580        } else if (ArrayBuffer.isView(data)) {
4581          FS.write(stream, data, 0, data.byteLength, void 0, opts.canOwn);
4582        } else {
4583          throw new Error("Unsupported data type");
4584        }
4585        FS.close(stream);
4586      },
4587      cwd: () => FS.currentPath,
4588      chdir(path) {
4589        var lookup = FS.lookupPath(path, { follow: true });
4590        if (lookup.node === null) {
4591          throw new FS.ErrnoError(44);
4592        }
4593        if (!FS.isDir(lookup.node.mode)) {
4594          throw new FS.ErrnoError(54);
4595        }
4596        var errCode = FS.nodePermissions(lookup.node, "x");
4597        if (errCode) {
4598          throw new FS.ErrnoError(errCode);
4599        }
4600        FS.currentPath = lookup.path;
4601      },
4602      createDefaultDirectories() {
4603        FS.mkdir("/tmp");
4604        FS.mkdir("/home");
4605        FS.mkdir("/home/web_user");
4606      },
4607      createDefaultDevices() {
4608        FS.mkdir("/dev");
4609        FS.registerDevice(FS.makedev(1, 3), {
4610          read: () => 0,
4611          write: (stream, buffer, offset, length, pos) => length
4612        });
4613        FS.mkdev("/dev/null", FS.makedev(1, 3));
4614        TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
4615        TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
4616        FS.mkdev("/dev/tty", FS.makedev(5, 0));
4617        FS.mkdev("/dev/tty1", FS.makedev(6, 0));
4618        var randomBuffer = new Uint8Array(1024), randomLeft = 0;
4619        var randomByte = () => {
4620          if (randomLeft === 0) {
4621            randomLeft = randomFill(randomBuffer).byteLength;
4622          }
4623          return randomBuffer[--randomLeft];
4624        };
4625        FS.createDevice("/dev", "random", randomByte);
4626        FS.createDevice("/dev", "urandom", randomByte);
4627        FS.mkdir("/dev/shm");
4628        FS.mkdir("/dev/shm/tmp");
4629      },
4630      createSpecialDirectories() {
4631        FS.mkdir("/proc");
4632        var proc_self = FS.mkdir("/proc/self");
4633        FS.mkdir("/proc/self/fd");
4634        FS.mount(
4635          {
4636            mount() {
4637              var node = FS.createNode(proc_self, "fd", 16384 | 511, 73);
4638              node.node_ops = {
4639                lookup(parent, name) {
4640                  var fd = +name;
4641                  var stream = FS.getStreamChecked(fd);
4642                  var ret = {
4643                    parent: null,
4644                    mount: { mountpoint: "fake" },
4645                    node_ops: { readlink: () => stream.path }
4646                  };
4647                  ret.parent = ret;
4648                  return ret;
4649                }
4650              };
4651              return node;
4652            }
4653          },
4654          {},
4655          "/proc/self/fd"
4656        );
4657      },
4658      createStandardStreams(input, output, error) {
4659        if (input) {
4660          FS.createDevice("/dev", "stdin", input);
4661        } else {
4662          FS.symlink("/dev/tty", "/dev/stdin");
4663        }
4664        if (output) {
4665          FS.createDevice("/dev", "stdout", null, output);
4666        } else {
4667          FS.symlink("/dev/tty", "/dev/stdout");
4668        }
4669        if (error) {
4670          FS.createDevice("/dev", "stderr", null, error);
4671        } else {
4672          FS.symlink("/dev/tty1", "/dev/stderr");
4673        }
4674        var stdin = FS.open("/dev/stdin", 0);
4675        var stdout = FS.open("/dev/stdout", 1);
4676        var stderr = FS.open("/dev/stderr", 1);
4677        assert(stdin.fd === 0, \`invalid handle for stdin (\${stdin.fd})\`);
4678        assert(stdout.fd === 1, \`invalid handle for stdout (\${stdout.fd})\`);
4679        assert(stderr.fd === 2, \`invalid handle for stderr (\${stderr.fd})\`);
4680      },
4681      staticInit() {
4682        [44].forEach((code) => {
4683          FS.genericErrors[code] = new FS.ErrnoError(code);
4684          FS.genericErrors[code].stack = "<generic error, no stack>";
4685        });
4686        FS.nameTable = new Array(4096);
4687        FS.mount(MEMFS, {}, "/");
4688        FS.createDefaultDirectories();
4689        FS.createDefaultDevices();
4690        FS.createSpecialDirectories();
4691        FS.filesystems = {
4692          MEMFS
4693        };
4694      },
4695      init(input, output, error) {
4696        assert(
4697          !FS.initialized,
4698          "FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"
4699        );
4700        FS.initialized = true;
4701        input ?? (input = Module["stdin"]);
4702        output ?? (output = Module["stdout"]);
4703        error ?? (error = Module["stderr"]);
4704        FS.createStandardStreams(input, output, error);
4705      },
4706      quit() {
4707        FS.initialized = false;
4708        _fflush(0);
4709        for (var i = 0; i < FS.streams.length; i++) {
4710          var stream = FS.streams[i];
4711          if (!stream) {
4712            continue;
4713          }
4714          FS.close(stream);
4715        }
4716      },
4717      findObject(path, dontResolveLastLink) {
4718        var ret = FS.analyzePath(path, dontResolveLastLink);
4719        if (!ret.exists) {
4720          return null;
4721        }
4722        return ret.object;
4723      },
4724      analyzePath(path, dontResolveLastLink) {
4725        try {
4726          var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
4727          path = lookup.path;
4728        } catch (e) {
4729        }
4730        var ret = {
4731          isRoot: false,
4732          exists: false,
4733          error: 0,
4734          name: null,
4735          path: null,
4736          object: null,
4737          parentExists: false,
4738          parentPath: null,
4739          parentObject: null
4740        };
4741        try {
4742          var lookup = FS.lookupPath(path, { parent: true });
4743          ret.parentExists = true;
4744          ret.parentPath = lookup.path;
4745          ret.parentObject = lookup.node;
4746          ret.name = PATH.basename(path);
4747          lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
4748          ret.exists = true;
4749          ret.path = lookup.path;
4750          ret.object = lookup.node;
4751          ret.name = lookup.node.name;
4752          ret.isRoot = lookup.path === "/";
4753        } catch (e) {
4754          ret.error = e.errno;
4755        }
4756        return ret;
4757      },
4758      createPath(parent, path, canRead, canWrite) {
4759        parent = typeof parent == "string" ? parent : FS.getPath(parent);
4760        var parts = path.split("/").reverse();
4761        while (parts.length) {
4762          var part = parts.pop();
4763          if (!part) continue;
4764          var current = PATH.join2(parent, part);
4765          try {
4766            FS.mkdir(current);
4767          } catch (e) {
4768          }
4769          parent = current;
4770        }
4771        return current;
4772      },
4773      createFile(parent, name, properties, canRead, canWrite) {
4774        var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);
4775        var mode = FS_getMode(canRead, canWrite);
4776        return FS.create(path, mode);
4777      },
4778      createDataFile(parent, name, data, canRead, canWrite, canOwn) {
4779        var path = name;
4780        if (parent) {
4781          parent = typeof parent == "string" ? parent : FS.getPath(parent);
4782          path = name ? PATH.join2(parent, name) : parent;
4783        }
4784        var mode = FS_getMode(canRead, canWrite);
4785        var node = FS.create(path, mode);
4786        if (data) {
4787          if (typeof data == "string") {
4788            var arr = new Array(data.length);
4789            for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
4790            data = arr;
4791          }
4792          FS.chmod(node, mode | 146);
4793          var stream = FS.open(node, 577);
4794          FS.write(stream, data, 0, data.length, 0, canOwn);
4795          FS.close(stream);
4796          FS.chmod(node, mode);
4797        }
4798      },
4799      createDevice(parent, name, input, output) {
4800        var _a;
4801        var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);
4802        var mode = FS_getMode(!!input, !!output);
4803        (_a = FS.createDevice).major ?? (_a.major = 64);
4804        var dev = FS.makedev(FS.createDevice.major++, 0);
4805        FS.registerDevice(dev, {
4806          open(stream) {
4807            stream.seekable = false;
4808          },
4809          close(stream) {
4810            var _a2;
4811            if ((_a2 = output == null ? void 0 : output.buffer) == null ? void 0 : _a2.length) {
4812              output(10);
4813            }
4814          },
4815          read(stream, buffer, offset, length, pos) {
4816            var bytesRead = 0;
4817            for (var i = 0; i < length; i++) {
4818              var result;
4819              try {
4820                result = input();
4821              } catch (e) {
4822                throw new FS.ErrnoError(29);
4823              }
4824              if (result === void 0 && bytesRead === 0) {
4825                throw new FS.ErrnoError(6);
4826              }
4827              if (result === null || result === void 0) break;
4828              bytesRead++;
4829              buffer[offset + i] = result;
4830            }
4831            if (bytesRead) {
4832              stream.node.timestamp = Date.now();
4833            }
4834            return bytesRead;
4835          },
4836          write(stream, buffer, offset, length, pos) {
4837            for (var i = 0; i < length; i++) {
4838              try {
4839                output(buffer[offset + i]);
4840              } catch (e) {
4841                throw new FS.ErrnoError(29);
4842              }
4843            }
4844            if (length) {
4845              stream.node.timestamp = Date.now();
4846            }
4847            return i;
4848          }
4849        });
4850        return FS.mkdev(path, mode, dev);
4851      },
4852      forceLoadFile(obj) {
4853        if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
4854        if (typeof XMLHttpRequest != "undefined") {
4855          throw new Error(
4856            "Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread."
4857          );
4858        } else {
4859          try {
4860            obj.contents = readBinary(obj.url);
4861            obj.usedBytes = obj.contents.length;
4862          } catch (e) {
4863            throw new FS.ErrnoError(29);
4864          }
4865        }
4866      },
4867      createLazyFile(parent, name, url, canRead, canWrite) {
4868        class LazyUint8Array {
4869          constructor() {
4870            this.lengthKnown = false;
4871            this.chunks = [];
4872          }
4873          get(idx) {
4874            if (idx > this.length - 1 || idx < 0) {
4875              return void 0;
4876            }
4877            var chunkOffset = idx % this.chunkSize;
4878            var chunkNum = idx / this.chunkSize | 0;
4879            return this.getter(chunkNum)[chunkOffset];
4880          }
4881          setDataGetter(getter) {
4882            this.getter = getter;
4883          }
4884          cacheLength() {
4885            var xhr = new XMLHttpRequest();
4886            xhr.open("HEAD", url, false);
4887            xhr.send(null);
4888            if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304))
4889              throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
4890            var datalength = Number(xhr.getResponseHeader("Content-length"));
4891            var header;
4892            var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
4893            var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
4894            var chunkSize = 1024 * 1024;
4895            if (!hasByteServing) chunkSize = datalength;
4896            var doXHR = (from, to) => {
4897              if (from > to)
4898                throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
4899              if (to > datalength - 1)
4900                throw new Error("only " + datalength + " bytes available! programmer error!");
4901              var xhr2 = new XMLHttpRequest();
4902              xhr2.open("GET", url, false);
4903              if (datalength !== chunkSize)
4904                xhr2.setRequestHeader("Range", "bytes=" + from + "-" + to);
4905              xhr2.responseType = "arraybuffer";
4906              if (xhr2.overrideMimeType) {
4907                xhr2.overrideMimeType("text/plain; charset=x-user-defined");
4908              }
4909              xhr2.send(null);
4910              if (!(xhr2.status >= 200 && xhr2.status < 300 || xhr2.status === 304))
4911                throw new Error("Couldn't load " + url + ". Status: " + xhr2.status);
4912              if (xhr2.response !== void 0) {
4913                return new Uint8Array(
4914                  /** @type{Array<number>} */
4915                  xhr2.response || []
4916                );
4917              }
4918              return intArrayFromString(xhr2.responseText || "");
4919            };
4920            var lazyArray2 = this;
4921            lazyArray2.setDataGetter((chunkNum) => {
4922              var start = chunkNum * chunkSize;
4923              var end = (chunkNum + 1) * chunkSize - 1;
4924              end = Math.min(end, datalength - 1);
4925              if (typeof lazyArray2.chunks[chunkNum] == "undefined") {
4926                lazyArray2.chunks[chunkNum] = doXHR(start, end);
4927              }
4928              if (typeof lazyArray2.chunks[chunkNum] == "undefined")
4929                throw new Error("doXHR failed!");
4930              return lazyArray2.chunks[chunkNum];
4931            });
4932            if (usesGzip || !datalength) {
4933              chunkSize = datalength = 1;
4934              datalength = this.getter(0).length;
4935              chunkSize = datalength;
4936              out("LazyFiles on gzip forces download of the whole file when length is accessed");
4937            }
4938            this._length = datalength;
4939            this._chunkSize = chunkSize;
4940            this.lengthKnown = true;
4941          }
4942          get length() {
4943            if (!this.lengthKnown) {
4944              this.cacheLength();
4945            }
4946            return this._length;
4947          }
4948          get chunkSize() {
4949            if (!this.lengthKnown) {
4950              this.cacheLength();
4951            }
4952            return this._chunkSize;
4953          }
4954        }
4955        if (typeof XMLHttpRequest != "undefined") {
4956          if (!ENVIRONMENT_IS_WORKER)
4957            throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";
4958          var lazyArray = new LazyUint8Array();
4959          var properties = { isDevice: false, contents: lazyArray };
4960        } else {
4961          var properties = { isDevice: false, url };
4962        }
4963        var node = FS.createFile(parent, name, properties, canRead, canWrite);
4964        if (properties.contents) {
4965          node.contents = properties.contents;
4966        } else if (properties.url) {
4967          node.contents = null;
4968          node.url = properties.url;
4969        }
4970        Object.defineProperties(node, {
4971          usedBytes: {
4972            get: function() {
4973              return this.contents.length;
4974            }
4975          }
4976        });
4977        var stream_ops = {};
4978        var keys = Object.keys(node.stream_ops);
4979        keys.forEach((key) => {
4980          var fn = node.stream_ops[key];
4981          stream_ops[key] = (...args) => {
4982            FS.forceLoadFile(node);
4983            return fn(...args);
4984          };
4985        });
4986        function writeChunks(stream, buffer, offset, length, position) {
4987          var contents = stream.node.contents;
4988          if (position >= contents.length) return 0;
4989          var size = Math.min(contents.length - position, length);
4990          assert(size >= 0);
4991          if (contents.slice) {
4992            for (var i = 0; i < size; i++) {
4993              buffer[offset + i] = contents[position + i];
4994            }
4995          } else {
4996            for (var i = 0; i < size; i++) {
4997              buffer[offset + i] = contents.get(position + i);
4998            }
4999          }
5000          return size;
5001        }
5002        stream_ops.read = (stream, buffer, offset, length, position) => {
5003          FS.forceLoadFile(node);
5004          return writeChunks(stream, buffer, offset, length, position);
5005        };
5006        stream_ops.mmap = (stream, length, position, prot, flags) => {
5007          FS.forceLoadFile(node);
5008          var ptr = mmapAlloc(length);
5009          if (!ptr) {
5010            throw new FS.ErrnoError(48);
5011          }
5012          writeChunks(stream, HEAP8, ptr, length, position);
5013          return { ptr, allocated: true };
5014        };
5015        node.stream_ops = stream_ops;
5016        return node;
5017      },
5018      absolutePath() {
5019        abort("FS.absolutePath has been removed; use PATH_FS.resolve instead");
5020      },
5021      createFolder() {
5022        abort("FS.createFolder has been removed; use FS.mkdir instead");
5023      },
5024      createLink() {
5025        abort("FS.createLink has been removed; use FS.symlink instead");
5026      },
5027      joinPath() {
5028        abort("FS.joinPath has been removed; use PATH.join instead");
5029      },
5030      mmapAlloc() {
5031        abort("FS.mmapAlloc has been replaced by the top level function mmapAlloc");
5032      },
5033      standardizePath() {
5034        abort("FS.standardizePath has been removed; use PATH.normalize instead");
5035      }
5036    };
5037    var SYSCALLS = {
5038      DEFAULT_POLLMASK: 5,
5039      calculateAt(dirfd, path, allowEmpty) {
5040        if (PATH.isAbs(path)) {
5041          return path;
5042        }
5043        var dir;
5044        if (dirfd === -100) {
5045          dir = FS.cwd();
5046        } else {
5047          var dirstream = SYSCALLS.getStreamFromFD(dirfd);
5048          dir = dirstream.path;
5049        }
5050        if (path.length == 0) {
5051          if (!allowEmpty) {
5052            throw new FS.ErrnoError(44);
5053          }
5054          return dir;
5055        }
5056        return PATH.join2(dir, path);
5057      },
5058      doStat(func, path, buf) {
5059        var stat = func(path);
5060        HEAP32[buf >> 2] = stat.dev;
5061        HEAP32[buf + 4 >> 2] = stat.mode;
5062        HEAPU32[buf + 8 >> 2] = stat.nlink;
5063        HEAP32[buf + 12 >> 2] = stat.uid;
5064        HEAP32[buf + 16 >> 2] = stat.gid;
5065        HEAP32[buf + 20 >> 2] = stat.rdev;
5066        tempI64 = [
5067          stat.size >>> 0,
5068          (tempDouble = stat.size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5069        ], HEAP32[buf + 24 >> 2] = tempI64[0], HEAP32[buf + 28 >> 2] = tempI64[1];
5070        HEAP32[buf + 32 >> 2] = 4096;
5071        HEAP32[buf + 36 >> 2] = stat.blocks;
5072        var atime = stat.atime.getTime();
5073        var mtime = stat.mtime.getTime();
5074        var ctime = stat.ctime.getTime();
5075        tempI64 = [
5076          Math.floor(atime / 1e3) >>> 0,
5077          (tempDouble = Math.floor(atime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5078        ], HEAP32[buf + 40 >> 2] = tempI64[0], HEAP32[buf + 44 >> 2] = tempI64[1];
5079        HEAPU32[buf + 48 >> 2] = atime % 1e3 * 1e3 * 1e3;
5080        tempI64 = [
5081          Math.floor(mtime / 1e3) >>> 0,
5082          (tempDouble = Math.floor(mtime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5083        ], HEAP32[buf + 56 >> 2] = tempI64[0], HEAP32[buf + 60 >> 2] = tempI64[1];
5084        HEAPU32[buf + 64 >> 2] = mtime % 1e3 * 1e3 * 1e3;
5085        tempI64 = [
5086          Math.floor(ctime / 1e3) >>> 0,
5087          (tempDouble = Math.floor(ctime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5088        ], HEAP32[buf + 72 >> 2] = tempI64[0], HEAP32[buf + 76 >> 2] = tempI64[1];
5089        HEAPU32[buf + 80 >> 2] = ctime % 1e3 * 1e3 * 1e3;
5090        tempI64 = [
5091          stat.ino >>> 0,
5092          (tempDouble = stat.ino, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5093        ], HEAP32[buf + 88 >> 2] = tempI64[0], HEAP32[buf + 92 >> 2] = tempI64[1];
5094        return 0;
5095      },
5096      doMsync(addr, stream, len, flags, offset) {
5097        if (!FS.isFile(stream.node.mode)) {
5098          throw new FS.ErrnoError(43);
5099        }
5100        if (flags & 2) {
5101          return 0;
5102        }
5103        var buffer = HEAPU8.slice(addr, addr + len);
5104        FS.msync(stream, buffer, offset, len, flags);
5105      },
5106      getStreamFromFD(fd) {
5107        var stream = FS.getStreamChecked(fd);
5108        return stream;
5109      },
5110      varargs: void 0,
5111      getStr(ptr) {
5112        var ret = UTF8ToString(ptr);
5113        return ret;
5114      }
5115    };
5116    function ___syscall_fcntl64(fd, cmd, varargs) {
5117      SYSCALLS.varargs = varargs;
5118      try {
5119        var stream = SYSCALLS.getStreamFromFD(fd);
5120        switch (cmd) {
5121          case 0: {
5122            var arg = syscallGetVarargI();
5123            if (arg < 0) {
5124              return -28;
5125            }
5126            while (FS.streams[arg]) {
5127              arg++;
5128            }
5129            var newStream;
5130            newStream = FS.dupStream(stream, arg);
5131            return newStream.fd;
5132          }
5133          case 1:
5134          case 2:
5135            return 0;
5136          // FD_CLOEXEC makes no sense for a single process.
5137          case 3:
5138            return stream.flags;
5139          case 4: {
5140            var arg = syscallGetVarargI();
5141            stream.flags |= arg;
5142            return 0;
5143          }
5144          case 12: {
5145            var arg = syscallGetVarargP();
5146            var offset = 0;
5147            HEAP16[arg + offset >> 1] = 2;
5148            return 0;
5149          }
5150          case 13:
5151          case 14:
5152            return 0;
5153        }
5154        return -28;
5155      } catch (e) {
5156        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5157        return -e.errno;
5158      }
5159    }
5160    function ___syscall_fstat64(fd, buf) {
5161      try {
5162        var stream = SYSCALLS.getStreamFromFD(fd);
5163        return SYSCALLS.doStat(FS.stat, stream.path, buf);
5164      } catch (e) {
5165        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5166        return -e.errno;
5167      }
5168    }
5169    var convertI32PairToI53Checked = (lo, hi) => {
5170      assert(lo == lo >>> 0 || lo == (lo | 0));
5171      assert(hi === (hi | 0));
5172      return hi + 2097152 >>> 0 < 4194305 - !!lo ? (lo >>> 0) + hi * 4294967296 : NaN;
5173    };
5174    function ___syscall_ftruncate64(fd, length_low, length_high) {
5175      var length = convertI32PairToI53Checked(length_low, length_high);
5176      try {
5177        if (isNaN(length)) return 61;
5178        FS.ftruncate(fd, length);
5179        return 0;
5180      } catch (e) {
5181        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5182        return -e.errno;
5183      }
5184    }
5185    var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {
5186      assert(
5187        typeof maxBytesToWrite == "number",
5188        "stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"
5189      );
5190      return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
5191    };
5192    function ___syscall_getdents64(fd, dirp, count) {
5193      try {
5194        var stream = SYSCALLS.getStreamFromFD(fd);
5195        stream.getdents || (stream.getdents = FS.readdir(stream.path));
5196        var struct_size = 280;
5197        var pos = 0;
5198        var off = FS.llseek(stream, 0, 1);
5199        var idx = Math.floor(off / struct_size);
5200        while (idx < stream.getdents.length && pos + struct_size <= count) {
5201          var id;
5202          var type;
5203          var name = stream.getdents[idx];
5204          if (name === ".") {
5205            id = stream.node.id;
5206            type = 4;
5207          } else if (name === "..") {
5208            var lookup = FS.lookupPath(stream.path, { parent: true });
5209            id = lookup.node.id;
5210            type = 4;
5211          } else {
5212            var child = FS.lookupNode(stream.node, name);
5213            id = child.id;
5214            type = FS.isChrdev(child.mode) ? 2 : FS.isDir(child.mode) ? 4 : FS.isLink(child.mode) ? 10 : 8;
5215          }
5216          assert(id);
5217          tempI64 = [
5218            id >>> 0,
5219            (tempDouble = id, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5220          ], HEAP32[dirp + pos >> 2] = tempI64[0], HEAP32[dirp + pos + 4 >> 2] = tempI64[1];
5221          tempI64 = [
5222            (idx + 1) * struct_size >>> 0,
5223            (tempDouble = (idx + 1) * struct_size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5224          ], HEAP32[dirp + pos + 8 >> 2] = tempI64[0], HEAP32[dirp + pos + 12 >> 2] = tempI64[1];
5225          HEAP16[dirp + pos + 16 >> 1] = 280;
5226          HEAP8[dirp + pos + 18] = type;
5227          stringToUTF8(name, dirp + pos + 19, 256);
5228          pos += struct_size;
5229          idx += 1;
5230        }
5231        FS.llseek(stream, idx * struct_size, 0);
5232        return pos;
5233      } catch (e) {
5234        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5235        return -e.errno;
5236      }
5237    }
5238    function ___syscall_ioctl(fd, op, varargs) {
5239      SYSCALLS.varargs = varargs;
5240      try {
5241        var stream = SYSCALLS.getStreamFromFD(fd);
5242        switch (op) {
5243          case 21509: {
5244            if (!stream.tty) return -59;
5245            return 0;
5246          }
5247          case 21505: {
5248            if (!stream.tty) return -59;
5249            if (stream.tty.ops.ioctl_tcgets) {
5250              var termios = stream.tty.ops.ioctl_tcgets(stream);
5251              var argp = syscallGetVarargP();
5252              HEAP32[argp >> 2] = termios.c_iflag || 0;
5253              HEAP32[argp + 4 >> 2] = termios.c_oflag || 0;
5254              HEAP32[argp + 8 >> 2] = termios.c_cflag || 0;
5255              HEAP32[argp + 12 >> 2] = termios.c_lflag || 0;
5256              for (var i = 0; i < 32; i++) {
5257                HEAP8[argp + i + 17] = termios.c_cc[i] || 0;
5258              }
5259              return 0;
5260            }
5261            return 0;
5262          }
5263          case 21510:
5264          case 21511:
5265          case 21512: {
5266            if (!stream.tty) return -59;
5267            return 0;
5268          }
5269          case 21506:
5270          case 21507:
5271          case 21508: {
5272            if (!stream.tty) return -59;
5273            if (stream.tty.ops.ioctl_tcsets) {
5274              var argp = syscallGetVarargP();
5275              var c_iflag = HEAP32[argp >> 2];
5276              var c_oflag = HEAP32[argp + 4 >> 2];
5277              var c_cflag = HEAP32[argp + 8 >> 2];
5278              var c_lflag = HEAP32[argp + 12 >> 2];
5279              var c_cc = [];
5280              for (var i = 0; i < 32; i++) {
5281                c_cc.push(HEAP8[argp + i + 17]);
5282              }
5283              return stream.tty.ops.ioctl_tcsets(stream.tty, op, {
5284                c_iflag,
5285                c_oflag,
5286                c_cflag,
5287                c_lflag,
5288                c_cc
5289              });
5290            }
5291            return 0;
5292          }
5293          case 21519: {
5294            if (!stream.tty) return -59;
5295            var argp = syscallGetVarargP();
5296            HEAP32[argp >> 2] = 0;
5297            return 0;
5298          }
5299          case 21520: {
5300            if (!stream.tty) return -59;
5301            return -28;
5302          }
5303          case 21531: {
5304            var argp = syscallGetVarargP();
5305            return FS.ioctl(stream, op, argp);
5306          }
5307          case 21523: {
5308            if (!stream.tty) return -59;
5309            if (stream.tty.ops.ioctl_tiocgwinsz) {
5310              var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);
5311              var argp = syscallGetVarargP();
5312              HEAP16[argp >> 1] = winsize[0];
5313              HEAP16[argp + 2 >> 1] = winsize[1];
5314            }
5315            return 0;
5316          }
5317          case 21524: {
5318            if (!stream.tty) return -59;
5319            return 0;
5320          }
5321          case 21515: {
5322            if (!stream.tty) return -59;
5323            return 0;
5324          }
5325          default:
5326            return -28;
5327        }
5328      } catch (e) {
5329        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5330        return -e.errno;
5331      }
5332    }
5333    function ___syscall_lstat64(path, buf) {
5334      try {
5335        path = SYSCALLS.getStr(path);
5336        return SYSCALLS.doStat(FS.lstat, path, buf);
5337      } catch (e) {
5338        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5339        return -e.errno;
5340      }
5341    }
5342    function ___syscall_newfstatat(dirfd, path, buf, flags) {
5343      try {
5344        path = SYSCALLS.getStr(path);
5345        var nofollow = flags & 256;
5346        var allowEmpty = flags & 4096;
5347        flags = flags & ~6400;
5348        assert(!flags, \`unknown flags in __syscall_newfstatat: \${flags}\`);
5349        path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);
5350        return SYSCALLS.doStat(nofollow ? FS.lstat : FS.stat, path, buf);
5351      } catch (e) {
5352        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5353        return -e.errno;
5354      }
5355    }
5356    function ___syscall_openat(dirfd, path, flags, varargs) {
5357      SYSCALLS.varargs = varargs;
5358      try {
5359        path = SYSCALLS.getStr(path);
5360        path = SYSCALLS.calculateAt(dirfd, path);
5361        var mode = varargs ? syscallGetVarargI() : 0;
5362        return FS.open(path, flags, mode).fd;
5363      } catch (e) {
5364        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5365        return -e.errno;
5366      }
5367    }
5368    function ___syscall_rmdir(path) {
5369      try {
5370        path = SYSCALLS.getStr(path);
5371        FS.rmdir(path);
5372        return 0;
5373      } catch (e) {
5374        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5375        return -e.errno;
5376      }
5377    }
5378    function ___syscall_stat64(path, buf) {
5379      try {
5380        path = SYSCALLS.getStr(path);
5381        return SYSCALLS.doStat(FS.stat, path, buf);
5382      } catch (e) {
5383        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5384        return -e.errno;
5385      }
5386    }
5387    function ___syscall_unlinkat(dirfd, path, flags) {
5388      try {
5389        path = SYSCALLS.getStr(path);
5390        path = SYSCALLS.calculateAt(dirfd, path);
5391        if (flags === 0) {
5392          FS.unlink(path);
5393        } else if (flags === 512) {
5394          FS.rmdir(path);
5395        } else {
5396          abort("Invalid flags passed to unlinkat");
5397        }
5398        return 0;
5399      } catch (e) {
5400        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5401        return -e.errno;
5402      }
5403    }
5404    var __abort_js = () => {
5405      abort("native code called abort()");
5406    };
5407    var __emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num);
5408    var __emscripten_throw_longjmp = () => {
5409      throw Infinity;
5410    };
5411    function __gmtime_js(time_low, time_high, tmPtr) {
5412      var time = convertI32PairToI53Checked(time_low, time_high);
5413      var date = new Date(time * 1e3);
5414      HEAP32[tmPtr >> 2] = date.getUTCSeconds();
5415      HEAP32[tmPtr + 4 >> 2] = date.getUTCMinutes();
5416      HEAP32[tmPtr + 8 >> 2] = date.getUTCHours();
5417      HEAP32[tmPtr + 12 >> 2] = date.getUTCDate();
5418      HEAP32[tmPtr + 16 >> 2] = date.getUTCMonth();
5419      HEAP32[tmPtr + 20 >> 2] = date.getUTCFullYear() - 1900;
5420      HEAP32[tmPtr + 24 >> 2] = date.getUTCDay();
5421      var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
5422      var yday = (date.getTime() - start) / (1e3 * 60 * 60 * 24) | 0;
5423      HEAP32[tmPtr + 28 >> 2] = yday;
5424    }
5425    var isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
5426    var MONTH_DAYS_LEAP_CUMULATIVE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
5427    var MONTH_DAYS_REGULAR_CUMULATIVE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
5428    var ydayFromDate = (date) => {
5429      var leap = isLeapYear(date.getFullYear());
5430      var monthDaysCumulative = leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE;
5431      var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;
5432      return yday;
5433    };
5434    function __localtime_js(time_low, time_high, tmPtr) {
5435      var time = convertI32PairToI53Checked(time_low, time_high);
5436      var date = new Date(time * 1e3);
5437      HEAP32[tmPtr >> 2] = date.getSeconds();
5438      HEAP32[tmPtr + 4 >> 2] = date.getMinutes();
5439      HEAP32[tmPtr + 8 >> 2] = date.getHours();
5440      HEAP32[tmPtr + 12 >> 2] = date.getDate();
5441      HEAP32[tmPtr + 16 >> 2] = date.getMonth();
5442      HEAP32[tmPtr + 20 >> 2] = date.getFullYear() - 1900;
5443      HEAP32[tmPtr + 24 >> 2] = date.getDay();
5444      var yday = ydayFromDate(date) | 0;
5445      HEAP32[tmPtr + 28 >> 2] = yday;
5446      HEAP32[tmPtr + 36 >> 2] = -(date.getTimezoneOffset() * 60);
5447      var start = new Date(date.getFullYear(), 0, 1);
5448      var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
5449      var winterOffset = start.getTimezoneOffset();
5450      var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;
5451      HEAP32[tmPtr + 32 >> 2] = dst;
5452    }
5453    var __tzset_js = (timezone, daylight, std_name, dst_name) => {
5454      var currentYear = (/* @__PURE__ */ new Date()).getFullYear();
5455      var winter = new Date(currentYear, 0, 1);
5456      var summer = new Date(currentYear, 6, 1);
5457      var winterOffset = winter.getTimezoneOffset();
5458      var summerOffset = summer.getTimezoneOffset();
5459      var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
5460      HEAPU32[timezone >> 2] = stdTimezoneOffset * 60;
5461      HEAP32[daylight >> 2] = Number(winterOffset != summerOffset);
5462      var extractZone = (timezoneOffset) => {
5463        var sign = timezoneOffset >= 0 ? "-" : "+";
5464        var absOffset = Math.abs(timezoneOffset);
5465        var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");
5466        var minutes = String(absOffset % 60).padStart(2, "0");
5467        return \`UTC\${sign}\${hours}\${minutes}\`;
5468      };
5469      var winterName = extractZone(winterOffset);
5470      var summerName = extractZone(summerOffset);
5471      assert(winterName);
5472      assert(summerName);
5473      assert(
5474        lengthBytesUTF8(winterName) <= 16,
5475        \`timezone name truncated to fit in TZNAME_MAX (\${winterName})\`
5476      );
5477      assert(
5478        lengthBytesUTF8(summerName) <= 16,
5479        \`timezone name truncated to fit in TZNAME_MAX (\${summerName})\`
5480      );
5481      if (summerOffset < winterOffset) {
5482        stringToUTF8(winterName, std_name, 17);
5483        stringToUTF8(summerName, dst_name, 17);
5484      } else {
5485        stringToUTF8(winterName, dst_name, 17);
5486        stringToUTF8(summerName, std_name, 17);
5487      }
5488    };
5489    var _emscripten_date_now = () => Date.now();
5490    var getHeapMax = () => (
5491      // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
5492      // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
5493      // for any code that deals with heap sizes, which would require special
5494      // casing all heap size related code to treat 0 specially.
5495      2147483648
5496    );
5497    var growMemory = (size) => {
5498      var b = wasmMemory.buffer;
5499      var pages = (size - b.byteLength + 65535) / 65536 | 0;
5500      try {
5501        wasmMemory.grow(pages);
5502        updateMemoryViews();
5503        return 1;
5504      } catch (e) {
5505        err(
5506          \`growMemory: Attempted to grow heap from \${b.byteLength} bytes to \${size} bytes, but got error: \${e}\`
5507        );
5508      }
5509    };
5510    var _emscripten_resize_heap = (requestedSize) => {
5511      var oldSize = HEAPU8.length;
5512      requestedSize >>>= 0;
5513      assert(requestedSize > oldSize);
5514      var maxHeapSize = getHeapMax();
5515      if (requestedSize > maxHeapSize) {
5516        err(
5517          \`Cannot enlarge memory, requested \${requestedSize} bytes, but the limit is \${maxHeapSize} bytes!\`
5518        );
5519        return false;
5520      }
5521      for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
5522        var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
5523        overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
5524        var newSize = Math.min(
5525          maxHeapSize,
5526          alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)
5527        );
5528        var replacement = growMemory(newSize);
5529        if (replacement) {
5530          return true;
5531        }
5532      }
5533      err(\`Failed to grow the heap from \${oldSize} bytes to \${newSize} bytes, not enough memory!\`);
5534      return false;
5535    };
5536    var ENV = {};
5537    var getExecutableName = () => {
5538      return thisProgram || "./this.program";
5539    };
5540    var getEnvStrings = () => {
5541      if (!getEnvStrings.strings) {
5542        var lang = (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8";
5543        var env = {
5544          USER: "web_user",
5545          LOGNAME: "web_user",
5546          PATH: "/",
5547          PWD: "/",
5548          HOME: "/home/web_user",
5549          LANG: lang,
5550          _: getExecutableName()
5551        };
5552        for (var x in ENV) {
5553          if (ENV[x] === void 0) delete env[x];
5554          else env[x] = ENV[x];
5555        }
5556        var strings = [];
5557        for (var x in env) {
5558          strings.push(\`\${x}=\${env[x]}\`);
5559        }
5560        getEnvStrings.strings = strings;
5561      }
5562      return getEnvStrings.strings;
5563    };
5564    var stringToAscii = (str, buffer) => {
5565      for (var i = 0; i < str.length; ++i) {
5566        assert(str.charCodeAt(i) === (str.charCodeAt(i) & 255));
5567        HEAP8[buffer++] = str.charCodeAt(i);
5568      }
5569      HEAP8[buffer] = 0;
5570    };
5571    var _environ_get = (__environ, environ_buf) => {
5572      var bufSize = 0;
5573      getEnvStrings().forEach((string, i) => {
5574        var ptr = environ_buf + bufSize;
5575        HEAPU32[__environ + i * 4 >> 2] = ptr;
5576        stringToAscii(string, ptr);
5577        bufSize += string.length + 1;
5578      });
5579      return 0;
5580    };
5581    var _environ_sizes_get = (penviron_count, penviron_buf_size) => {
5582      var strings = getEnvStrings();
5583      HEAPU32[penviron_count >> 2] = strings.length;
5584      var bufSize = 0;
5585      strings.forEach((string) => bufSize += string.length + 1);
5586      HEAPU32[penviron_buf_size >> 2] = bufSize;
5587      return 0;
5588    };
5589    function _fd_close(fd) {
5590      try {
5591        var stream = SYSCALLS.getStreamFromFD(fd);
5592        FS.close(stream);
5593        return 0;
5594      } catch (e) {
5595        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5596        return e.errno;
5597      }
5598    }
5599    var doReadv = (stream, iov, iovcnt, offset) => {
5600      var ret = 0;
5601      for (var i = 0; i < iovcnt; i++) {
5602        var ptr = HEAPU32[iov >> 2];
5603        var len = HEAPU32[iov + 4 >> 2];
5604        iov += 8;
5605        var curr = FS.read(stream, HEAP8, ptr, len, offset);
5606        if (curr < 0) return -1;
5607        ret += curr;
5608        if (curr < len) break;
5609      }
5610      return ret;
5611    };
5612    function _fd_read(fd, iov, iovcnt, pnum) {
5613      try {
5614        var stream = SYSCALLS.getStreamFromFD(fd);
5615        var num = doReadv(stream, iov, iovcnt);
5616        HEAPU32[pnum >> 2] = num;
5617        return 0;
5618      } catch (e) {
5619        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5620        return e.errno;
5621      }
5622    }
5623    function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
5624      var offset = convertI32PairToI53Checked(offset_low, offset_high);
5625      try {
5626        if (isNaN(offset)) return 61;
5627        var stream = SYSCALLS.getStreamFromFD(fd);
5628        FS.llseek(stream, offset, whence);
5629        tempI64 = [
5630          stream.position >>> 0,
5631          (tempDouble = stream.position, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5632        ], HEAP32[newOffset >> 2] = tempI64[0], HEAP32[newOffset + 4 >> 2] = tempI64[1];
5633        if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;
5634        return 0;
5635      } catch (e) {
5636        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5637        return e.errno;
5638      }
5639    }
5640    function _fd_sync(fd) {
5641      var _a;
5642      try {
5643        var stream = SYSCALLS.getStreamFromFD(fd);
5644        if ((_a = stream.stream_ops) == null ? void 0 : _a.fsync) {
5645          return stream.stream_ops.fsync(stream);
5646        }
5647        return 0;
5648      } catch (e) {
5649        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5650        return e.errno;
5651      }
5652    }
5653    var doWritev = (stream, iov, iovcnt, offset) => {
5654      var ret = 0;
5655      for (var i = 0; i < iovcnt; i++) {
5656        var ptr = HEAPU32[iov >> 2];
5657        var len = HEAPU32[iov + 4 >> 2];
5658        iov += 8;
5659        var curr = FS.write(stream, HEAP8, ptr, len, offset);
5660        if (curr < 0) return -1;
5661        ret += curr;
5662        if (curr < len) {
5663          break;
5664        }
5665      }
5666      return ret;
5667    };
5668    function _fd_write(fd, iov, iovcnt, pnum) {
5669      try {
5670        var stream = SYSCALLS.getStreamFromFD(fd);
5671        var num = doWritev(stream, iov, iovcnt);
5672        HEAPU32[pnum >> 2] = num;
5673        return 0;
5674      } catch (e) {
5675        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5676        return e.errno;
5677      }
5678    }
5679    var wasmTableMirror = [];
5680    var wasmTable;
5681    var getWasmTableEntry = (funcPtr) => {
5682      var func = wasmTableMirror[funcPtr];
5683      if (!func) {
5684        if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;
5685        wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);
5686      }
5687      assert(
5688        wasmTable.get(funcPtr) == func,
5689        "JavaScript-side Wasm function table mirror is out of date!"
5690      );
5691      return func;
5692    };
5693    var UTF16Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf-16le") : void 0;
5694    var UTF16ToString = (ptr, maxBytesToRead) => {
5695      assert(ptr % 2 == 0, "Pointer passed to UTF16ToString must be aligned to two bytes!");
5696      var endPtr = ptr;
5697      var idx = endPtr >> 1;
5698      var maxIdx = idx + maxBytesToRead / 2;
5699      while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;
5700      endPtr = idx << 1;
5701      if (endPtr - ptr > 32 && UTF16Decoder)
5702        return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
5703      var str = "";
5704      for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
5705        var codeUnit = HEAP16[ptr + i * 2 >> 1];
5706        if (codeUnit == 0) break;
5707        str += String.fromCharCode(codeUnit);
5708      }
5709      return str;
5710    };
5711    var uleb128Encode = (n, target) => {
5712      assert(n < 16384);
5713      if (n < 128) {
5714        target.push(n);
5715      } else {
5716        target.push(n % 128 | 128, n >> 7);
5717      }
5718    };
5719    var sigToWasmTypes = (sig) => {
5720      assert(
5721        !sig.includes("j"),
5722        "i64 not permitted in function signatures when WASM_BIGINT is disabled"
5723      );
5724      var typeNames = {
5725        i: "i32",
5726        j: "i64",
5727        f: "f32",
5728        d: "f64",
5729        e: "externref",
5730        p: "i32"
5731      };
5732      var type = {
5733        parameters: [],
5734        results: sig[0] == "v" ? [] : [typeNames[sig[0]]]
5735      };
5736      for (var i = 1; i < sig.length; ++i) {
5737        assert(sig[i] in typeNames, "invalid signature char: " + sig[i]);
5738        type.parameters.push(typeNames[sig[i]]);
5739      }
5740      return type;
5741    };
5742    var generateFuncType = (sig, target) => {
5743      var sigRet = sig.slice(0, 1);
5744      var sigParam = sig.slice(1);
5745      var typeCodes = {
5746        i: 127,
5747        // i32
5748        p: 127,
5749        // i32
5750        j: 126,
5751        // i64
5752        f: 125,
5753        // f32
5754        d: 124,
5755        // f64
5756        e: 111
5757        // externref
5758      };
5759      target.push(
5760        96
5761        /* form: func */
5762      );
5763      uleb128Encode(sigParam.length, target);
5764      for (var i = 0; i < sigParam.length; ++i) {
5765        assert(sigParam[i] in typeCodes, "invalid signature char: " + sigParam[i]);
5766        target.push(typeCodes[sigParam[i]]);
5767      }
5768      if (sigRet == "v") {
5769        target.push(0);
5770      } else {
5771        target.push(1, typeCodes[sigRet]);
5772      }
5773    };
5774    var convertJsFunctionToWasm = (func, sig) => {
5775      assert(
5776        !sig.includes("j"),
5777        "i64 not permitted in function signatures when WASM_BIGINT is disabled"
5778      );
5779      if (typeof WebAssembly.Function == "function") {
5780        return new WebAssembly.Function(sigToWasmTypes(sig), func);
5781      }
5782      var typeSectionBody = [
5783        1
5784        // count: 1
5785      ];
5786      generateFuncType(sig, typeSectionBody);
5787      var bytes = [
5788        0,
5789        97,
5790        115,
5791        109,
5792        // magic ("\\0asm")
5793        1,
5794        0,
5795        0,
5796        0,
5797        // version: 1
5798        1
5799        // Type section code
5800      ];
5801      uleb128Encode(typeSectionBody.length, bytes);
5802      bytes.push(...typeSectionBody);
5803      bytes.push(
5804        2,
5805        7,
5806        // import section
5807        // (import "e" "f" (func 0 (type 0)))
5808        1,
5809        1,
5810        101,
5811        1,
5812        102,
5813        0,
5814        0,
5815        7,
5816        5,
5817        // export section
5818        // (export "f" (func 0 (type 0)))
5819        1,
5820        1,
5821        102,
5822        0,
5823        0
5824      );
5825      var module = new WebAssembly.Module(new Uint8Array(bytes));
5826      var instance = new WebAssembly.Instance(module, { e: { f: func } });
5827      var wrappedFunc = instance.exports["f"];
5828      return wrappedFunc;
5829    };
5830    var updateTableMap = (offset, count) => {
5831      if (functionsInTableMap) {
5832        for (var i = offset; i < offset + count; i++) {
5833          var item = getWasmTableEntry(i);
5834          if (item) {
5835            functionsInTableMap.set(item, i);
5836          }
5837        }
5838      }
5839    };
5840    var functionsInTableMap;
5841    var getFunctionAddress = (func) => {
5842      if (!functionsInTableMap) {
5843        functionsInTableMap = /* @__PURE__ */ new WeakMap();
5844        updateTableMap(0, wasmTable.length);
5845      }
5846      return functionsInTableMap.get(func) || 0;
5847    };
5848    var freeTableIndexes = [];
5849    var getEmptyTableSlot = () => {
5850      if (freeTableIndexes.length) {
5851        return freeTableIndexes.pop();
5852      }
5853      try {
5854        wasmTable.grow(1);
5855      } catch (err2) {
5856        if (!(err2 instanceof RangeError)) {
5857          throw err2;
5858        }
5859        throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";
5860      }
5861      return wasmTable.length - 1;
5862    };
5863    var setWasmTableEntry = (idx, func) => {
5864      wasmTable.set(idx, func);
5865      wasmTableMirror[idx] = wasmTable.get(idx);
5866    };
5867    var addFunction = (func, sig) => {
5868      assert(typeof func != "undefined");
5869      var rtn = getFunctionAddress(func);
5870      if (rtn) {
5871        return rtn;
5872      }
5873      var ret = getEmptyTableSlot();
5874      try {
5875        setWasmTableEntry(ret, func);
5876      } catch (err2) {
5877        if (!(err2 instanceof TypeError)) {
5878          throw err2;
5879        }
5880        assert(typeof sig != "undefined", "Missing signature argument to addFunction: " + func);
5881        var wrapped = convertJsFunctionToWasm(func, sig);
5882        setWasmTableEntry(ret, wrapped);
5883      }
5884      functionsInTableMap.set(func, ret);
5885      return ret;
5886    };
5887    var getCFunc = (ident) => {
5888      var func = Module["_" + ident];
5889      assert(func, "Cannot call unknown function " + ident + ", make sure it is exported");
5890      return func;
5891    };
5892    var writeArrayToMemory = (array, buffer) => {
5893      assert(
5894        array.length >= 0,
5895        "writeArrayToMemory array must have a length (should be an array or typed array)"
5896      );
5897      HEAP8.set(array, buffer);
5898    };
5899    var stackAlloc = (sz) => __emscripten_stack_alloc(sz);
5900    var stringToUTF8OnStack = (str) => {
5901      var size = lengthBytesUTF8(str) + 1;
5902      var ret = stackAlloc(size);
5903      stringToUTF8(str, ret, size);
5904      return ret;
5905    };
5906    var ccall = (ident, returnType, argTypes, args, opts) => {
5907      var toC = {
5908        string: (str) => {
5909          var ret2 = 0;
5910          if (str !== null && str !== void 0 && str !== 0) {
5911            ret2 = stringToUTF8OnStack(str);
5912          }
5913          return ret2;
5914        },
5915        array: (arr) => {
5916          var ret2 = stackAlloc(arr.length);
5917          writeArrayToMemory(arr, ret2);
5918          return ret2;
5919        }
5920      };
5921      function convertReturnValue(ret2) {
5922        if (returnType === "string") {
5923          return UTF8ToString(ret2);
5924        }
5925        if (returnType === "boolean") return Boolean(ret2);
5926        return ret2;
5927      }
5928      var func = getCFunc(ident);
5929      var cArgs = [];
5930      var stack = 0;
5931      assert(returnType !== "array", 'Return type should not be "array".');
5932      if (args) {
5933        for (var i = 0; i < args.length; i++) {
5934          var converter = toC[argTypes[i]];
5935          if (converter) {
5936            if (stack === 0) stack = stackSave();
5937            cArgs[i] = converter(args[i]);
5938          } else {
5939            cArgs[i] = args[i];
5940          }
5941        }
5942      }
5943      var ret = func(...cArgs);
5944      function onDone(ret2) {
5945        if (stack !== 0) stackRestore(stack);
5946        return convertReturnValue(ret2);
5947      }
5948      ret = onDone(ret);
5949      return ret;
5950    };
5951    var cwrap = (ident, returnType, argTypes, opts) => {
5952      return (...args) => ccall(ident, returnType, argTypes, args);
5953    };
5954    var removeFunction = (index) => {
5955      functionsInTableMap.delete(getWasmTableEntry(index));
5956      setWasmTableEntry(index, null);
5957      freeTableIndexes.push(index);
5958    };
5959    var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {
5960      assert(outPtr % 2 == 0, "Pointer passed to stringToUTF16 must be aligned to two bytes!");
5961      assert(
5962        typeof maxBytesToWrite == "number",
5963        "stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"
5964      );
5965      maxBytesToWrite ?? (maxBytesToWrite = 2147483647);
5966      if (maxBytesToWrite < 2) return 0;
5967      maxBytesToWrite -= 2;
5968      var startPtr = outPtr;
5969      var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;
5970      for (var i = 0; i < numCharsToWrite; ++i) {
5971        var codeUnit = str.charCodeAt(i);
5972        HEAP16[outPtr >> 1] = codeUnit;
5973        outPtr += 2;
5974      }
5975      HEAP16[outPtr >> 1] = 0;
5976      return outPtr - startPtr;
5977    };
5978    FS.createPreloadedFile = FS_createPreloadedFile;
5979    FS.staticInit();
5980    function checkIncomingModuleAPI() {
5981      ignoredModuleProp("fetchSettings");
5982    }
5983    var wasmImports = {
5984      /** @export */
5985      __assert_fail: ___assert_fail,
5986      /** @export */
5987      __syscall_fcntl64: ___syscall_fcntl64,
5988      /** @export */
5989      __syscall_fstat64: ___syscall_fstat64,
5990      /** @export */
5991      __syscall_ftruncate64: ___syscall_ftruncate64,
5992      /** @export */
5993      __syscall_getdents64: ___syscall_getdents64,
5994      /** @export */
5995      __syscall_ioctl: ___syscall_ioctl,
5996      /** @export */
5997      __syscall_lstat64: ___syscall_lstat64,
5998      /** @export */
5999      __syscall_newfstatat: ___syscall_newfstatat,
6000      /** @export */
6001      __syscall_openat: ___syscall_openat,
6002      /** @export */
6003      __syscall_rmdir: ___syscall_rmdir,
6004      /** @export */
6005      __syscall_stat64: ___syscall_stat64,
6006      /** @export */
6007      __syscall_unlinkat: ___syscall_unlinkat,
6008      /** @export */
6009      _abort_js: __abort_js,
6010      /** @export */
6011      _emscripten_memcpy_js: __emscripten_memcpy_js,
6012      /** @export */
6013      _emscripten_throw_longjmp: __emscripten_throw_longjmp,
6014      /** @export */
6015      _gmtime_js: __gmtime_js,
6016      /** @export */
6017      _localtime_js: __localtime_js,
6018      /** @export */
6019      _tzset_js: __tzset_js,
6020      /** @export */
6021      emscripten_date_now: _emscripten_date_now,
6022      /** @export */
6023      emscripten_resize_heap: _emscripten_resize_heap,
6024      /** @export */
6025      environ_get: _environ_get,
6026      /** @export */
6027      environ_sizes_get: _environ_sizes_get,
6028      /** @export */
6029      fd_close: _fd_close,
6030      /** @export */
6031      fd_read: _fd_read,
6032      /** @export */
6033      fd_seek: _fd_seek,
6034      /** @export */
6035      fd_sync: _fd_sync,
6036      /** @export */
6037      fd_write: _fd_write,
6038      /** @export */
6039      invoke_ii,
6040      /** @export */
6041      invoke_iii,
6042      /** @export */
6043      invoke_iiii,
6044      /** @export */
6045      invoke_iiiii,
6046      /** @export */
6047      invoke_v,
6048      /** @export */
6049      invoke_vi,
6050      /** @export */
6051      invoke_vii,
6052      /** @export */
6053      invoke_viii,
6054      /** @export */
6055      invoke_viiii,
6056      /** @export */
6057      invoke_viiiiiiiii
6058    };
6059    var wasmExports = createWasm();
6060    Module["_PDFiumExt_Init"] = createExportWrapper("PDFiumExt_Init", 0);
6061    Module["_FPDF_InitLibraryWithConfig"] = createExportWrapper(
6062      "FPDF_InitLibraryWithConfig",
6063      1
6064    );
6065    Module["_PDFiumExt_OpenFileWriter"] = createExportWrapper(
6066      "PDFiumExt_OpenFileWriter",
6067      0
6068    );
6069    Module["_PDFiumExt_GetFileWriterSize"] = createExportWrapper("PDFiumExt_GetFileWriterSize", 1);
6070    Module["_PDFiumExt_GetFileWriterData"] = createExportWrapper("PDFiumExt_GetFileWriterData", 3);
6071    Module["_PDFiumExt_CloseFileWriter"] = createExportWrapper(
6072      "PDFiumExt_CloseFileWriter",
6073      1
6074    );
6075    Module["_PDFiumExt_SaveAsCopy"] = createExportWrapper(
6076      "PDFiumExt_SaveAsCopy",
6077      2
6078    );
6079    Module["_FPDF_SaveAsCopy"] = createExportWrapper("FPDF_SaveAsCopy", 3);
6080    Module["_PDFiumExt_OpenFormFillInfo"] = createExportWrapper(
6081      "PDFiumExt_OpenFormFillInfo",
6082      0
6083    );
6084    Module["_PDFiumExt_CloseFormFillInfo"] = createExportWrapper("PDFiumExt_CloseFormFillInfo", 1);
6085    Module["_PDFiumExt_InitFormFillEnvironment"] = createExportWrapper("PDFiumExt_InitFormFillEnvironment", 2);
6086    Module["_FPDFDOC_InitFormFillEnvironment"] = createExportWrapper("FPDFDOC_InitFormFillEnvironment", 2);
6087    Module["_PDFiumExt_ExitFormFillEnvironment"] = createExportWrapper("PDFiumExt_ExitFormFillEnvironment", 1);
6088    Module["_FPDFDOC_ExitFormFillEnvironment"] = createExportWrapper("FPDFDOC_ExitFormFillEnvironment", 1);
6089    Module["_EPDFNamedDest_SetDest"] = createExportWrapper(
6090      "EPDFNamedDest_SetDest",
6091      3
6092    );
6093    Module["_EPDFNamedDest_Remove"] = createExportWrapper(
6094      "EPDFNamedDest_Remove",
6095      2
6096    );
6097    Module["_EPDFDest_CreateView"] = createExportWrapper(
6098      "EPDFDest_CreateView",
6099      4
6100    );
6101    Module["_EPDFDest_CreateXYZ"] = createExportWrapper(
6102      "EPDFDest_CreateXYZ",
6103      7
6104    );
6105    Module["_EPDFDest_CreateRemoteView"] = createExportWrapper(
6106      "EPDFDest_CreateRemoteView",
6107      5
6108    );
6109    Module["_EPDFDest_CreateRemoteXYZ"] = createExportWrapper(
6110      "EPDFDest_CreateRemoteXYZ",
6111      8
6112    );
6113    Module["_EPDFAction_CreateGoTo"] = createExportWrapper(
6114      "EPDFAction_CreateGoTo",
6115      2
6116    );
6117    Module["_EPDFAction_CreateGoToNamed"] = createExportWrapper(
6118      "EPDFAction_CreateGoToNamed",
6119      2
6120    );
6121    Module["_EPDFAction_CreateLaunch"] = createExportWrapper(
6122      "EPDFAction_CreateLaunch",
6123      2
6124    );
6125    Module["_EPDFAction_CreateRemoteGoToByName"] = createExportWrapper("EPDFAction_CreateRemoteGoToByName", 3);
6126    Module["_EPDFAction_CreateRemoteGoToDest"] = createExportWrapper("EPDFAction_CreateRemoteGoToDest", 3);
6127    Module["_EPDFAction_CreateURI"] = createExportWrapper(
6128      "EPDFAction_CreateURI",
6129      2
6130    );
6131    Module["_EPDFBookmark_Create"] = createExportWrapper(
6132      "EPDFBookmark_Create",
6133      2
6134    );
6135    Module["_EPDFBookmark_Delete"] = createExportWrapper(
6136      "EPDFBookmark_Delete",
6137      2
6138    );
6139    Module["_EPDFBookmark_AppendChild"] = createExportWrapper(
6140      "EPDFBookmark_AppendChild",
6141      3
6142    );
6143    Module["_EPDFBookmark_InsertAfter"] = createExportWrapper(
6144      "EPDFBookmark_InsertAfter",
6145      4
6146    );
6147    Module["_EPDFBookmark_Clear"] = createExportWrapper(
6148      "EPDFBookmark_Clear",
6149      1
6150    );
6151    Module["_EPDFBookmark_SetTitle"] = createExportWrapper(
6152      "EPDFBookmark_SetTitle",
6153      2
6154    );
6155    Module["_EPDFBookmark_SetDest"] = createExportWrapper(
6156      "EPDFBookmark_SetDest",
6157      3
6158    );
6159    Module["_EPDFBookmark_SetAction"] = createExportWrapper(
6160      "EPDFBookmark_SetAction",
6161      3
6162    );
6163    Module["_EPDFBookmark_ClearTarget"] = createExportWrapper(
6164      "EPDFBookmark_ClearTarget",
6165      1
6166    );
6167    Module["_EPDF_PNG_EncodeRGBA"] = createExportWrapper(
6168      "EPDF_PNG_EncodeRGBA",
6169      6
6170    );
6171    Module["_FPDFAnnot_IsSupportedSubtype"] = createExportWrapper("FPDFAnnot_IsSupportedSubtype", 1);
6172    Module["_FPDFPage_CreateAnnot"] = createExportWrapper(
6173      "FPDFPage_CreateAnnot",
6174      2
6175    );
6176    Module["_FPDFPage_GetAnnotCount"] = createExportWrapper(
6177      "FPDFPage_GetAnnotCount",
6178      1
6179    );
6180    Module["_FPDFPage_GetAnnot"] = createExportWrapper(
6181      "FPDFPage_GetAnnot",
6182      2
6183    );
6184    Module["_FPDFPage_GetAnnotIndex"] = createExportWrapper(
6185      "FPDFPage_GetAnnotIndex",
6186      2
6187    );
6188    Module["_FPDFPage_CloseAnnot"] = createExportWrapper(
6189      "FPDFPage_CloseAnnot",
6190      1
6191    );
6192    Module["_FPDFPage_RemoveAnnot"] = createExportWrapper(
6193      "FPDFPage_RemoveAnnot",
6194      2
6195    );
6196    Module["_FPDFAnnot_GetSubtype"] = createExportWrapper(
6197      "FPDFAnnot_GetSubtype",
6198      1
6199    );
6200    Module["_FPDFAnnot_IsObjectSupportedSubtype"] = createExportWrapper("FPDFAnnot_IsObjectSupportedSubtype", 1);
6201    Module["_FPDFAnnot_UpdateObject"] = createExportWrapper(
6202      "FPDFAnnot_UpdateObject",
6203      2
6204    );
6205    Module["_FPDFAnnot_AddInkStroke"] = createExportWrapper(
6206      "FPDFAnnot_AddInkStroke",
6207      3
6208    );
6209    Module["_FPDFAnnot_RemoveInkList"] = createExportWrapper(
6210      "FPDFAnnot_RemoveInkList",
6211      1
6212    );
6213    Module["_FPDFAnnot_AppendObject"] = createExportWrapper(
6214      "FPDFAnnot_AppendObject",
6215      2
6216    );
6217    Module["_FPDFAnnot_GetObjectCount"] = createExportWrapper(
6218      "FPDFAnnot_GetObjectCount",
6219      1
6220    );
6221    Module["_FPDFAnnot_GetObject"] = createExportWrapper(
6222      "FPDFAnnot_GetObject",
6223      2
6224    );
6225    Module["_FPDFAnnot_RemoveObject"] = createExportWrapper(
6226      "FPDFAnnot_RemoveObject",
6227      2
6228    );
6229    Module["_FPDFAnnot_SetColor"] = createExportWrapper(
6230      "FPDFAnnot_SetColor",
6231      6
6232    );
6233    Module["_FPDFAnnot_GetColor"] = createExportWrapper(
6234      "FPDFAnnot_GetColor",
6235      6
6236    );
6237    Module["_FPDFAnnot_HasAttachmentPoints"] = createExportWrapper("FPDFAnnot_HasAttachmentPoints", 1);
6238    Module["_FPDFAnnot_SetAttachmentPoints"] = createExportWrapper("FPDFAnnot_SetAttachmentPoints", 3);
6239    Module["_FPDFAnnot_AppendAttachmentPoints"] = createExportWrapper("FPDFAnnot_AppendAttachmentPoints", 2);
6240    Module["_FPDFAnnot_CountAttachmentPoints"] = createExportWrapper("FPDFAnnot_CountAttachmentPoints", 1);
6241    Module["_FPDFAnnot_GetAttachmentPoints"] = createExportWrapper("FPDFAnnot_GetAttachmentPoints", 3);
6242    Module["_FPDFAnnot_SetRect"] = createExportWrapper(
6243      "FPDFAnnot_SetRect",
6244      2
6245    );
6246    Module["_FPDFAnnot_GetRect"] = createExportWrapper(
6247      "FPDFAnnot_GetRect",
6248      2
6249    );
6250    Module["_FPDFAnnot_GetVertices"] = createExportWrapper(
6251      "FPDFAnnot_GetVertices",
6252      3
6253    );
6254    Module["_FPDFAnnot_GetInkListCount"] = createExportWrapper(
6255      "FPDFAnnot_GetInkListCount",
6256      1
6257    );
6258    Module["_FPDFAnnot_GetInkListPath"] = createExportWrapper(
6259      "FPDFAnnot_GetInkListPath",
6260      4
6261    );
6262    Module["_FPDFAnnot_GetLine"] = createExportWrapper(
6263      "FPDFAnnot_GetLine",
6264      3
6265    );
6266    Module["_FPDFAnnot_SetBorder"] = createExportWrapper(
6267      "FPDFAnnot_SetBorder",
6268      4
6269    );
6270    Module["_FPDFAnnot_GetBorder"] = createExportWrapper(
6271      "FPDFAnnot_GetBorder",
6272      4
6273    );
6274    Module["_FPDFAnnot_HasKey"] = createExportWrapper(
6275      "FPDFAnnot_HasKey",
6276      2
6277    );
6278    Module["_FPDFAnnot_GetValueType"] = createExportWrapper(
6279      "FPDFAnnot_GetValueType",
6280      2
6281    );
6282    Module["_FPDFAnnot_SetStringValue"] = createExportWrapper(
6283      "FPDFAnnot_SetStringValue",
6284      3
6285    );
6286    Module["_FPDFAnnot_GetStringValue"] = createExportWrapper(
6287      "FPDFAnnot_GetStringValue",
6288      4
6289    );
6290    Module["_FPDFAnnot_GetNumberValue"] = createExportWrapper(
6291      "FPDFAnnot_GetNumberValue",
6292      3
6293    );
6294    Module["_EPDFAnnot_SetNumberValue"] = createExportWrapper(
6295      "EPDFAnnot_SetNumberValue",
6296      3
6297    );
6298    Module["_FPDFAnnot_SetAP"] = createExportWrapper("FPDFAnnot_SetAP", 3);
6299    Module["_FPDFAnnot_GetAP"] = createExportWrapper("FPDFAnnot_GetAP", 4);
6300    Module["_FPDFAnnot_GetLinkedAnnot"] = createExportWrapper(
6301      "FPDFAnnot_GetLinkedAnnot",
6302      2
6303    );
6304    Module["_FPDFAnnot_GetFlags"] = createExportWrapper(
6305      "FPDFAnnot_GetFlags",
6306      1
6307    );
6308    Module["_FPDFAnnot_SetFlags"] = createExportWrapper(
6309      "FPDFAnnot_SetFlags",
6310      2
6311    );
6312    Module["_FPDFAnnot_GetFormFieldFlags"] = createExportWrapper("FPDFAnnot_GetFormFieldFlags", 2);
6313    Module["_FPDFAnnot_SetFormFieldFlags"] = createExportWrapper("FPDFAnnot_SetFormFieldFlags", 3);
6314    Module["_FPDFAnnot_GetFormFieldAtPoint"] = createExportWrapper("FPDFAnnot_GetFormFieldAtPoint", 3);
6315    Module["_FPDFAnnot_GetFormFieldName"] = createExportWrapper(
6316      "FPDFAnnot_GetFormFieldName",
6317      4
6318    );
6319    Module["_FPDFAnnot_GetFormFieldType"] = createExportWrapper(
6320      "FPDFAnnot_GetFormFieldType",
6321      2
6322    );
6323    Module["_FPDFAnnot_GetFormAdditionalActionJavaScript"] = createExportWrapper("FPDFAnnot_GetFormAdditionalActionJavaScript", 5);
6324    Module["_FPDFAnnot_GetFormFieldAlternateName"] = createExportWrapper("FPDFAnnot_GetFormFieldAlternateName", 4);
6325    Module["_FPDFAnnot_GetFormFieldValue"] = createExportWrapper("FPDFAnnot_GetFormFieldValue", 4);
6326    Module["_FPDFAnnot_GetOptionCount"] = createExportWrapper(
6327      "FPDFAnnot_GetOptionCount",
6328      2
6329    );
6330    Module["_FPDFAnnot_GetOptionLabel"] = createExportWrapper(
6331      "FPDFAnnot_GetOptionLabel",
6332      5
6333    );
6334    Module["_FPDFAnnot_IsOptionSelected"] = createExportWrapper(
6335      "FPDFAnnot_IsOptionSelected",
6336      3
6337    );
6338    Module["_FPDFAnnot_GetFontSize"] = createExportWrapper(
6339      "FPDFAnnot_GetFontSize",
6340      3
6341    );
6342    Module["_FPDFAnnot_SetFontColor"] = createExportWrapper(
6343      "FPDFAnnot_SetFontColor",
6344      5
6345    );
6346    Module["_FPDFAnnot_GetFontColor"] = createExportWrapper(
6347      "FPDFAnnot_GetFontColor",
6348      5
6349    );
6350    Module["_FPDFAnnot_IsChecked"] = createExportWrapper(
6351      "FPDFAnnot_IsChecked",
6352      2
6353    );
6354    Module["_FPDFAnnot_SetFocusableSubtypes"] = createExportWrapper("FPDFAnnot_SetFocusableSubtypes", 3);
6355    Module["_FPDFAnnot_GetFocusableSubtypesCount"] = createExportWrapper("FPDFAnnot_GetFocusableSubtypesCount", 1);
6356    Module["_FPDFAnnot_GetFocusableSubtypes"] = createExportWrapper("FPDFAnnot_GetFocusableSubtypes", 3);
6357    Module["_FPDFAnnot_GetLink"] = createExportWrapper(
6358      "FPDFAnnot_GetLink",
6359      1
6360    );
6361    Module["_FPDFAnnot_GetFormControlCount"] = createExportWrapper("FPDFAnnot_GetFormControlCount", 2);
6362    Module["_FPDFAnnot_GetFormControlIndex"] = createExportWrapper("FPDFAnnot_GetFormControlIndex", 2);
6363    Module["_FPDFAnnot_GetFormFieldExportValue"] = createExportWrapper("FPDFAnnot_GetFormFieldExportValue", 4);
6364    Module["_FPDFAnnot_SetURI"] = createExportWrapper(
6365      "FPDFAnnot_SetURI",
6366      2
6367    );
6368    Module["_EPDFAnnot_SetAction"] = createExportWrapper(
6369      "EPDFAnnot_SetAction",
6370      2
6371    );
6372    Module["_FPDFAnnot_GetFileAttachment"] = createExportWrapper("FPDFAnnot_GetFileAttachment", 1);
6373    Module["_FPDFAnnot_AddFileAttachment"] = createExportWrapper("FPDFAnnot_AddFileAttachment", 2);
6374    Module["_EPDFAnnot_SetColor"] = createExportWrapper(
6375      "EPDFAnnot_SetColor",
6376      5
6377    );
6378    Module["_EPDFAnnot_GetColor"] = createExportWrapper(
6379      "EPDFAnnot_GetColor",
6380      5
6381    );
6382    Module["_EPDFAnnot_ClearColor"] = createExportWrapper(
6383      "EPDFAnnot_ClearColor",
6384      2
6385    );
6386    Module["_EPDFAnnot_SetOpacity"] = createExportWrapper(
6387      "EPDFAnnot_SetOpacity",
6388      2
6389    );
6390    Module["_EPDFAnnot_GetOpacity"] = createExportWrapper(
6391      "EPDFAnnot_GetOpacity",
6392      2
6393    );
6394    Module["_EPDFAnnot_GetBorderEffect"] = createExportWrapper(
6395      "EPDFAnnot_GetBorderEffect",
6396      2
6397    );
6398    Module["_EPDFAnnot_SetBorderEffect"] = createExportWrapper(
6399      "EPDFAnnot_SetBorderEffect",
6400      2
6401    );
6402    Module["_EPDFAnnot_ClearBorderEffect"] = createExportWrapper("EPDFAnnot_ClearBorderEffect", 1);
6403    Module["_EPDFAnnot_GetRectangleDifferences"] = createExportWrapper("EPDFAnnot_GetRectangleDifferences", 5);
6404    Module["_EPDFAnnot_SetRectangleDifferences"] = createExportWrapper("EPDFAnnot_SetRectangleDifferences", 5);
6405    Module["_EPDFAnnot_ClearRectangleDifferences"] = createExportWrapper("EPDFAnnot_ClearRectangleDifferences", 1);
6406    Module["_EPDFAnnot_GetBorderDashPatternCount"] = createExportWrapper("EPDFAnnot_GetBorderDashPatternCount", 1);
6407    Module["_EPDFAnnot_GetBorderDashPattern"] = createExportWrapper("EPDFAnnot_GetBorderDashPattern", 3);
6408    Module["_EPDFAnnot_SetBorderDashPattern"] = createExportWrapper("EPDFAnnot_SetBorderDashPattern", 3);
6409    Module["_EPDFAnnot_GetBorderStyle"] = createExportWrapper(
6410      "EPDFAnnot_GetBorderStyle",
6411      2
6412    );
6413    Module["_EPDFAnnot_SetBorderStyle"] = createExportWrapper(
6414      "EPDFAnnot_SetBorderStyle",
6415      3
6416    );
6417    Module["_EPDFAnnot_GenerateAppearance"] = createExportWrapper("EPDFAnnot_GenerateAppearance", 1);
6418    Module["_EPDFAnnot_GenerateAppearanceWithBlend"] = createExportWrapper("EPDFAnnot_GenerateAppearanceWithBlend", 2);
6419    Module["_EPDFAnnot_GetBlendMode"] = createExportWrapper(
6420      "EPDFAnnot_GetBlendMode",
6421      1
6422    );
6423    Module["_EPDFAnnot_SetIntent"] = createExportWrapper(
6424      "EPDFAnnot_SetIntent",
6425      2
6426    );
6427    Module["_EPDFAnnot_GetIntent"] = createExportWrapper(
6428      "EPDFAnnot_GetIntent",
6429      3
6430    );
6431    Module["_EPDFAnnot_GetRichContent"] = createExportWrapper(
6432      "EPDFAnnot_GetRichContent",
6433      3
6434    );
6435    Module["_EPDFAnnot_SetLineEndings"] = createExportWrapper(
6436      "EPDFAnnot_SetLineEndings",
6437      3
6438    );
6439    Module["_EPDFAnnot_GetLineEndings"] = createExportWrapper(
6440      "EPDFAnnot_GetLineEndings",
6441      3
6442    );
6443    Module["_EPDFAnnot_SetVertices"] = createExportWrapper(
6444      "EPDFAnnot_SetVertices",
6445      3
6446    );
6447    Module["_EPDFAnnot_SetLine"] = createExportWrapper(
6448      "EPDFAnnot_SetLine",
6449      3
6450    );
6451    Module["_EPDFAnnot_SetDefaultAppearance"] = createExportWrapper("EPDFAnnot_SetDefaultAppearance", 6);
6452    Module["_EPDFAnnot_GetDefaultAppearance"] = createExportWrapper("EPDFAnnot_GetDefaultAppearance", 6);
6453    Module["_EPDFAnnot_SetTextAlignment"] = createExportWrapper(
6454      "EPDFAnnot_SetTextAlignment",
6455      2
6456    );
6457    Module["_EPDFAnnot_GetTextAlignment"] = createExportWrapper(
6458      "EPDFAnnot_GetTextAlignment",
6459      1
6460    );
6461    Module["_EPDFAnnot_SetVerticalAlignment"] = createExportWrapper("EPDFAnnot_SetVerticalAlignment", 2);
6462    Module["_EPDFAnnot_GetVerticalAlignment"] = createExportWrapper("EPDFAnnot_GetVerticalAlignment", 1);
6463    Module["_EPDFPage_GetAnnotByName"] = createExportWrapper(
6464      "EPDFPage_GetAnnotByName",
6465      2
6466    );
6467    Module["_EPDFPage_RemoveAnnotByName"] = createExportWrapper(
6468      "EPDFPage_RemoveAnnotByName",
6469      2
6470    );
6471    Module["_EPDFAnnot_SetLinkedAnnot"] = createExportWrapper(
6472      "EPDFAnnot_SetLinkedAnnot",
6473      3
6474    );
6475    Module["_EPDFPage_GetAnnotCountRaw"] = createExportWrapper(
6476      "EPDFPage_GetAnnotCountRaw",
6477      2
6478    );
6479    Module["_EPDFPage_GetAnnotRaw"] = createExportWrapper(
6480      "EPDFPage_GetAnnotRaw",
6481      3
6482    );
6483    Module["_EPDFPage_RemoveAnnotRaw"] = createExportWrapper(
6484      "EPDFPage_RemoveAnnotRaw",
6485      3
6486    );
6487    Module["_EPDFAnnot_SetName"] = createExportWrapper(
6488      "EPDFAnnot_SetName",
6489      2
6490    );
6491    Module["_EPDFAnnot_GetName"] = createExportWrapper(
6492      "EPDFAnnot_GetName",
6493      1
6494    );
6495    Module["_EPDFAnnot_UpdateAppearanceToRect"] = createExportWrapper("EPDFAnnot_UpdateAppearanceToRect", 2);
6496    Module["_EPDFPage_CreateAnnot"] = createExportWrapper(
6497      "EPDFPage_CreateAnnot",
6498      2
6499    );
6500    Module["_EPDFAnnot_SetRotate"] = createExportWrapper(
6501      "EPDFAnnot_SetRotate",
6502      2
6503    );
6504    Module["_EPDFAnnot_GetRotate"] = createExportWrapper(
6505      "EPDFAnnot_GetRotate",
6506      2
6507    );
6508    Module["_EPDFAnnot_GetReplyType"] = createExportWrapper(
6509      "EPDFAnnot_GetReplyType",
6510      1
6511    );
6512    Module["_EPDFAnnot_SetReplyType"] = createExportWrapper(
6513      "EPDFAnnot_SetReplyType",
6514      2
6515    );
6516    Module["_EPDFAnnot_SetOverlayText"] = createExportWrapper(
6517      "EPDFAnnot_SetOverlayText",
6518      2
6519    );
6520    Module["_EPDFAnnot_GetOverlayText"] = createExportWrapper(
6521      "EPDFAnnot_GetOverlayText",
6522      3
6523    );
6524    Module["_EPDFAnnot_SetOverlayTextRepeat"] = createExportWrapper("EPDFAnnot_SetOverlayTextRepeat", 2);
6525    Module["_EPDFAnnot_GetOverlayTextRepeat"] = createExportWrapper("EPDFAnnot_GetOverlayTextRepeat", 1);
6526    Module["_EPDFAnnot_ApplyRedaction"] = createExportWrapper(
6527      "EPDFAnnot_ApplyRedaction",
6528      2
6529    );
6530    Module["_EPDFPage_ApplyRedactions"] = createExportWrapper(
6531      "EPDFPage_ApplyRedactions",
6532      1
6533    );
6534    Module["_EPDFAnnot_Flatten"] = createExportWrapper(
6535      "EPDFAnnot_Flatten",
6536      2
6537    );
6538    Module["_EPDFAnnot_SetAppearanceFromPage"] = createExportWrapper("EPDFAnnot_SetAppearanceFromPage", 3);
6539    Module["_EPDFAnnot_ExportAppearanceAsDocument"] = createExportWrapper("EPDFAnnot_ExportAppearanceAsDocument", 1);
6540    Module["_EPDFAnnot_ExportMultipleAppearancesAsDocument"] = createExportWrapper("EPDFAnnot_ExportMultipleAppearancesAsDocument", 2);
6541    Module["_EPDFAnnot_SetExtendedRotation"] = createExportWrapper("EPDFAnnot_SetExtendedRotation", 2);
6542    Module["_EPDFAnnot_GetExtendedRotation"] = createExportWrapper("EPDFAnnot_GetExtendedRotation", 2);
6543    Module["_EPDFAnnot_SetUnrotatedRect"] = createExportWrapper(
6544      "EPDFAnnot_SetUnrotatedRect",
6545      2
6546    );
6547    Module["_EPDFAnnot_GetUnrotatedRect"] = createExportWrapper(
6548      "EPDFAnnot_GetUnrotatedRect",
6549      2
6550    );
6551    Module["_EPDFAnnot_GetRect"] = createExportWrapper(
6552      "EPDFAnnot_GetRect",
6553      2
6554    );
6555    Module["_EPDFAnnot_SetAPMatrix"] = createExportWrapper(
6556      "EPDFAnnot_SetAPMatrix",
6557      3
6558    );
6559    Module["_EPDFAnnot_GetAPMatrix"] = createExportWrapper(
6560      "EPDFAnnot_GetAPMatrix",
6561      3
6562    );
6563    Module["_EPDFAnnot_GetAvailableAppearanceModes"] = createExportWrapper("EPDFAnnot_GetAvailableAppearanceModes", 1);
6564    Module["_EPDFAnnot_HasAppearanceStream"] = createExportWrapper("EPDFAnnot_HasAppearanceStream", 2);
6565    Module["_EPDFAnnot_SetMKColor"] = createExportWrapper(
6566      "EPDFAnnot_SetMKColor",
6567      5
6568    );
6569    Module["_EPDFAnnot_GetMKColor"] = createExportWrapper(
6570      "EPDFAnnot_GetMKColor",
6571      5
6572    );
6573    Module["_EPDFAnnot_ClearMKColor"] = createExportWrapper(
6574      "EPDFAnnot_ClearMKColor",
6575      2
6576    );
6577    Module["_EPDFPage_CreateFormField"] = createExportWrapper(
6578      "EPDFPage_CreateFormField",
6579      4
6580    );
6581    Module["_EPDFAnnot_GenerateFormFieldAP"] = createExportWrapper("EPDFAnnot_GenerateFormFieldAP", 1);
6582    Module["_EPDFAnnot_GetButtonExportValue"] = createExportWrapper("EPDFAnnot_GetButtonExportValue", 3);
6583    Module["_EPDFAnnot_GetFormFieldRawValue"] = createExportWrapper("EPDFAnnot_GetFormFieldRawValue", 4);
6584    Module["_EPDFAnnot_SetFormFieldValue"] = createExportWrapper("EPDFAnnot_SetFormFieldValue", 3);
6585    Module["_EPDFAnnot_SetFormFieldName"] = createExportWrapper(
6586      "EPDFAnnot_SetFormFieldName",
6587      3
6588    );
6589    Module["_EPDFAnnot_GetFormFieldObjectNumber"] = createExportWrapper("EPDFAnnot_GetFormFieldObjectNumber", 2);
6590    Module["_EPDFAnnot_ShareFormField"] = createExportWrapper(
6591      "EPDFAnnot_ShareFormField",
6592      3
6593    );
6594    Module["_EPDFAnnot_GetCalloutLineCount"] = createExportWrapper("EPDFAnnot_GetCalloutLineCount", 1);
6595    Module["_EPDFAnnot_GetCalloutLine"] = createExportWrapper(
6596      "EPDFAnnot_GetCalloutLine",
6597      3
6598    );
6599    Module["_EPDFAnnot_SetCalloutLine"] = createExportWrapper(
6600      "EPDFAnnot_SetCalloutLine",
6601      3
6602    );
6603    Module["_EPDFAnnot_SetFormFieldOptions"] = createExportWrapper("EPDFAnnot_SetFormFieldOptions", 4);
6604    Module["_FPDFDoc_GetAttachmentCount"] = createExportWrapper(
6605      "FPDFDoc_GetAttachmentCount",
6606      1
6607    );
6608    Module["_FPDFDoc_AddAttachment"] = createExportWrapper(
6609      "FPDFDoc_AddAttachment",
6610      2
6611    );
6612    Module["_FPDFDoc_GetAttachment"] = createExportWrapper(
6613      "FPDFDoc_GetAttachment",
6614      2
6615    );
6616    Module["_FPDFDoc_DeleteAttachment"] = createExportWrapper(
6617      "FPDFDoc_DeleteAttachment",
6618      2
6619    );
6620    Module["_FPDFAttachment_GetName"] = createExportWrapper(
6621      "FPDFAttachment_GetName",
6622      3
6623    );
6624    Module["_FPDFAttachment_HasKey"] = createExportWrapper(
6625      "FPDFAttachment_HasKey",
6626      2
6627    );
6628    Module["_FPDFAttachment_GetValueType"] = createExportWrapper("FPDFAttachment_GetValueType", 2);
6629    Module["_FPDFAttachment_SetStringValue"] = createExportWrapper("FPDFAttachment_SetStringValue", 3);
6630    Module["_FPDFAttachment_GetStringValue"] = createExportWrapper("FPDFAttachment_GetStringValue", 4);
6631    Module["_FPDFAttachment_SetFile"] = createExportWrapper(
6632      "FPDFAttachment_SetFile",
6633      4
6634    );
6635    Module["_FPDFAttachment_GetFile"] = createExportWrapper(
6636      "FPDFAttachment_GetFile",
6637      4
6638    );
6639    Module["_FPDFAttachment_GetSubtype"] = createExportWrapper(
6640      "FPDFAttachment_GetSubtype",
6641      3
6642    );
6643    Module["_EPDFAttachment_SetSubtype"] = createExportWrapper(
6644      "EPDFAttachment_SetSubtype",
6645      2
6646    );
6647    Module["_EPDFAttachment_SetDescription"] = createExportWrapper("EPDFAttachment_SetDescription", 2);
6648    Module["_EPDFAttachment_GetDescription"] = createExportWrapper("EPDFAttachment_GetDescription", 3);
6649    Module["_EPDFAttachment_GetIntegerValue"] = createExportWrapper("EPDFAttachment_GetIntegerValue", 3);
6650    Module["_FPDFCatalog_IsTagged"] = createExportWrapper(
6651      "FPDFCatalog_IsTagged",
6652      1
6653    );
6654    Module["_FPDFCatalog_GetLanguage"] = createExportWrapper(
6655      "FPDFCatalog_GetLanguage",
6656      3
6657    );
6658    Module["_FPDFCatalog_SetLanguage"] = createExportWrapper(
6659      "FPDFCatalog_SetLanguage",
6660      2
6661    );
6662    Module["_EPDFCatalog_GetLanguage"] = createExportWrapper(
6663      "EPDFCatalog_GetLanguage",
6664      3
6665    );
6666    Module["_FPDFAvail_Create"] = createExportWrapper(
6667      "FPDFAvail_Create",
6668      2
6669    );
6670    Module["_FPDFAvail_Destroy"] = createExportWrapper(
6671      "FPDFAvail_Destroy",
6672      1
6673    );
6674    Module["_FPDFAvail_IsDocAvail"] = createExportWrapper(
6675      "FPDFAvail_IsDocAvail",
6676      2
6677    );
6678    Module["_FPDFAvail_GetDocument"] = createExportWrapper(
6679      "FPDFAvail_GetDocument",
6680      2
6681    );
6682    Module["_FPDFAvail_GetFirstPageNum"] = createExportWrapper(
6683      "FPDFAvail_GetFirstPageNum",
6684      1
6685    );
6686    Module["_FPDFAvail_IsPageAvail"] = createExportWrapper(
6687      "FPDFAvail_IsPageAvail",
6688      3
6689    );
6690    Module["_FPDFAvail_IsFormAvail"] = createExportWrapper(
6691      "FPDFAvail_IsFormAvail",
6692      2
6693    );
6694    Module["_FPDFAvail_IsLinearized"] = createExportWrapper(
6695      "FPDFAvail_IsLinearized",
6696      1
6697    );
6698    Module["_FPDFBookmark_GetFirstChild"] = createExportWrapper(
6699      "FPDFBookmark_GetFirstChild",
6700      2
6701    );
6702    Module["_FPDFBookmark_GetNextSibling"] = createExportWrapper("FPDFBookmark_GetNextSibling", 2);
6703    Module["_FPDFBookmark_GetTitle"] = createExportWrapper(
6704      "FPDFBookmark_GetTitle",
6705      3
6706    );
6707    Module["_FPDFBookmark_GetCount"] = createExportWrapper(
6708      "FPDFBookmark_GetCount",
6709      1
6710    );
6711    Module["_FPDFBookmark_Find"] = createExportWrapper(
6712      "FPDFBookmark_Find",
6713      2
6714    );
6715    Module["_FPDFBookmark_GetDest"] = createExportWrapper(
6716      "FPDFBookmark_GetDest",
6717      2
6718    );
6719    Module["_FPDFBookmark_GetAction"] = createExportWrapper(
6720      "FPDFBookmark_GetAction",
6721      1
6722    );
6723    Module["_FPDFAction_GetType"] = createExportWrapper(
6724      "FPDFAction_GetType",
6725      1
6726    );
6727    Module["_FPDFAction_GetDest"] = createExportWrapper(
6728      "FPDFAction_GetDest",
6729      2
6730    );
6731    Module["_FPDFAction_GetFilePath"] = createExportWrapper(
6732      "FPDFAction_GetFilePath",
6733      3
6734    );
6735    Module["_FPDFAction_GetURIPath"] = createExportWrapper(
6736      "FPDFAction_GetURIPath",
6737      4
6738    );
6739    Module["_FPDFDest_GetDestPageIndex"] = createExportWrapper(
6740      "FPDFDest_GetDestPageIndex",
6741      2
6742    );
6743    Module["_FPDFDest_GetView"] = createExportWrapper(
6744      "FPDFDest_GetView",
6745      3
6746    );
6747    Module["_FPDFDest_GetLocationInPage"] = createExportWrapper(
6748      "FPDFDest_GetLocationInPage",
6749      7
6750    );
6751    Module["_FPDFLink_GetLinkAtPoint"] = createExportWrapper(
6752      "FPDFLink_GetLinkAtPoint",
6753      3
6754    );
6755    Module["_FPDFLink_GetLinkZOrderAtPoint"] = createExportWrapper("FPDFLink_GetLinkZOrderAtPoint", 3);
6756    Module["_FPDFLink_GetDest"] = createExportWrapper(
6757      "FPDFLink_GetDest",
6758      2
6759    );
6760    Module["_FPDFLink_GetAction"] = createExportWrapper(
6761      "FPDFLink_GetAction",
6762      1
6763    );
6764    Module["_FPDFLink_Enumerate"] = createExportWrapper(
6765      "FPDFLink_Enumerate",
6766      3
6767    );
6768    Module["_FPDFLink_GetAnnot"] = createExportWrapper(
6769      "FPDFLink_GetAnnot",
6770      2
6771    );
6772    Module["_FPDFLink_GetAnnotRect"] = createExportWrapper(
6773      "FPDFLink_GetAnnotRect",
6774      2
6775    );
6776    Module["_FPDFLink_CountQuadPoints"] = createExportWrapper(
6777      "FPDFLink_CountQuadPoints",
6778      1
6779    );
6780    Module["_FPDFLink_GetQuadPoints"] = createExportWrapper(
6781      "FPDFLink_GetQuadPoints",
6782      3
6783    );
6784    Module["_FPDF_GetPageAAction"] = createExportWrapper(
6785      "FPDF_GetPageAAction",
6786      2
6787    );
6788    Module["_FPDF_GetFileIdentifier"] = createExportWrapper(
6789      "FPDF_GetFileIdentifier",
6790      4
6791    );
6792    Module["_FPDF_GetMetaText"] = createExportWrapper(
6793      "FPDF_GetMetaText",
6794      4
6795    );
6796    Module["_FPDF_GetPageLabel"] = createExportWrapper(
6797      "FPDF_GetPageLabel",
6798      4
6799    );
6800    Module["_EPDF_SetMetaText"] = createExportWrapper(
6801      "EPDF_SetMetaText",
6802      3
6803    );
6804    Module["_EPDF_HasMetaText"] = createExportWrapper(
6805      "EPDF_HasMetaText",
6806      2
6807    );
6808    Module["_EPDF_GetMetaTrapped"] = createExportWrapper(
6809      "EPDF_GetMetaTrapped",
6810      1
6811    );
6812    Module["_EPDF_SetMetaTrapped"] = createExportWrapper(
6813      "EPDF_SetMetaTrapped",
6814      2
6815    );
6816    Module["_EPDF_GetMetaKeyCount"] = createExportWrapper(
6817      "EPDF_GetMetaKeyCount",
6818      2
6819    );
6820    Module["_EPDF_GetMetaKeyName"] = createExportWrapper(
6821      "EPDF_GetMetaKeyName",
6822      5
6823    );
6824    Module["_FPDFPageObj_NewImageObj"] = createExportWrapper(
6825      "FPDFPageObj_NewImageObj",
6826      1
6827    );
6828    Module["_FPDFImageObj_LoadJpegFile"] = createExportWrapper(
6829      "FPDFImageObj_LoadJpegFile",
6830      4
6831    );
6832    Module["_FPDFImageObj_LoadJpegFileInline"] = createExportWrapper("FPDFImageObj_LoadJpegFileInline", 4);
6833    Module["_FPDFImageObj_SetMatrix"] = createExportWrapper(
6834      "FPDFImageObj_SetMatrix",
6835      7
6836    );
6837    Module["_FPDFImageObj_SetBitmap"] = createExportWrapper(
6838      "FPDFImageObj_SetBitmap",
6839      4
6840    );
6841    Module["_FPDFImageObj_GetBitmap"] = createExportWrapper(
6842      "FPDFImageObj_GetBitmap",
6843      1
6844    );
6845    Module["_FPDFImageObj_GetRenderedBitmap"] = createExportWrapper("FPDFImageObj_GetRenderedBitmap", 3);
6846    Module["_FPDFImageObj_GetImageDataDecoded"] = createExportWrapper("FPDFImageObj_GetImageDataDecoded", 3);
6847    Module["_FPDFImageObj_GetImageDataRaw"] = createExportWrapper("FPDFImageObj_GetImageDataRaw", 3);
6848    Module["_FPDFImageObj_GetImageFilterCount"] = createExportWrapper("FPDFImageObj_GetImageFilterCount", 1);
6849    Module["_FPDFImageObj_GetImageFilter"] = createExportWrapper("FPDFImageObj_GetImageFilter", 4);
6850    Module["_FPDFImageObj_GetImageMetadata"] = createExportWrapper("FPDFImageObj_GetImageMetadata", 3);
6851    Module["_FPDFImageObj_GetImagePixelSize"] = createExportWrapper("FPDFImageObj_GetImagePixelSize", 3);
6852    Module["_FPDFImageObj_GetIccProfileDataDecoded"] = createExportWrapper("FPDFImageObj_GetIccProfileDataDecoded", 5);
6853    Module["_EPDFImageObj_SetPng"] = createExportWrapper(
6854      "EPDFImageObj_SetPng",
6855      5
6856    );
6857    Module["_EPDFImageObj_SetJpeg"] = createExportWrapper(
6858      "EPDFImageObj_SetJpeg",
6859      5
6860    );
6861    Module["_FPDF_CreateNewDocument"] = createExportWrapper(
6862      "FPDF_CreateNewDocument",
6863      0
6864    );
6865    Module["_FPDFPage_Delete"] = createExportWrapper("FPDFPage_Delete", 2);
6866    Module["_FPDF_MovePages"] = createExportWrapper("FPDF_MovePages", 4);
6867    Module["_FPDFPage_New"] = createExportWrapper("FPDFPage_New", 4);
6868    Module["_FPDFPage_GetRotation"] = createExportWrapper(
6869      "FPDFPage_GetRotation",
6870      1
6871    );
6872    Module["_FPDFPage_InsertObject"] = createExportWrapper(
6873      "FPDFPage_InsertObject",
6874      2
6875    );
6876    Module["_FPDFPage_InsertObjectAtIndex"] = createExportWrapper("FPDFPage_InsertObjectAtIndex", 3);
6877    Module["_FPDFPage_RemoveObject"] = createExportWrapper(
6878      "FPDFPage_RemoveObject",
6879      2
6880    );
6881    Module["_FPDFPage_CountObjects"] = createExportWrapper(
6882      "FPDFPage_CountObjects",
6883      1
6884    );
6885    Module["_FPDFPage_GetObject"] = createExportWrapper(
6886      "FPDFPage_GetObject",
6887      2
6888    );
6889    Module["_FPDFPage_HasTransparency"] = createExportWrapper(
6890      "FPDFPage_HasTransparency",
6891      1
6892    );
6893    Module["_FPDFPageObj_Destroy"] = createExportWrapper(
6894      "FPDFPageObj_Destroy",
6895      1
6896    );
6897    Module["_FPDFPageObj_GetMarkedContentID"] = createExportWrapper("FPDFPageObj_GetMarkedContentID", 1);
6898    Module["_FPDFPageObj_CountMarks"] = createExportWrapper(
6899      "FPDFPageObj_CountMarks",
6900      1
6901    );
6902    Module["_FPDFPageObj_GetMark"] = createExportWrapper(
6903      "FPDFPageObj_GetMark",
6904      2
6905    );
6906    Module["_FPDFPageObj_AddMark"] = createExportWrapper(
6907      "FPDFPageObj_AddMark",
6908      2
6909    );
6910    Module["_FPDFPageObj_RemoveMark"] = createExportWrapper(
6911      "FPDFPageObj_RemoveMark",
6912      2
6913    );
6914    Module["_FPDFPageObjMark_GetName"] = createExportWrapper(
6915      "FPDFPageObjMark_GetName",
6916      4
6917    );
6918    Module["_FPDFPageObjMark_CountParams"] = createExportWrapper("FPDFPageObjMark_CountParams", 1);
6919    Module["_FPDFPageObjMark_GetParamKey"] = createExportWrapper("FPDFPageObjMark_GetParamKey", 5);
6920    Module["_FPDFPageObjMark_GetParamValueType"] = createExportWrapper("FPDFPageObjMark_GetParamValueType", 2);
6921    Module["_FPDFPageObjMark_GetParamIntValue"] = createExportWrapper("FPDFPageObjMark_GetParamIntValue", 3);
6922    Module["_FPDFPageObjMark_GetParamFloatValue"] = createExportWrapper("FPDFPageObjMark_GetParamFloatValue", 3);
6923    Module["_FPDFPageObjMark_GetParamStringValue"] = createExportWrapper("FPDFPageObjMark_GetParamStringValue", 5);
6924    Module["_FPDFPageObjMark_GetParamBlobValue"] = createExportWrapper("FPDFPageObjMark_GetParamBlobValue", 5);
6925    Module["_FPDFPageObj_HasTransparency"] = createExportWrapper("FPDFPageObj_HasTransparency", 1);
6926    Module["_FPDFPageObjMark_SetIntParam"] = createExportWrapper("FPDFPageObjMark_SetIntParam", 5);
6927    Module["_FPDFPageObjMark_SetFloatParam"] = createExportWrapper("FPDFPageObjMark_SetFloatParam", 5);
6928    Module["_FPDFPageObjMark_SetStringParam"] = createExportWrapper("FPDFPageObjMark_SetStringParam", 5);
6929    Module["_FPDFPageObjMark_SetBlobParam"] = createExportWrapper("FPDFPageObjMark_SetBlobParam", 6);
6930    Module["_FPDFPageObjMark_RemoveParam"] = createExportWrapper("FPDFPageObjMark_RemoveParam", 3);
6931    Module["_FPDFPageObj_GetType"] = createExportWrapper(
6932      "FPDFPageObj_GetType",
6933      1
6934    );
6935    Module["_FPDFPageObj_GetIsActive"] = createExportWrapper(
6936      "FPDFPageObj_GetIsActive",
6937      2
6938    );
6939    Module["_FPDFPageObj_SetIsActive"] = createExportWrapper(
6940      "FPDFPageObj_SetIsActive",
6941      2
6942    );
6943    Module["_FPDFPage_GenerateContent"] = createExportWrapper(
6944      "FPDFPage_GenerateContent",
6945      1
6946    );
6947    Module["_FPDFPageObj_Transform"] = createExportWrapper(
6948      "FPDFPageObj_Transform",
6949      7
6950    );
6951    Module["_FPDFPageObj_TransformF"] = createExportWrapper(
6952      "FPDFPageObj_TransformF",
6953      2
6954    );
6955    Module["_FPDFPageObj_GetMatrix"] = createExportWrapper(
6956      "FPDFPageObj_GetMatrix",
6957      2
6958    );
6959    Module["_FPDFPageObj_SetMatrix"] = createExportWrapper(
6960      "FPDFPageObj_SetMatrix",
6961      2
6962    );
6963    Module["_FPDFPageObj_SetBlendMode"] = createExportWrapper(
6964      "FPDFPageObj_SetBlendMode",
6965      2
6966    );
6967    Module["_FPDFPage_TransformAnnots"] = createExportWrapper(
6968      "FPDFPage_TransformAnnots",
6969      7
6970    );
6971    Module["_FPDFPage_SetRotation"] = createExportWrapper(
6972      "FPDFPage_SetRotation",
6973      2
6974    );
6975    Module["_FPDFPageObj_SetFillColor"] = createExportWrapper(
6976      "FPDFPageObj_SetFillColor",
6977      5
6978    );
6979    Module["_FPDFPageObj_GetFillColor"] = createExportWrapper(
6980      "FPDFPageObj_GetFillColor",
6981      5
6982    );
6983    Module["_FPDFPageObj_GetBounds"] = createExportWrapper(
6984      "FPDFPageObj_GetBounds",
6985      5
6986    );
6987    Module["_FPDFPageObj_GetRotatedBounds"] = createExportWrapper("FPDFPageObj_GetRotatedBounds", 2);
6988    Module["_FPDFPageObj_SetStrokeColor"] = createExportWrapper(
6989      "FPDFPageObj_SetStrokeColor",
6990      5
6991    );
6992    Module["_FPDFPageObj_GetStrokeColor"] = createExportWrapper(
6993      "FPDFPageObj_GetStrokeColor",
6994      5
6995    );
6996    Module["_FPDFPageObj_SetStrokeWidth"] = createExportWrapper(
6997      "FPDFPageObj_SetStrokeWidth",
6998      2
6999    );
7000    Module["_FPDFPageObj_GetStrokeWidth"] = createExportWrapper(
7001      "FPDFPageObj_GetStrokeWidth",
7002      2
7003    );
7004    Module["_FPDFPageObj_GetLineJoin"] = createExportWrapper(
7005      "FPDFPageObj_GetLineJoin",
7006      1
7007    );
7008    Module["_FPDFPageObj_SetLineJoin"] = createExportWrapper(
7009      "FPDFPageObj_SetLineJoin",
7010      2
7011    );
7012    Module["_FPDFPageObj_GetLineCap"] = createExportWrapper(
7013      "FPDFPageObj_GetLineCap",
7014      1
7015    );
7016    Module["_FPDFPageObj_SetLineCap"] = createExportWrapper(
7017      "FPDFPageObj_SetLineCap",
7018      2
7019    );
7020    Module["_FPDFPageObj_GetDashPhase"] = createExportWrapper(
7021      "FPDFPageObj_GetDashPhase",
7022      2
7023    );
7024    Module["_FPDFPageObj_SetDashPhase"] = createExportWrapper(
7025      "FPDFPageObj_SetDashPhase",
7026      2
7027    );
7028    Module["_FPDFPageObj_GetDashCount"] = createExportWrapper(
7029      "FPDFPageObj_GetDashCount",
7030      1
7031    );
7032    Module["_FPDFPageObj_GetDashArray"] = createExportWrapper(
7033      "FPDFPageObj_GetDashArray",
7034      3
7035    );
7036    Module["_FPDFPageObj_SetDashArray"] = createExportWrapper(
7037      "FPDFPageObj_SetDashArray",
7038      4
7039    );
7040    Module["_FPDFFormObj_CountObjects"] = createExportWrapper(
7041      "FPDFFormObj_CountObjects",
7042      1
7043    );
7044    Module["_FPDFFormObj_GetObject"] = createExportWrapper(
7045      "FPDFFormObj_GetObject",
7046      2
7047    );
7048    Module["_FPDFFormObj_RemoveObject"] = createExportWrapper(
7049      "FPDFFormObj_RemoveObject",
7050      2
7051    );
7052    Module["_FPDFPageObj_CreateNewPath"] = createExportWrapper(
7053      "FPDFPageObj_CreateNewPath",
7054      2
7055    );
7056    Module["_FPDFPageObj_CreateNewRect"] = createExportWrapper(
7057      "FPDFPageObj_CreateNewRect",
7058      4
7059    );
7060    Module["_FPDFPath_CountSegments"] = createExportWrapper(
7061      "FPDFPath_CountSegments",
7062      1
7063    );
7064    Module["_FPDFPath_GetPathSegment"] = createExportWrapper(
7065      "FPDFPath_GetPathSegment",
7066      2
7067    );
7068    Module["_FPDFPath_MoveTo"] = createExportWrapper("FPDFPath_MoveTo", 3);
7069    Module["_FPDFPath_LineTo"] = createExportWrapper("FPDFPath_LineTo", 3);
7070    Module["_FPDFPath_BezierTo"] = createExportWrapper(
7071      "FPDFPath_BezierTo",
7072      7
7073    );
7074    Module["_FPDFPath_Close"] = createExportWrapper("FPDFPath_Close", 1);
7075    Module["_FPDFPath_SetDrawMode"] = createExportWrapper(
7076      "FPDFPath_SetDrawMode",
7077      3
7078    );
7079    Module["_FPDFPath_GetDrawMode"] = createExportWrapper(
7080      "FPDFPath_GetDrawMode",
7081      3
7082    );
7083    Module["_FPDFPathSegment_GetPoint"] = createExportWrapper(
7084      "FPDFPathSegment_GetPoint",
7085      3
7086    );
7087    Module["_FPDFPathSegment_GetType"] = createExportWrapper(
7088      "FPDFPathSegment_GetType",
7089      1
7090    );
7091    Module["_FPDFPathSegment_GetClose"] = createExportWrapper(
7092      "FPDFPathSegment_GetClose",
7093      1
7094    );
7095    Module["_FPDFPageObj_NewTextObj"] = createExportWrapper(
7096      "FPDFPageObj_NewTextObj",
7097      3
7098    );
7099    Module["_FPDFText_SetText"] = createExportWrapper(
7100      "FPDFText_SetText",
7101      2
7102    );
7103    Module["_FPDFText_SetCharcodes"] = createExportWrapper(
7104      "FPDFText_SetCharcodes",
7105      3
7106    );
7107    Module["_FPDFText_LoadFont"] = createExportWrapper(
7108      "FPDFText_LoadFont",
7109      5
7110    );
7111    Module["_FPDFText_LoadStandardFont"] = createExportWrapper(
7112      "FPDFText_LoadStandardFont",
7113      2
7114    );
7115    Module["_FPDFText_LoadCidType2Font"] = createExportWrapper(
7116      "FPDFText_LoadCidType2Font",
7117      6
7118    );
7119    Module["_FPDFTextObj_GetFontSize"] = createExportWrapper(
7120      "FPDFTextObj_GetFontSize",
7121      2
7122    );
7123    Module["_FPDFTextObj_GetText"] = createExportWrapper(
7124      "FPDFTextObj_GetText",
7125      4
7126    );
7127    Module["_FPDFTextObj_GetRenderedBitmap"] = createExportWrapper("FPDFTextObj_GetRenderedBitmap", 4);
7128    Module["_FPDFFont_Close"] = createExportWrapper("FPDFFont_Close", 1);
7129    Module["_FPDFPageObj_CreateTextObj"] = createExportWrapper(
7130      "FPDFPageObj_CreateTextObj",
7131      3
7132    );
7133    Module["_FPDFTextObj_GetTextRenderMode"] = createExportWrapper("FPDFTextObj_GetTextRenderMode", 1);
7134    Module["_FPDFTextObj_SetTextRenderMode"] = createExportWrapper("FPDFTextObj_SetTextRenderMode", 2);
7135    Module["_FPDFTextObj_GetFont"] = createExportWrapper(
7136      "FPDFTextObj_GetFont",
7137      1
7138    );
7139    Module["_FPDFFont_GetBaseFontName"] = createExportWrapper(
7140      "FPDFFont_GetBaseFontName",
7141      3
7142    );
7143    Module["_FPDFFont_GetFamilyName"] = createExportWrapper(
7144      "FPDFFont_GetFamilyName",
7145      3
7146    );
7147    Module["_FPDFFont_GetFontData"] = createExportWrapper(
7148      "FPDFFont_GetFontData",
7149      4
7150    );
7151    Module["_FPDFFont_GetIsEmbedded"] = createExportWrapper(
7152      "FPDFFont_GetIsEmbedded",
7153      1
7154    );
7155    Module["_FPDFFont_GetFlags"] = createExportWrapper(
7156      "FPDFFont_GetFlags",
7157      1
7158    );
7159    Module["_FPDFFont_GetWeight"] = createExportWrapper(
7160      "FPDFFont_GetWeight",
7161      1
7162    );
7163    Module["_FPDFFont_GetItalicAngle"] = createExportWrapper(
7164      "FPDFFont_GetItalicAngle",
7165      2
7166    );
7167    Module["_FPDFFont_GetAscent"] = createExportWrapper(
7168      "FPDFFont_GetAscent",
7169      3
7170    );
7171    Module["_FPDFFont_GetDescent"] = createExportWrapper(
7172      "FPDFFont_GetDescent",
7173      3
7174    );
7175    Module["_FPDFFont_GetGlyphWidth"] = createExportWrapper(
7176      "FPDFFont_GetGlyphWidth",
7177      4
7178    );
7179    Module["_FPDFFont_GetGlyphPath"] = createExportWrapper(
7180      "FPDFFont_GetGlyphPath",
7181      3
7182    );
7183    Module["_FPDFGlyphPath_CountGlyphSegments"] = createExportWrapper("FPDFGlyphPath_CountGlyphSegments", 1);
7184    Module["_FPDFGlyphPath_GetGlyphPathSegment"] = createExportWrapper("FPDFGlyphPath_GetGlyphPathSegment", 2);
7185    Module["_EPDFText_RedactInRect"] = createExportWrapper(
7186      "EPDFText_RedactInRect",
7187      4
7188    );
7189    Module["_EPDFText_RedactInQuads"] = createExportWrapper(
7190      "EPDFText_RedactInQuads",
7191      5
7192    );
7193    Module["_FPDFDoc_GetPageMode"] = createExportWrapper(
7194      "FPDFDoc_GetPageMode",
7195      1
7196    );
7197    Module["_FPDFPage_Flatten"] = createExportWrapper(
7198      "FPDFPage_Flatten",
7199      2
7200    );
7201    Module["_FPDFPage_HasFormFieldAtPoint"] = createExportWrapper("FPDFPage_HasFormFieldAtPoint", 4);
7202    Module["_FPDFPage_FormFieldZOrderAtPoint"] = createExportWrapper("FPDFPage_FormFieldZOrderAtPoint", 4);
7203    Module["_malloc"] = createExportWrapper("malloc", 1);
7204    Module["_free"] = createExportWrapper("free", 1);
7205    Module["_FORM_OnMouseMove"] = createExportWrapper(
7206      "FORM_OnMouseMove",
7207      5
7208    );
7209    Module["_FORM_OnMouseWheel"] = createExportWrapper(
7210      "FORM_OnMouseWheel",
7211      6
7212    );
7213    Module["_FORM_OnFocus"] = createExportWrapper("FORM_OnFocus", 5);
7214    Module["_FORM_OnLButtonDown"] = createExportWrapper(
7215      "FORM_OnLButtonDown",
7216      5
7217    );
7218    Module["_FORM_OnLButtonUp"] = createExportWrapper(
7219      "FORM_OnLButtonUp",
7220      5
7221    );
7222    Module["_FORM_OnLButtonDoubleClick"] = createExportWrapper(
7223      "FORM_OnLButtonDoubleClick",
7224      5
7225    );
7226    Module["_FORM_OnRButtonDown"] = createExportWrapper(
7227      "FORM_OnRButtonDown",
7228      5
7229    );
7230    Module["_FORM_OnRButtonUp"] = createExportWrapper(
7231      "FORM_OnRButtonUp",
7232      5
7233    );
7234    Module["_FORM_OnKeyDown"] = createExportWrapper("FORM_OnKeyDown", 4);
7235    Module["_FORM_OnKeyUp"] = createExportWrapper("FORM_OnKeyUp", 4);
7236    Module["_FORM_OnChar"] = createExportWrapper("FORM_OnChar", 4);
7237    Module["_FORM_GetFocusedText"] = createExportWrapper(
7238      "FORM_GetFocusedText",
7239      4
7240    );
7241    Module["_FORM_GetSelectedText"] = createExportWrapper(
7242      "FORM_GetSelectedText",
7243      4
7244    );
7245    Module["_FORM_ReplaceAndKeepSelection"] = createExportWrapper("FORM_ReplaceAndKeepSelection", 3);
7246    Module["_FORM_ReplaceSelection"] = createExportWrapper(
7247      "FORM_ReplaceSelection",
7248      3
7249    );
7250    Module["_FORM_SelectAllText"] = createExportWrapper(
7251      "FORM_SelectAllText",
7252      2
7253    );
7254    Module["_FORM_CanUndo"] = createExportWrapper("FORM_CanUndo", 2);
7255    Module["_FORM_CanRedo"] = createExportWrapper("FORM_CanRedo", 2);
7256    Module["_FORM_Undo"] = createExportWrapper("FORM_Undo", 2);
7257    Module["_FORM_Redo"] = createExportWrapper("FORM_Redo", 2);
7258    Module["_FORM_ForceToKillFocus"] = createExportWrapper(
7259      "FORM_ForceToKillFocus",
7260      1
7261    );
7262    Module["_FORM_GetFocusedAnnot"] = createExportWrapper(
7263      "FORM_GetFocusedAnnot",
7264      3
7265    );
7266    Module["_FORM_SetFocusedAnnot"] = createExportWrapper(
7267      "FORM_SetFocusedAnnot",
7268      2
7269    );
7270    Module["_FPDF_FFLDraw"] = createExportWrapper("FPDF_FFLDraw", 9);
7271    Module["_FPDF_SetFormFieldHighlightColor"] = createExportWrapper("FPDF_SetFormFieldHighlightColor", 3);
7272    Module["_FPDF_SetFormFieldHighlightAlpha"] = createExportWrapper("FPDF_SetFormFieldHighlightAlpha", 2);
7273    Module["_FPDF_RemoveFormFieldHighlight"] = createExportWrapper("FPDF_RemoveFormFieldHighlight", 1);
7274    Module["_FORM_OnAfterLoadPage"] = createExportWrapper(
7275      "FORM_OnAfterLoadPage",
7276      2
7277    );
7278    Module["_FORM_OnBeforeClosePage"] = createExportWrapper(
7279      "FORM_OnBeforeClosePage",
7280      2
7281    );
7282    Module["_FORM_DoDocumentJSAction"] = createExportWrapper(
7283      "FORM_DoDocumentJSAction",
7284      1
7285    );
7286    Module["_FORM_DoDocumentOpenAction"] = createExportWrapper(
7287      "FORM_DoDocumentOpenAction",
7288      1
7289    );
7290    Module["_FORM_DoDocumentAAction"] = createExportWrapper(
7291      "FORM_DoDocumentAAction",
7292      2
7293    );
7294    Module["_FORM_DoPageAAction"] = createExportWrapper(
7295      "FORM_DoPageAAction",
7296      3
7297    );
7298    Module["_FORM_SetIndexSelected"] = createExportWrapper(
7299      "FORM_SetIndexSelected",
7300      4
7301    );
7302    Module["_FORM_IsIndexSelected"] = createExportWrapper(
7303      "FORM_IsIndexSelected",
7304      3
7305    );
7306    Module["_FPDFDoc_GetJavaScriptActionCount"] = createExportWrapper("FPDFDoc_GetJavaScriptActionCount", 1);
7307    Module["_FPDFDoc_GetJavaScriptAction"] = createExportWrapper("FPDFDoc_GetJavaScriptAction", 2);
7308    Module["_FPDFDoc_CloseJavaScriptAction"] = createExportWrapper("FPDFDoc_CloseJavaScriptAction", 1);
7309    Module["_FPDFJavaScriptAction_GetName"] = createExportWrapper("FPDFJavaScriptAction_GetName", 3);
7310    Module["_FPDFJavaScriptAction_GetScript"] = createExportWrapper("FPDFJavaScriptAction_GetScript", 3);
7311    Module["_FPDF_ImportPagesByIndex"] = createExportWrapper(
7312      "FPDF_ImportPagesByIndex",
7313      5
7314    );
7315    Module["_FPDF_ImportPages"] = createExportWrapper(
7316      "FPDF_ImportPages",
7317      4
7318    );
7319    Module["_FPDF_ImportNPagesToOne"] = createExportWrapper(
7320      "FPDF_ImportNPagesToOne",
7321      5
7322    );
7323    Module["_FPDF_NewXObjectFromPage"] = createExportWrapper(
7324      "FPDF_NewXObjectFromPage",
7325      3
7326    );
7327    Module["_FPDF_CloseXObject"] = createExportWrapper(
7328      "FPDF_CloseXObject",
7329      1
7330    );
7331    Module["_FPDF_NewFormObjectFromXObject"] = createExportWrapper("FPDF_NewFormObjectFromXObject", 1);
7332    Module["_FPDF_CopyViewerPreferences"] = createExportWrapper(
7333      "FPDF_CopyViewerPreferences",
7334      2
7335    );
7336    Module["_FPDF_RenderPageBitmapWithColorScheme_Start"] = createExportWrapper("FPDF_RenderPageBitmapWithColorScheme_Start", 10);
7337    Module["_FPDF_RenderPageBitmap_Start"] = createExportWrapper("FPDF_RenderPageBitmap_Start", 9);
7338    Module["_FPDF_RenderPage_Continue"] = createExportWrapper(
7339      "FPDF_RenderPage_Continue",
7340      2
7341    );
7342    Module["_FPDF_RenderPage_Close"] = createExportWrapper(
7343      "FPDF_RenderPage_Close",
7344      1
7345    );
7346    Module["_FPDF_SaveWithVersion"] = createExportWrapper(
7347      "FPDF_SaveWithVersion",
7348      4
7349    );
7350    Module["_FPDFText_GetCharIndexFromTextIndex"] = createExportWrapper("FPDFText_GetCharIndexFromTextIndex", 2);
7351    Module["_FPDFText_GetTextIndexFromCharIndex"] = createExportWrapper("FPDFText_GetTextIndexFromCharIndex", 2);
7352    Module["_FPDF_GetSignatureCount"] = createExportWrapper(
7353      "FPDF_GetSignatureCount",
7354      1
7355    );
7356    Module["_FPDF_GetSignatureObject"] = createExportWrapper(
7357      "FPDF_GetSignatureObject",
7358      2
7359    );
7360    Module["_FPDFSignatureObj_GetContents"] = createExportWrapper("FPDFSignatureObj_GetContents", 3);
7361    Module["_FPDFSignatureObj_GetByteRange"] = createExportWrapper("FPDFSignatureObj_GetByteRange", 3);
7362    Module["_FPDFSignatureObj_GetSubFilter"] = createExportWrapper("FPDFSignatureObj_GetSubFilter", 3);
7363    Module["_FPDFSignatureObj_GetReason"] = createExportWrapper(
7364      "FPDFSignatureObj_GetReason",
7365      3
7366    );
7367    Module["_FPDFSignatureObj_GetTime"] = createExportWrapper(
7368      "FPDFSignatureObj_GetTime",
7369      3
7370    );
7371    Module["_FPDFSignatureObj_GetDocMDPPermission"] = createExportWrapper("FPDFSignatureObj_GetDocMDPPermission", 1);
7372    Module["_FPDF_StructTree_GetForPage"] = createExportWrapper(
7373      "FPDF_StructTree_GetForPage",
7374      1
7375    );
7376    Module["_FPDF_StructTree_Close"] = createExportWrapper(
7377      "FPDF_StructTree_Close",
7378      1
7379    );
7380    Module["_FPDF_StructTree_CountChildren"] = createExportWrapper("FPDF_StructTree_CountChildren", 1);
7381    Module["_FPDF_StructTree_GetChildAtIndex"] = createExportWrapper("FPDF_StructTree_GetChildAtIndex", 2);
7382    Module["_FPDF_StructElement_GetAltText"] = createExportWrapper("FPDF_StructElement_GetAltText", 3);
7383    Module["_FPDF_StructElement_GetActualText"] = createExportWrapper("FPDF_StructElement_GetActualText", 3);
7384    Module["_FPDF_StructElement_GetID"] = createExportWrapper(
7385      "FPDF_StructElement_GetID",
7386      3
7387    );
7388    Module["_FPDF_StructElement_GetLang"] = createExportWrapper(
7389      "FPDF_StructElement_GetLang",
7390      3
7391    );
7392    Module["_FPDF_StructElement_GetAttributeCount"] = createExportWrapper("FPDF_StructElement_GetAttributeCount", 1);
7393    Module["_FPDF_StructElement_GetAttributeAtIndex"] = createExportWrapper("FPDF_StructElement_GetAttributeAtIndex", 2);
7394    Module["_FPDF_StructElement_GetStringAttribute"] = createExportWrapper("FPDF_StructElement_GetStringAttribute", 4);
7395    Module["_FPDF_StructElement_GetMarkedContentID"] = createExportWrapper("FPDF_StructElement_GetMarkedContentID", 1);
7396    Module["_FPDF_StructElement_GetType"] = createExportWrapper(
7397      "FPDF_StructElement_GetType",
7398      3
7399    );
7400    Module["_FPDF_StructElement_GetObjType"] = createExportWrapper("FPDF_StructElement_GetObjType", 3);
7401    Module["_FPDF_StructElement_GetTitle"] = createExportWrapper("FPDF_StructElement_GetTitle", 3);
7402    Module["_FPDF_StructElement_CountChildren"] = createExportWrapper("FPDF_StructElement_CountChildren", 1);
7403    Module["_FPDF_StructElement_GetChildAtIndex"] = createExportWrapper("FPDF_StructElement_GetChildAtIndex", 2);
7404    Module["_FPDF_StructElement_GetChildMarkedContentID"] = createExportWrapper("FPDF_StructElement_GetChildMarkedContentID", 2);
7405    Module["_FPDF_StructElement_GetParent"] = createExportWrapper("FPDF_StructElement_GetParent", 1);
7406    Module["_FPDF_StructElement_Attr_GetCount"] = createExportWrapper("FPDF_StructElement_Attr_GetCount", 1);
7407    Module["_FPDF_StructElement_Attr_GetName"] = createExportWrapper("FPDF_StructElement_Attr_GetName", 5);
7408    Module["_FPDF_StructElement_Attr_GetValue"] = createExportWrapper("FPDF_StructElement_Attr_GetValue", 2);
7409    Module["_FPDF_StructElement_Attr_GetType"] = createExportWrapper("FPDF_StructElement_Attr_GetType", 1);
7410    Module["_FPDF_StructElement_Attr_GetBooleanValue"] = createExportWrapper("FPDF_StructElement_Attr_GetBooleanValue", 2);
7411    Module["_FPDF_StructElement_Attr_GetNumberValue"] = createExportWrapper("FPDF_StructElement_Attr_GetNumberValue", 2);
7412    Module["_FPDF_StructElement_Attr_GetStringValue"] = createExportWrapper("FPDF_StructElement_Attr_GetStringValue", 4);
7413    Module["_FPDF_StructElement_Attr_GetBlobValue"] = createExportWrapper("FPDF_StructElement_Attr_GetBlobValue", 4);
7414    Module["_FPDF_StructElement_Attr_CountChildren"] = createExportWrapper("FPDF_StructElement_Attr_CountChildren", 1);
7415    Module["_FPDF_StructElement_Attr_GetChildAtIndex"] = createExportWrapper("FPDF_StructElement_Attr_GetChildAtIndex", 2);
7416    Module["_FPDF_StructElement_GetMarkedContentIdCount"] = createExportWrapper("FPDF_StructElement_GetMarkedContentIdCount", 1);
7417    Module["_FPDF_StructElement_GetMarkedContentIdAtIndex"] = createExportWrapper("FPDF_StructElement_GetMarkedContentIdAtIndex", 2);
7418    Module["_FPDF_AddInstalledFont"] = createExportWrapper(
7419      "FPDF_AddInstalledFont",
7420      3
7421    );
7422    Module["_FPDF_SetSystemFontInfo"] = createExportWrapper(
7423      "FPDF_SetSystemFontInfo",
7424      1
7425    );
7426    Module["_FPDF_GetDefaultTTFMap"] = createExportWrapper(
7427      "FPDF_GetDefaultTTFMap",
7428      0
7429    );
7430    Module["_FPDF_GetDefaultTTFMapCount"] = createExportWrapper(
7431      "FPDF_GetDefaultTTFMapCount",
7432      0
7433    );
7434    Module["_FPDF_GetDefaultTTFMapEntry"] = createExportWrapper(
7435      "FPDF_GetDefaultTTFMapEntry",
7436      1
7437    );
7438    Module["_FPDF_GetDefaultSystemFontInfo"] = createExportWrapper("FPDF_GetDefaultSystemFontInfo", 0);
7439    Module["_FPDF_FreeDefaultSystemFontInfo"] = createExportWrapper("FPDF_FreeDefaultSystemFontInfo", 1);
7440    Module["_FPDFText_LoadPage"] = createExportWrapper(
7441      "FPDFText_LoadPage",
7442      1
7443    );
7444    Module["_FPDFText_ClosePage"] = createExportWrapper(
7445      "FPDFText_ClosePage",
7446      1
7447    );
7448    Module["_FPDFText_CountChars"] = createExportWrapper(
7449      "FPDFText_CountChars",
7450      1
7451    );
7452    Module["_FPDFText_GetUnicode"] = createExportWrapper(
7453      "FPDFText_GetUnicode",
7454      2
7455    );
7456    Module["_FPDFText_GetTextObject"] = createExportWrapper(
7457      "FPDFText_GetTextObject",
7458      2
7459    );
7460    Module["_FPDFText_IsGenerated"] = createExportWrapper(
7461      "FPDFText_IsGenerated",
7462      2
7463    );
7464    Module["_FPDFText_IsHyphen"] = createExportWrapper(
7465      "FPDFText_IsHyphen",
7466      2
7467    );
7468    Module["_FPDFText_HasUnicodeMapError"] = createExportWrapper("FPDFText_HasUnicodeMapError", 2);
7469    Module["_FPDFText_GetFontSize"] = createExportWrapper(
7470      "FPDFText_GetFontSize",
7471      2
7472    );
7473    Module["_FPDFText_GetFontInfo"] = createExportWrapper(
7474      "FPDFText_GetFontInfo",
7475      5
7476    );
7477    Module["_FPDFText_GetFontWeight"] = createExportWrapper(
7478      "FPDFText_GetFontWeight",
7479      2
7480    );
7481    Module["_FPDFText_GetFillColor"] = createExportWrapper(
7482      "FPDFText_GetFillColor",
7483      6
7484    );
7485    Module["_FPDFText_GetStrokeColor"] = createExportWrapper(
7486      "FPDFText_GetStrokeColor",
7487      6
7488    );
7489    Module["_FPDFText_GetCharAngle"] = createExportWrapper(
7490      "FPDFText_GetCharAngle",
7491      2
7492    );
7493    Module["_FPDFText_GetCharBox"] = createExportWrapper(
7494      "FPDFText_GetCharBox",
7495      6
7496    );
7497    Module["_FPDFText_GetLooseCharBox"] = createExportWrapper(
7498      "FPDFText_GetLooseCharBox",
7499      3
7500    );
7501    Module["_FPDFText_GetMatrix"] = createExportWrapper(
7502      "FPDFText_GetMatrix",
7503      3
7504    );
7505    Module["_FPDFText_GetCharOrigin"] = createExportWrapper(
7506      "FPDFText_GetCharOrigin",
7507      4
7508    );
7509    Module["_FPDFText_GetCharIndexAtPos"] = createExportWrapper(
7510      "FPDFText_GetCharIndexAtPos",
7511      5
7512    );
7513    Module["_FPDFText_GetText"] = createExportWrapper(
7514      "FPDFText_GetText",
7515      4
7516    );
7517    Module["_FPDFText_CountRects"] = createExportWrapper(
7518      "FPDFText_CountRects",
7519      3
7520    );
7521    Module["_FPDFText_GetRect"] = createExportWrapper(
7522      "FPDFText_GetRect",
7523      6
7524    );
7525    Module["_FPDFText_GetBoundedText"] = createExportWrapper(
7526      "FPDFText_GetBoundedText",
7527      7
7528    );
7529    Module["_FPDFText_FindStart"] = createExportWrapper(
7530      "FPDFText_FindStart",
7531      4
7532    );
7533    Module["_FPDFText_FindNext"] = createExportWrapper(
7534      "FPDFText_FindNext",
7535      1
7536    );
7537    Module["_FPDFText_FindPrev"] = createExportWrapper(
7538      "FPDFText_FindPrev",
7539      1
7540    );
7541    Module["_FPDFText_GetSchResultIndex"] = createExportWrapper(
7542      "FPDFText_GetSchResultIndex",
7543      1
7544    );
7545    Module["_FPDFText_GetSchCount"] = createExportWrapper(
7546      "FPDFText_GetSchCount",
7547      1
7548    );
7549    Module["_FPDFText_FindClose"] = createExportWrapper(
7550      "FPDFText_FindClose",
7551      1
7552    );
7553    Module["_FPDFLink_LoadWebLinks"] = createExportWrapper(
7554      "FPDFLink_LoadWebLinks",
7555      1
7556    );
7557    Module["_FPDFLink_CountWebLinks"] = createExportWrapper(
7558      "FPDFLink_CountWebLinks",
7559      1
7560    );
7561    Module["_FPDFLink_GetURL"] = createExportWrapper("FPDFLink_GetURL", 4);
7562    Module["_FPDFLink_CountRects"] = createExportWrapper(
7563      "FPDFLink_CountRects",
7564      2
7565    );
7566    Module["_FPDFLink_GetRect"] = createExportWrapper(
7567      "FPDFLink_GetRect",
7568      7
7569    );
7570    Module["_FPDFLink_GetTextRange"] = createExportWrapper(
7571      "FPDFLink_GetTextRange",
7572      4
7573    );
7574    Module["_FPDFLink_CloseWebLinks"] = createExportWrapper(
7575      "FPDFLink_CloseWebLinks",
7576      1
7577    );
7578    Module["_FPDFPage_GetDecodedThumbnailData"] = createExportWrapper("FPDFPage_GetDecodedThumbnailData", 3);
7579    Module["_FPDFPage_GetRawThumbnailData"] = createExportWrapper("FPDFPage_GetRawThumbnailData", 3);
7580    Module["_FPDFPage_GetThumbnailAsBitmap"] = createExportWrapper("FPDFPage_GetThumbnailAsBitmap", 1);
7581    Module["_FPDFPage_SetMediaBox"] = createExportWrapper(
7582      "FPDFPage_SetMediaBox",
7583      5
7584    );
7585    Module["_FPDFPage_SetCropBox"] = createExportWrapper(
7586      "FPDFPage_SetCropBox",
7587      5
7588    );
7589    Module["_FPDFPage_SetBleedBox"] = createExportWrapper(
7590      "FPDFPage_SetBleedBox",
7591      5
7592    );
7593    Module["_FPDFPage_SetTrimBox"] = createExportWrapper(
7594      "FPDFPage_SetTrimBox",
7595      5
7596    );
7597    Module["_FPDFPage_SetArtBox"] = createExportWrapper(
7598      "FPDFPage_SetArtBox",
7599      5
7600    );
7601    Module["_FPDFPage_GetMediaBox"] = createExportWrapper(
7602      "FPDFPage_GetMediaBox",
7603      5
7604    );
7605    Module["_FPDFPage_GetCropBox"] = createExportWrapper(
7606      "FPDFPage_GetCropBox",
7607      5
7608    );
7609    Module["_FPDFPage_GetBleedBox"] = createExportWrapper(
7610      "FPDFPage_GetBleedBox",
7611      5
7612    );
7613    Module["_FPDFPage_GetTrimBox"] = createExportWrapper(
7614      "FPDFPage_GetTrimBox",
7615      5
7616    );
7617    Module["_FPDFPage_GetArtBox"] = createExportWrapper(
7618      "FPDFPage_GetArtBox",
7619      5
7620    );
7621    Module["_FPDFPage_TransFormWithClip"] = createExportWrapper(
7622      "FPDFPage_TransFormWithClip",
7623      3
7624    );
7625    Module["_FPDFPageObj_TransformClipPath"] = createExportWrapper("FPDFPageObj_TransformClipPath", 7);
7626    Module["_FPDFPageObj_GetClipPath"] = createExportWrapper(
7627      "FPDFPageObj_GetClipPath",
7628      1
7629    );
7630    Module["_FPDFClipPath_CountPaths"] = createExportWrapper(
7631      "FPDFClipPath_CountPaths",
7632      1
7633    );
7634    Module["_FPDFClipPath_CountPathSegments"] = createExportWrapper("FPDFClipPath_CountPathSegments", 2);
7635    Module["_FPDFClipPath_GetPathSegment"] = createExportWrapper("FPDFClipPath_GetPathSegment", 3);
7636    Module["_FPDF_CreateClipPath"] = createExportWrapper(
7637      "FPDF_CreateClipPath",
7638      4
7639    );
7640    Module["_FPDF_DestroyClipPath"] = createExportWrapper(
7641      "FPDF_DestroyClipPath",
7642      1
7643    );
7644    Module["_FPDFPage_InsertClipPath"] = createExportWrapper(
7645      "FPDFPage_InsertClipPath",
7646      2
7647    );
7648    Module["_FPDF_InitLibrary"] = createExportWrapper(
7649      "FPDF_InitLibrary",
7650      0
7651    );
7652    Module["_FPDF_DestroyLibrary"] = createExportWrapper(
7653      "FPDF_DestroyLibrary",
7654      0
7655    );
vendor: 15,565 bytes, lines 7656-8143
7656    Module["_FPDF_SetSandBoxPolicy"] = createExportWrapper(
7657      "FPDF_SetSandBoxPolicy",
7658      2
7659    );
7660    Module["_FPDF_LoadDocument"] = createExportWrapper(
7661      "FPDF_LoadDocument",
7662      2
7663    );
7664    Module["_FPDF_GetFormType"] = createExportWrapper(
7665      "FPDF_GetFormType",
7666      1
7667    );
7668    Module["_FPDF_LoadXFA"] = createExportWrapper("FPDF_LoadXFA", 1);
7669    Module["_FPDF_LoadMemDocument"] = createExportWrapper(
7670      "FPDF_LoadMemDocument",
7671      3
7672    );
7673    Module["_FPDF_LoadMemDocument64"] = createExportWrapper(
7674      "FPDF_LoadMemDocument64",
7675      3
7676    );
7677    Module["_FPDF_LoadCustomDocument"] = createExportWrapper(
7678      "FPDF_LoadCustomDocument",
7679      2
7680    );
7681    Module["_FPDF_GetFileVersion"] = createExportWrapper(
7682      "FPDF_GetFileVersion",
7683      2
7684    );
7685    Module["_FPDF_DocumentHasValidCrossReferenceTable"] = createExportWrapper("FPDF_DocumentHasValidCrossReferenceTable", 1);
7686    Module["_FPDF_GetDocPermissions"] = createExportWrapper(
7687      "FPDF_GetDocPermissions",
7688      1
7689    );
7690    Module["_FPDF_GetDocUserPermissions"] = createExportWrapper(
7691      "FPDF_GetDocUserPermissions",
7692      1
7693    );
7694    Module["_FPDF_GetSecurityHandlerRevision"] = createExportWrapper("FPDF_GetSecurityHandlerRevision", 1);
7695    Module["_EPDF_SetEncryption"] = createExportWrapper(
7696      "EPDF_SetEncryption",
7697      4
7698    );
7699    Module["_EPDF_RemoveEncryption"] = createExportWrapper(
7700      "EPDF_RemoveEncryption",
7701      1
7702    );
7703    Module["_EPDF_UnlockOwnerPermissions"] = createExportWrapper("EPDF_UnlockOwnerPermissions", 2);
7704    Module["_EPDF_IsEncrypted"] = createExportWrapper(
7705      "EPDF_IsEncrypted",
7706      1
7707    );
7708    Module["_EPDF_IsOwnerUnlocked"] = createExportWrapper(
7709      "EPDF_IsOwnerUnlocked",
7710      1
7711    );
7712    Module["_FPDF_GetPageCount"] = createExportWrapper(
7713      "FPDF_GetPageCount",
7714      1
7715    );
7716    Module["_FPDF_LoadPage"] = createExportWrapper("FPDF_LoadPage", 2);
7717    Module["_FPDF_GetPageWidthF"] = createExportWrapper(
7718      "FPDF_GetPageWidthF",
7719      1
7720    );
7721    Module["_FPDF_GetPageWidth"] = createExportWrapper(
7722      "FPDF_GetPageWidth",
7723      1
7724    );
7725    Module["_FPDF_GetPageHeightF"] = createExportWrapper(
7726      "FPDF_GetPageHeightF",
7727      1
7728    );
7729    Module["_FPDF_GetPageHeight"] = createExportWrapper(
7730      "FPDF_GetPageHeight",
7731      1
7732    );
7733    Module["_FPDF_GetPageBoundingBox"] = createExportWrapper(
7734      "FPDF_GetPageBoundingBox",
7735      2
7736    );
7737    Module["_FPDF_RenderPageBitmap"] = createExportWrapper(
7738      "FPDF_RenderPageBitmap",
7739      8
7740    );
7741    Module["_FPDF_RenderPageBitmapWithMatrix"] = createExportWrapper("FPDF_RenderPageBitmapWithMatrix", 5);
7742    Module["_EPDF_RenderAnnotBitmap"] = createExportWrapper(
7743      "EPDF_RenderAnnotBitmap",
7744      6
7745    );
7746    Module["_EPDF_RenderAnnotBitmapUnrotated"] = createExportWrapper("EPDF_RenderAnnotBitmapUnrotated", 6);
7747    Module["_FPDF_ClosePage"] = createExportWrapper("FPDF_ClosePage", 1);
7748    Module["_FPDF_CloseDocument"] = createExportWrapper(
7749      "FPDF_CloseDocument",
7750      1
7751    );
7752    Module["_FPDF_GetLastError"] = createExportWrapper(
7753      "FPDF_GetLastError",
7754      0
7755    );
7756    Module["_FPDF_DeviceToPage"] = createExportWrapper(
7757      "FPDF_DeviceToPage",
7758      10
7759    );
7760    Module["_FPDF_PageToDevice"] = createExportWrapper(
7761      "FPDF_PageToDevice",
7762      10
7763    );
7764    Module["_FPDFBitmap_Create"] = createExportWrapper(
7765      "FPDFBitmap_Create",
7766      3
7767    );
7768    Module["_FPDFBitmap_CreateEx"] = createExportWrapper(
7769      "FPDFBitmap_CreateEx",
7770      5
7771    );
7772    Module["_FPDFBitmap_GetFormat"] = createExportWrapper(
7773      "FPDFBitmap_GetFormat",
7774      1
7775    );
7776    Module["_FPDFBitmap_FillRect"] = createExportWrapper(
7777      "FPDFBitmap_FillRect",
7778      6
7779    );
7780    Module["_FPDFBitmap_GetBuffer"] = createExportWrapper(
7781      "FPDFBitmap_GetBuffer",
7782      1
7783    );
7784    Module["_FPDFBitmap_GetWidth"] = createExportWrapper(
7785      "FPDFBitmap_GetWidth",
7786      1
7787    );
7788    Module["_FPDFBitmap_GetHeight"] = createExportWrapper(
7789      "FPDFBitmap_GetHeight",
7790      1
7791    );
7792    Module["_FPDFBitmap_GetStride"] = createExportWrapper(
7793      "FPDFBitmap_GetStride",
7794      1
7795    );
7796    Module["_FPDFBitmap_Destroy"] = createExportWrapper(
7797      "FPDFBitmap_Destroy",
7798      1
7799    );
7800    Module["_FPDF_GetPageSizeByIndexF"] = createExportWrapper(
7801      "FPDF_GetPageSizeByIndexF",
7802      3
7803    );
7804    Module["_EPDF_GetPageRotationByIndex"] = createExportWrapper("EPDF_GetPageRotationByIndex", 2);
7805    Module["_EPDF_GetPageSizeByIndexNormalized"] = createExportWrapper("EPDF_GetPageSizeByIndexNormalized", 3);
7806    Module["_EPDF_LoadPageNormalized"] = createExportWrapper(
7807      "EPDF_LoadPageNormalized",
7808      3
7809    );
7810    Module["_FPDF_GetPageSizeByIndex"] = createExportWrapper(
7811      "FPDF_GetPageSizeByIndex",
7812      4
7813    );
7814    Module["_FPDF_VIEWERREF_GetPrintScaling"] = createExportWrapper("FPDF_VIEWERREF_GetPrintScaling", 1);
7815    Module["_FPDF_VIEWERREF_GetNumCopies"] = createExportWrapper("FPDF_VIEWERREF_GetNumCopies", 1);
7816    Module["_FPDF_VIEWERREF_GetPrintPageRange"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRange", 1);
7817    Module["_FPDF_VIEWERREF_GetPrintPageRangeCount"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRangeCount", 1);
7818    Module["_FPDF_VIEWERREF_GetPrintPageRangeElement"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRangeElement", 2);
7819    Module["_FPDF_VIEWERREF_GetDuplex"] = createExportWrapper(
7820      "FPDF_VIEWERREF_GetDuplex",
7821      1
7822    );
7823    Module["_FPDF_VIEWERREF_GetName"] = createExportWrapper(
7824      "FPDF_VIEWERREF_GetName",
7825      4
7826    );
7827    Module["_FPDF_CountNamedDests"] = createExportWrapper(
7828      "FPDF_CountNamedDests",
7829      1
7830    );
7831    Module["_FPDF_GetNamedDestByName"] = createExportWrapper(
7832      "FPDF_GetNamedDestByName",
7833      2
7834    );
7835    Module["_FPDF_GetNamedDest"] = createExportWrapper(
7836      "FPDF_GetNamedDest",
7837      4
7838    );
7839    Module["_FPDF_GetXFAPacketCount"] = createExportWrapper(
7840      "FPDF_GetXFAPacketCount",
7841      1
7842    );
7843    Module["_FPDF_GetXFAPacketName"] = createExportWrapper(
7844      "FPDF_GetXFAPacketName",
7845      4
7846    );
7847    Module["_FPDF_GetXFAPacketContent"] = createExportWrapper(
7848      "FPDF_GetXFAPacketContent",
7849      5
7850    );
7851    Module["_FPDF_GetTrailerEnds"] = createExportWrapper(
7852      "FPDF_GetTrailerEnds",
7853      3
7854    );
7855    var _strerror = createExportWrapper("strerror", 1);
7856    var _fflush = createExportWrapper("fflush", 1);
7857    var _emscripten_builtin_memalign = createExportWrapper("emscripten_builtin_memalign", 2);
7858    var _setThrew = createExportWrapper("setThrew", 2);
7859    var _emscripten_stack_init = () => (_emscripten_stack_init = wasmExports["emscripten_stack_init"])();
7860    var _emscripten_stack_get_end = () => (_emscripten_stack_get_end = wasmExports["emscripten_stack_get_end"])();
7861    var __emscripten_stack_restore = (a0) => (__emscripten_stack_restore = wasmExports["_emscripten_stack_restore"])(a0);
7862    var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"])(a0);
7863    var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"])();
7864    Module["dynCall_j"] = createExportWrapper("dynCall_j", 1);
7865    Module["dynCall_ji"] = createExportWrapper("dynCall_ji", 2);
7866    Module["dynCall_iiij"] = createExportWrapper("dynCall_iiij", 5);
7867    Module["dynCall_jji"] = createExportWrapper("dynCall_jji", 4);
7868    Module["dynCall_iji"] = createExportWrapper("dynCall_iji", 4);
7869    Module["dynCall_viijii"] = createExportWrapper("dynCall_viijii", 7);
7870    Module["dynCall_jij"] = createExportWrapper("dynCall_jij", 4);
7871    Module["dynCall_iij"] = createExportWrapper("dynCall_iij", 4);
7872    Module["dynCall_iiji"] = createExportWrapper("dynCall_iiji", 5);
7873    Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji", 5);
7874    Module["dynCall_iiiiij"] = createExportWrapper("dynCall_iiiiij", 7);
7875    Module["dynCall_iiiiijj"] = createExportWrapper("dynCall_iiiiijj", 9);
7876    Module["dynCall_iiiiiijj"] = createExportWrapper(
7877      "dynCall_iiiiiijj",
7878      10
7879    );
7880    Module["dynCall_viji"] = createExportWrapper("dynCall_viji", 5);
7881    function invoke_viii(index, a1, a2, a3) {
7882      var sp = stackSave();
7883      try {
7884        getWasmTableEntry(index)(a1, a2, a3);
7885      } catch (e) {
7886        stackRestore(sp);
7887        if (e !== e + 0) throw e;
7888        _setThrew(1, 0);
7889      }
7890    }
7891    function invoke_ii(index, a1) {
7892      var sp = stackSave();
7893      try {
7894        return getWasmTableEntry(index)(a1);
7895      } catch (e) {
7896        stackRestore(sp);
7897        if (e !== e + 0) throw e;
7898        _setThrew(1, 0);
7899      }
7900    }
7901    function invoke_iii(index, a1, a2) {
7902      var sp = stackSave();
7903      try {
7904        return getWasmTableEntry(index)(a1, a2);
7905      } catch (e) {
7906        stackRestore(sp);
7907        if (e !== e + 0) throw e;
7908        _setThrew(1, 0);
7909      }
7910    }
7911    function invoke_iiii(index, a1, a2, a3) {
7912      var sp = stackSave();
7913      try {
7914        return getWasmTableEntry(index)(a1, a2, a3);
7915      } catch (e) {
7916        stackRestore(sp);
7917        if (e !== e + 0) throw e;
7918        _setThrew(1, 0);
7919      }
7920    }
7921    function invoke_iiiii(index, a1, a2, a3, a4) {
7922      var sp = stackSave();
7923      try {
7924        return getWasmTableEntry(index)(a1, a2, a3, a4);
7925      } catch (e) {
7926        stackRestore(sp);
7927        if (e !== e + 0) throw e;
7928        _setThrew(1, 0);
7929      }
7930    }
7931    function invoke_vii(index, a1, a2) {
7932      var sp = stackSave();
7933      try {
7934        getWasmTableEntry(index)(a1, a2);
7935      } catch (e) {
7936        stackRestore(sp);
7937        if (e !== e + 0) throw e;
7938        _setThrew(1, 0);
7939      }
7940    }
7941    function invoke_vi(index, a1) {
7942      var sp = stackSave();
7943      try {
7944        getWasmTableEntry(index)(a1);
7945      } catch (e) {
7946        stackRestore(sp);
7947        if (e !== e + 0) throw e;
7948        _setThrew(1, 0);
7949      }
7950    }
7951    function invoke_v(index) {
7952      var sp = stackSave();
7953      try {
7954        getWasmTableEntry(index)();
7955      } catch (e) {
7956        stackRestore(sp);
7957        if (e !== e + 0) throw e;
7958        _setThrew(1, 0);
7959      }
7960    }
7961    function invoke_viiii(index, a1, a2, a3, a4) {
7962      var sp = stackSave();
7963      try {
7964        getWasmTableEntry(index)(a1, a2, a3, a4);
7965      } catch (e) {
7966        stackRestore(sp);
7967        if (e !== e + 0) throw e;
7968        _setThrew(1, 0);
7969      }
7970    }
7971    function invoke_viiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
7972      var sp = stackSave();
7973      try {
7974        getWasmTableEntry(index)(a1, a2, a3, a4, a5, a6, a7, a8, a9);
7975      } catch (e) {
7976        stackRestore(sp);
7977        if (e !== e + 0) throw e;
7978        _setThrew(1, 0);
7979      }
7980    }
7981    Module["wasmExports"] = wasmExports;
7982    Module["ccall"] = ccall;
7983    Module["cwrap"] = cwrap;
7984    Module["addFunction"] = addFunction;
7985    Module["removeFunction"] = removeFunction;
7986    Module["setValue"] = setValue;
7987    Module["getValue"] = getValue;
7988    Module["UTF8ToString"] = UTF8ToString;
7989    Module["stringToUTF8"] = stringToUTF8;
7990    Module["UTF16ToString"] = UTF16ToString;
7991    Module["stringToUTF16"] = stringToUTF16;
7992    var missingLibrarySymbols = [
7993      "writeI53ToI64",
7994      "writeI53ToI64Clamped",
7995      "writeI53ToI64Signaling",
7996      "writeI53ToU64Clamped",
7997      "writeI53ToU64Signaling",
7998      "readI53FromI64",
7999      "readI53FromU64",
8000      "convertI32PairToI53",
8001      "convertU32PairToI53",
8002      "getTempRet0",
8003      "setTempRet0",
8004      "exitJS",
8005      "inetPton4",
8006      "inetNtop4",
8007      "inetPton6",
8008      "inetNtop6",
8009      "readSockaddr",
8010      "writeSockaddr",
8011      "emscriptenLog",
8012      "readEmAsmArgs",
8013      "jstoi_q",
8014      "listenOnce",
8015      "autoResumeAudioContext",
8016      "dynCallLegacy",
8017      "getDynCaller",
8018      "dynCall",
8019      "handleException",
8020      "keepRuntimeAlive",
8021      "runtimeKeepalivePush",
8022      "runtimeKeepalivePop",
8023      "callUserCallback",
8024      "maybeExit",
8025      "asmjsMangle",
8026      "HandleAllocator",
8027      "getNativeTypeSize",
8028      "STACK_SIZE",
8029      "STACK_ALIGN",
8030      "POINTER_SIZE",
8031      "ASSERTIONS",
8032      "reallyNegative",
8033      "unSign",
8034      "strLen",
8035      "reSign",
8036      "formatString",
8037      "intArrayToString",
8038      "AsciiToString",
8039      "lengthBytesUTF16",
8040      "UTF32ToString",
8041      "stringToUTF32",
8042      "lengthBytesUTF32",
8043      "stringToNewUTF8",
8044      "registerKeyEventCallback",
8045      "maybeCStringToJsString",
8046      "findEventTarget",
8047      "getBoundingClientRect",
8048      "fillMouseEventData",
8049      "registerMouseEventCallback",
8050      "registerWheelEventCallback",
8051      "registerUiEventCallback",
8052      "registerFocusEventCallback",
8053      "fillDeviceOrientationEventData",
8054      "registerDeviceOrientationEventCallback",
8055      "fillDeviceMotionEventData",
8056      "registerDeviceMotionEventCallback",
8057      "screenOrientation",
8058      "fillOrientationChangeEventData",
8059      "registerOrientationChangeEventCallback",
8060      "fillFullscreenChangeEventData",
8061      "registerFullscreenChangeEventCallback",
8062      "JSEvents_requestFullscreen",
8063      "JSEvents_resizeCanvasForFullscreen",
8064      "registerRestoreOldStyle",
8065      "hideEverythingExceptGivenElement",
8066      "restoreHiddenElements",
8067      "setLetterbox",
8068      "softFullscreenResizeWebGLRenderTarget",
8069      "doRequestFullscreen",
8070      "fillPointerlockChangeEventData",
8071      "registerPointerlockChangeEventCallback",
8072      "registerPointerlockErrorEventCallback",
8073      "requestPointerLock",
8074      "fillVisibilityChangeEventData",
8075      "registerVisibilityChangeEventCallback",
8076      "registerTouchEventCallback",
8077      "fillGamepadEventData",
8078      "registerGamepadEventCallback",
8079      "registerBeforeUnloadEventCallback",
8080      "fillBatteryEventData",
8081      "battery",
8082      "registerBatteryEventCallback",
8083      "setCanvasElementSize",
8084      "getCanvasElementSize",
8085      "jsStackTrace",
8086      "getCallstack",
8087      "convertPCtoSourceLocation",
8088      "checkWasiClock",
8089      "wasiRightsToMuslOFlags",
8090      "wasiOFlagsToMuslOFlags",
8091      "createDyncallWrapper",
8092      "safeSetTimeout",
8093      "setImmediateWrapped",
8094      "clearImmediateWrapped",
8095      "polyfillSetImmediate",
8096      "registerPostMainLoop",
8097      "registerPreMainLoop",
8098      "getPromise",
8099      "makePromise",
8100      "idsToPromises",
8101      "makePromiseCallback",
8102      "ExceptionInfo",
8103      "findMatchingCatch",
8104      "Browser_asyncPrepareDataCounter",
8105      "safeRequestAnimationFrame",
8106      "arraySum",
8107      "addDays",
8108      "getSocketFromFD",
8109      "getSocketAddress",
8110      "FS_unlink",
8111      "FS_mkdirTree",
8112      "_setNetworkCallback",
8113      "heapObjectForWebGLType",
8114      "toTypedArrayIndex",
8115      "webgl_enable_ANGLE_instanced_arrays",
8116      "webgl_enable_OES_vertex_array_object",
8117      "webgl_enable_WEBGL_draw_buffers",
8118      "webgl_enable_WEBGL_multi_draw",
8119      "webgl_enable_EXT_polygon_offset_clamp",
8120      "webgl_enable_EXT_clip_control",
8121      "webgl_enable_WEBGL_polygon_mode",
8122      "emscriptenWebGLGet",
8123      "computeUnpackAlignedImageSize",
8124      "colorChannelsInGlTextureFormat",
8125      "emscriptenWebGLGetTexPixelData",
8126      "emscriptenWebGLGetUniform",
8127      "webglGetUniformLocation",
8128      "webglPrepareUniformLocationsBeforeFirstUse",
8129      "webglGetLeftBracePos",
8130      "emscriptenWebGLGetVertexAttrib",
8131      "__glGetActiveAttribOrUniform",
8132      "writeGLArray",
8133      "registerWebGlEventCallback",
8134      "runAndAbortIfError",
8135      "ALLOC_NORMAL",
8136      "ALLOC_STACK",
8137      "allocate",
8138      "writeStringToMemory",
8139      "writeAsciiToMemory",
8140      "setErrNo",
8141      "demangle",
8142      "stackTrace"
8143    ];
8144    missingLibrarySymbols.forEach(missingLibrarySymbol);
8145    var unexportedSymbols = [
8146      "run",
8147      "addOnPreRun",
8148      "addOnInit",
8149      "addOnPreMain",
8150      "addOnExit",
8151      "addOnPostRun",
8152      "addRunDependency",
8153      "removeRunDependency",
8154      "out",
8155      "err",
8156      "callMain",
8157      "abort",
8158      "wasmMemory",
8159      "writeStackCookie",
8160      "checkStackCookie",
8161      "convertI32PairToI53Checked",
8162      "stackSave",
8163      "stackRestore",
8164      "stackAlloc",
8165      "ptrToString",
8166      "zeroMemory",
8167      "getHeapMax",
8168      "growMemory",
8169      "ENV",
8170      "ERRNO_CODES",
8171      "strError",
8172      "DNS",
8173      "Protocols",
8174      "Sockets",
8175      "initRandomFill",
8176      "randomFill",
8177      "timers",
8178      "warnOnce",
8179      "readEmAsmArgsArray",
8180      "jstoi_s",
8181      "getExecutableName",
8182      "asyncLoad",
8183      "alignMemory",
8184      "mmapAlloc",
8185      "wasmTable",
8186      "noExitRuntime",
8187      "getCFunc",
8188      "uleb128Encode",
8189      "sigToWasmTypes",
8190      "generateFuncType",
8191      "convertJsFunctionToWasm",
8192      "freeTableIndexes",
8193      "functionsInTableMap",
8194      "getEmptyTableSlot",
8195      "updateTableMap",
8196      "getFunctionAddress",
8197      "PATH",
8198      "PATH_FS",
8199      "UTF8Decoder",
8200      "UTF8ArrayToString",
8201      "stringToUTF8Array",
8202      "lengthBytesUTF8",
8203      "intArrayFromString",
8204      "stringToAscii",
8205      "UTF16Decoder",
8206      "stringToUTF8OnStack",
8207      "writeArrayToMemory",
8208      "JSEvents",
8209      "specialHTMLTargets",
8210      "findCanvasEventTarget",
8211      "currentFullscreenStrategy",
8212      "restoreOldWindowedStyle",
8213      "UNWIND_CACHE",
8214      "ExitStatus",
8215      "getEnvStrings",
8216      "doReadv",
8217      "doWritev",
8218      "promiseMap",
8219      "uncaughtExceptionCount",
8220      "exceptionLast",
8221      "exceptionCaught",
8222      "Browser",
8223      "getPreloadedImageData__data",
8224      "wget",
8225      "MONTH_DAYS_REGULAR",
8226      "MONTH_DAYS_LEAP",
8227      "MONTH_DAYS_REGULAR_CUMULATIVE",
8228      "MONTH_DAYS_LEAP_CUMULATIVE",
8229      "isLeapYear",
8230      "ydayFromDate",
8231      "SYSCALLS",
8232      "preloadPlugins",
8233      "FS_createPreloadedFile",
8234      "FS_modeStringToFlags",
8235      "FS_getMode",
8236      "FS_stdin_getChar_buffer",
8237      "FS_stdin_getChar",
8238      "FS_createPath",
8239      "FS_createDevice",
8240      "FS_readFile",
8241      "FS",
8242      "FS_createDataFile",
8243      "FS_createLazyFile",
8244      "MEMFS",
8245      "TTY",
8246      "PIPEFS",
8247      "SOCKFS",
8248      "tempFixedLengthArray",
8249      "miniTempWebGLFloatBuffers",
8250      "miniTempWebGLIntBuffers",
8251      "GL",
8252      "AL",
8253      "GLUT",
8254      "EGL",
8255      "GLEW",
8256      "IDBStore",
8257      "SDL",
8258      "SDL_gfx",
8259      "allocateUTF8",
8260      "allocateUTF8OnStack",
8261      "print",
8262      "printErr"
8263    ];
8264    unexportedSymbols.forEach(unexportedRuntimeSymbol);
8265    var calledRun;
8266    var calledPrerun;
8267    dependenciesFulfilled = function runCaller() {
8268      if (!calledRun) run();
8269      if (!calledRun) dependenciesFulfilled = runCaller;
8270    };
8271    function stackCheckInit() {
8272      _emscripten_stack_init();
8273      writeStackCookie();
8274    }
8275    function run() {
8276      if (runDependencies > 0) {
8277        return;
8278      }
8279      stackCheckInit();
8280      if (!calledPrerun) {
8281        calledPrerun = 1;
8282        preRun();
8283        if (runDependencies > 0) {
8284          return;
8285        }
8286      }
8287      function doRun() {
8288        var _a;
8289        if (calledRun) return;
8290        calledRun = 1;
8291        Module["calledRun"] = 1;
8292        if (ABORT) return;
8293        initRuntime();
8294        readyPromiseResolve(Module);
8295        (_a = Module["onRuntimeInitialized"]) == null ? void 0 : _a.call(Module);
8296        assert(
8297          !Module["_main"],
8298          'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'
8299        );
8300        postRun();
8301      }
8302      if (Module["setStatus"]) {
8303        Module["setStatus"]("Running...");
8304        setTimeout(() => {
8305          setTimeout(() => Module["setStatus"](""), 1);
8306          doRun();
8307        }, 1);
8308      } else {
8309        doRun();
8310      }
8311      checkStackCookie();
8312    }
8313    if (Module["preInit"]) {
8314      if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]];
8315      while (Module["preInit"].length > 0) {
8316        Module["preInit"].pop()();
8317      }
8318    }
8319    run();
8320    moduleRtn = readyPromise;
8321    for (const prop of Object.keys(Module)) {
8322      if (!(prop in moduleArg)) {
8323        Object.defineProperty(moduleArg, prop, {
8324          configurable: true,
8325          get() {
8326            abort(
8327              \`Access to module property ('\${prop}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.\`
8328            );
8329          }
8330        });
8331      }
8332    }
8333    return moduleRtn;
8334  };
8335})();
8336const functions = {
8337  EPDF_GetMetaKeyCount: [["number", "boolean"], "number"],
8338  EPDF_GetMetaKeyName: [
8339    ["number", "number", "boolean", "number", "number"],
8340    "number"
8341  ],
8342  EPDF_GetMetaTrapped: [["number"], "number"],
8343  EPDF_GetPageRotationByIndex: [["number", "number"], "number"],
8344  EPDF_GetPageSizeByIndexNormalized: [["number", "number", "number"], "boolean"],
8345  EPDF_HasMetaText: [["number", "string"], "boolean"],
8346  EPDF_IsEncrypted: [["number"], "boolean"],
vendor: 16,384 bytes, lines 8347-8738
8347  EPDF_IsOwnerUnlocked: [["number"], "boolean"],
8348  EPDF_LoadPageNormalized: [["number", "number", "number"], "number"],
8349  EPDF_PNG_EncodeRGBA: [
8350    ["number", "number", "number", "number", "number", "number"],
8351    "number"
8352  ],
8353  EPDF_RemoveEncryption: [["number"], "boolean"],
8354  EPDF_RenderAnnotBitmap: [
8355    ["number", "number", "number", "number", "number", "number"],
8356    "boolean"
8357  ],
8358  EPDF_RenderAnnotBitmapUnrotated: [
8359    ["number", "number", "number", "number", "number", "number"],
8360    "boolean"
8361  ],
8362  EPDF_SetEncryption: [["number", "string", "string", "number"], "boolean"],
8363  EPDF_SetMetaText: [["number", "string", "number"], "boolean"],
8364  EPDF_SetMetaTrapped: [["number", "number"], "boolean"],
8365  EPDF_UnlockOwnerPermissions: [["number", "string"], "boolean"],
8366  EPDFAction_CreateGoTo: [["number", "number"], "number"],
8367  EPDFAction_CreateGoToNamed: [["number", "string"], "number"],
8368  EPDFAction_CreateLaunch: [["number", "number"], "number"],
8369  EPDFAction_CreateRemoteGoToByName: [["number", "number", "number"], "number"],
8370  EPDFAction_CreateRemoteGoToDest: [["number", "number", "number"], "number"],
8371  EPDFAction_CreateURI: [["number", "string"], "number"],
8372  EPDFAnnot_ApplyRedaction: [["number", "number"], "boolean"],
8373  EPDFAnnot_ClearBorderEffect: [["number"], "boolean"],
8374  EPDFAnnot_ClearColor: [["number", "number"], "boolean"],
8375  EPDFAnnot_ClearMKColor: [["number", "number"], "boolean"],
8376  EPDFAnnot_ClearRectangleDifferences: [["number"], "boolean"],
8377  EPDFAnnot_ExportAppearanceAsDocument: [["number"], "number"],
8378  EPDFAnnot_ExportMultipleAppearancesAsDocument: [["number", "number"], "number"],
8379  EPDFAnnot_Flatten: [["number", "number"], "boolean"],
8380  EPDFAnnot_GenerateAppearance: [["number"], "boolean"],
8381  EPDFAnnot_GenerateAppearanceWithBlend: [["number", "number"], "boolean"],
8382  EPDFAnnot_GenerateFormFieldAP: [["number"], "boolean"],
8383  EPDFAnnot_GetAPMatrix: [["number", "number", "number"], "boolean"],
8384  EPDFAnnot_GetAvailableAppearanceModes: [["number"], "number"],
8385  EPDFAnnot_GetBlendMode: [["number"], "number"],
8386  EPDFAnnot_GetBorderDashPattern: [["number", "number", "number"], "boolean"],
8387  EPDFAnnot_GetBorderDashPatternCount: [["number"], "number"],
8388  EPDFAnnot_GetBorderEffect: [["number", "number"], "boolean"],
8389  EPDFAnnot_GetBorderStyle: [["number", "number"], "number"],
8390  EPDFAnnot_GetButtonExportValue: [["number", "number", "number"], "number"],
8391  EPDFAnnot_GetCalloutLine: [["number", "number", "number"], "number"],
8392  EPDFAnnot_GetCalloutLineCount: [["number"], "number"],
8393  EPDFAnnot_GetColor: [
8394    ["number", "number", "number", "number", "number"],
8395    "boolean"
8396  ],
8397  EPDFAnnot_GetDefaultAppearance: [
8398    ["number", "number", "number", "number", "number", "number"],
8399    "boolean"
8400  ],
8401  EPDFAnnot_GetExtendedRotation: [["number", "number"], "boolean"],
8402  EPDFAnnot_GetFormFieldObjectNumber: [["number", "number"], "number"],
8403  EPDFAnnot_GetFormFieldRawValue: [
8404    ["number", "number", "number", "number"],
8405    "number"
8406  ],
8407  EPDFAnnot_GetIntent: [["number", "number", "number"], "number"],
8408  EPDFAnnot_GetLineEndings: [["number", "number", "number"], "boolean"],
8409  EPDFAnnot_GetMKColor: [
8410    ["number", "number", "number", "number", "number"],
8411    "boolean"
8412  ],
8413  EPDFAnnot_GetName: [["number"], "number"],
8414  EPDFAnnot_GetOpacity: [["number", "number"], "boolean"],
8415  EPDFAnnot_GetOverlayText: [["number", "number", "number"], "number"],
8416  EPDFAnnot_GetOverlayTextRepeat: [["number"], "boolean"],
8417  EPDFAnnot_GetRect: [["number", "number"], "boolean"],
8418  EPDFAnnot_GetRectangleDifferences: [
8419    ["number", "number", "number", "number", "number"],
8420    "boolean"
8421  ],
8422  EPDFAnnot_GetReplyType: [["number"], "number"],
8423  EPDFAnnot_GetRichContent: [["number", "number", "number"], "number"],
8424  EPDFAnnot_GetRotate: [["number", "number"], "boolean"],
8425  EPDFAnnot_GetTextAlignment: [["number"], "number"],
8426  EPDFAnnot_GetUnrotatedRect: [["number", "number"], "boolean"],
8427  EPDFAnnot_GetVerticalAlignment: [["number"], "number"],
8428  EPDFAnnot_HasAppearanceStream: [["number", "number"], "boolean"],
8429  EPDFAnnot_SetAction: [["number", "number"], "boolean"],
8430  EPDFAnnot_SetAPMatrix: [["number", "number", "number"], "boolean"],
8431  EPDFAnnot_SetAppearanceFromPage: [["number", "number", "number"], "boolean"],
8432  EPDFAnnot_SetBorderDashPattern: [["number", "number", "number"], "boolean"],
8433  EPDFAnnot_SetBorderEffect: [["number", "number"], "boolean"],
8434  EPDFAnnot_SetBorderStyle: [["number", "number", "number"], "boolean"],
8435  EPDFAnnot_SetCalloutLine: [["number", "number", "number"], "boolean"],
8436  EPDFAnnot_SetColor: [
8437    ["number", "number", "number", "number", "number"],
8438    "boolean"
8439  ],
8440  EPDFAnnot_SetDefaultAppearance: [
8441    ["number", "number", "number", "number", "number", "number"],
8442    "boolean"
8443  ],
8444  EPDFAnnot_SetExtendedRotation: [["number", "number"], "boolean"],
8445  EPDFAnnot_SetFormFieldName: [["number", "number", "number"], "boolean"],
8446  EPDFAnnot_SetFormFieldOptions: [
8447    ["number", "number", "number", "number"],
8448    "boolean"
8449  ],
8450  EPDFAnnot_SetFormFieldValue: [["number", "number", "number"], "boolean"],
8451  EPDFAnnot_SetIntent: [["number", "string"], "boolean"],
8452  EPDFAnnot_SetLine: [["number", "number", "number"], "boolean"],
8453  EPDFAnnot_SetLineEndings: [["number", "number", "number"], "boolean"],
8454  EPDFAnnot_SetLinkedAnnot: [["number", "string", "number"], "boolean"],
8455  EPDFAnnot_SetMKColor: [
8456    ["number", "number", "number", "number", "number"],
8457    "boolean"
8458  ],
8459  EPDFAnnot_SetName: [["number", "number"], "boolean"],
8460  EPDFAnnot_SetNumberValue: [["number", "string", "number"], "boolean"],
8461  EPDFAnnot_SetOpacity: [["number", "number"], "boolean"],
8462  EPDFAnnot_SetOverlayText: [["number", "number"], "boolean"],
8463  EPDFAnnot_SetOverlayTextRepeat: [["number", "boolean"], "boolean"],
8464  EPDFAnnot_SetRectangleDifferences: [
8465    ["number", "number", "number", "number", "number"],
8466    "boolean"
8467  ],
8468  EPDFAnnot_SetReplyType: [["number", "number"], "boolean"],
8469  EPDFAnnot_SetRotate: [["number", "number"], "boolean"],
8470  EPDFAnnot_SetTextAlignment: [["number", "number"], "boolean"],
8471  EPDFAnnot_SetUnrotatedRect: [["number", "number"], "boolean"],
8472  EPDFAnnot_SetVerticalAlignment: [["number", "number"], "boolean"],
8473  EPDFAnnot_SetVertices: [["number", "number", "number"], "boolean"],
8474  EPDFAnnot_ShareFormField: [["number", "number", "number"], "boolean"],
8475  EPDFAnnot_UpdateAppearanceToRect: [["number", "number"], "boolean"],
8476  EPDFAttachment_GetDescription: [["number", "number", "number"], "number"],
8477  EPDFAttachment_GetIntegerValue: [["number", "string", "number"], "boolean"],
8478  EPDFAttachment_SetDescription: [["number", "number"], "boolean"],
8479  EPDFAttachment_SetSubtype: [["number", "string"], "boolean"],
8480  EPDFBookmark_AppendChild: [["number", "number", "number"], "number"],
8481  EPDFBookmark_Clear: [["number"], "boolean"],
8482  EPDFBookmark_ClearTarget: [["number"], "boolean"],
8483  EPDFBookmark_Create: [["number", "number"], "number"],
8484  EPDFBookmark_Delete: [["number", "number"], "boolean"],
8485  EPDFBookmark_InsertAfter: [["number", "number", "number", "number"], "number"],
8486  EPDFBookmark_SetAction: [["number", "number", "number"], "boolean"],
8487  EPDFBookmark_SetDest: [["number", "number", "number"], "boolean"],
8488  EPDFBookmark_SetTitle: [["number", "number"], "boolean"],
8489  EPDFCatalog_GetLanguage: [["number", "number", "number"], "number"],
8490  EPDFDest_CreateRemoteView: [
8491    ["number", "number", "number", "number", "number"],
8492    "number"
8493  ],
8494  EPDFDest_CreateRemoteXYZ: [
8495    ["number", "number", "boolean", "number", "boolean", "number", "boolean", "number"],
8496    "number"
8497  ],
8498  EPDFDest_CreateView: [["number", "number", "number", "number"], "number"],
8499  EPDFDest_CreateXYZ: [
8500    ["number", "boolean", "number", "boolean", "number", "boolean", "number"],
8501    "number"
8502  ],
8503  EPDFImageObj_SetJpeg: [
8504    ["number", "number", "number", "number", "number"],
8505    "boolean"
8506  ],
8507  EPDFImageObj_SetPng: [
8508    ["number", "number", "number", "number", "number"],
8509    "boolean"
8510  ],
8511  EPDFNamedDest_Remove: [["number", "string"], "boolean"],
8512  EPDFNamedDest_SetDest: [["number", "string", "number"], "boolean"],
8513  EPDFPage_ApplyRedactions: [["number"], "boolean"],
8514  EPDFPage_CreateAnnot: [["number", "number"], "number"],
8515  EPDFPage_CreateFormField: [["number", "number", "number", "number"], "number"],
8516  EPDFPage_GetAnnotByName: [["number", "number"], "number"],
8517  EPDFPage_GetAnnotCountRaw: [["number", "number"], "number"],
8518  EPDFPage_GetAnnotRaw: [["number", "number", "number"], "number"],
8519  EPDFPage_RemoveAnnotByName: [["number", "number"], "boolean"],
8520  EPDFPage_RemoveAnnotRaw: [["number", "number", "number"], "boolean"],
8521  EPDFText_RedactInQuads: [
8522    ["number", "number", "number", "boolean", "boolean"],
8523    "boolean"
8524  ],
8525  EPDFText_RedactInRect: [["number", "number", "boolean", "boolean"], "boolean"],
8526  FORM_CanRedo: [["number", "number"], "boolean"],
8527  FORM_CanUndo: [["number", "number"], "boolean"],
8528  FORM_DoDocumentAAction: [["number", "number"], null],
8529  FORM_DoDocumentJSAction: [["number"], null],
8530  FORM_DoDocumentOpenAction: [["number"], null],
8531  FORM_DoPageAAction: [["number", "number", "number"], null],
8532  FORM_ForceToKillFocus: [["number"], "boolean"],
8533  FORM_GetFocusedAnnot: [["number", "number", "number"], "boolean"],
8534  FORM_GetFocusedText: [["number", "number", "number", "number"], "number"],
8535  FORM_GetSelectedText: [["number", "number", "number", "number"], "number"],
8536  FORM_IsIndexSelected: [["number", "number", "number"], "boolean"],
8537  FORM_OnAfterLoadPage: [["number", "number"], null],
8538  FORM_OnBeforeClosePage: [["number", "number"], null],
8539  FORM_OnChar: [["number", "number", "number", "number"], "boolean"],
8540  FORM_OnFocus: [["number", "number", "number", "number", "number"], "boolean"],
8541  FORM_OnKeyDown: [["number", "number", "number", "number"], "boolean"],
8542  FORM_OnKeyUp: [["number", "number", "number", "number"], "boolean"],
8543  FORM_OnLButtonDoubleClick: [
8544    ["number", "number", "number", "number", "number"],
8545    "boolean"
8546  ],
8547  FORM_OnLButtonDown: [
8548    ["number", "number", "number", "number", "number"],
8549    "boolean"
8550  ],
8551  FORM_OnLButtonUp: [
8552    ["number", "number", "number", "number", "number"],
8553    "boolean"
8554  ],
8555  FORM_OnMouseMove: [
8556    ["number", "number", "number", "number", "number"],
8557    "boolean"
8558  ],
8559  FORM_OnMouseWheel: [
8560    ["number", "number", "number", "number", "number", "number"],
8561    "boolean"
8562  ],
8563  FORM_OnRButtonDown: [
8564    ["number", "number", "number", "number", "number"],
8565    "boolean"
8566  ],
8567  FORM_OnRButtonUp: [
8568    ["number", "number", "number", "number", "number"],
8569    "boolean"
8570  ],
8571  FORM_Redo: [["number", "number"], "boolean"],
8572  FORM_ReplaceAndKeepSelection: [["number", "number", "number"], null],
8573  FORM_ReplaceSelection: [["number", "number", "number"], null],
8574  FORM_SelectAllText: [["number", "number"], "boolean"],
8575  FORM_SetFocusedAnnot: [["number", "number"], "boolean"],
8576  FORM_SetIndexSelected: [["number", "number", "number", "boolean"], "boolean"],
8577  FORM_Undo: [["number", "number"], "boolean"],
8578  FPDF_AddInstalledFont: [["number", "number", "number"], null],
8579  FPDF_CloseDocument: [["number"], null],
8580  FPDF_ClosePage: [["number"], null],
8581  FPDF_CloseXObject: [["number"], null],
8582  FPDF_CopyViewerPreferences: [["number", "number"], "boolean"],
8583  FPDF_CountNamedDests: [["number"], "number"],
8584  FPDF_CreateClipPath: [["number", "number", "number", "number"], "number"],
8585  FPDF_CreateNewDocument: [[], "number"],
8586  FPDF_DestroyClipPath: [["number"], null],
8587  FPDF_DestroyLibrary: [[], null],
8588  FPDF_DeviceToPage: [
8589    [
8590      "number",
8591      "number",
8592      "number",
8593      "number",
8594      "number",
8595      "number",
8596      "number",
8597      "number",
8598      "number",
8599      "number"
8600    ],
8601    "boolean"
8602  ],
8603  FPDF_DocumentHasValidCrossReferenceTable: [["number"], "boolean"],
8604  FPDF_FFLDraw: [
8605    [
8606      "number",
8607      "number",
8608      "number",
8609      "number",
8610      "number",
8611      "number",
8612      "number",
8613      "number",
8614      "number"
8615    ],
8616    null
8617  ],
8618  FPDF_FreeDefaultSystemFontInfo: [["number"], null],
8619  FPDF_GetDefaultSystemFontInfo: [[], "number"],
8620  FPDF_GetDefaultTTFMap: [[], "number"],
8621  FPDF_GetDefaultTTFMapCount: [[], "number"],
8622  FPDF_GetDefaultTTFMapEntry: [["number"], "number"],
8623  FPDF_GetDocPermissions: [["number"], "number"],
8624  FPDF_GetDocUserPermissions: [["number"], "number"],
8625  FPDF_GetFileIdentifier: [["number", "number", "number", "number"], "number"],
8626  FPDF_GetFileVersion: [["number", "number"], "boolean"],
8627  FPDF_GetFormType: [["number"], "number"],
8628  FPDF_GetLastError: [[], "number"],
8629  FPDF_GetMetaText: [["number", "string", "number", "number"], "number"],
8630  FPDF_GetNamedDest: [["number", "number", "number", "number"], "number"],
8631  FPDF_GetNamedDestByName: [["number", "string"], "number"],
8632  FPDF_GetPageAAction: [["number", "number"], "number"],
8633  FPDF_GetPageBoundingBox: [["number", "number"], "boolean"],
8634  FPDF_GetPageCount: [["number"], "number"],
8635  FPDF_GetPageHeight: [["number"], "number"],
8636  FPDF_GetPageHeightF: [["number"], "number"],
8637  FPDF_GetPageLabel: [["number", "number", "number", "number"], "number"],
8638  FPDF_GetPageSizeByIndex: [["number", "number", "number", "number"], "number"],
8639  FPDF_GetPageSizeByIndexF: [["number", "number", "number"], "boolean"],
8640  FPDF_GetPageWidth: [["number"], "number"],
8641  FPDF_GetPageWidthF: [["number"], "number"],
8642  FPDF_GetSecurityHandlerRevision: [["number"], "number"],
8643  FPDF_GetSignatureCount: [["number"], "number"],
8644  FPDF_GetSignatureObject: [["number", "number"], "number"],
8645  FPDF_GetTrailerEnds: [["number", "number", "number"], "number"],
8646  FPDF_GetXFAPacketContent: [
8647    ["number", "number", "number", "number", "number"],
8648    "boolean"
8649  ],
8650  FPDF_GetXFAPacketCount: [["number"], "number"],
8651  FPDF_GetXFAPacketName: [["number", "number", "number", "number"], "number"],
8652  FPDF_ImportNPagesToOne: [
8653    ["number", "number", "number", "number", "number"],
8654    "number"
8655  ],
8656  FPDF_ImportPages: [["number", "number", "string", "number"], "boolean"],
8657  FPDF_ImportPagesByIndex: [
8658    ["number", "number", "number", "number", "number"],
8659    "boolean"
8660  ],
8661  FPDF_InitLibrary: [[], null],
8662  FPDF_InitLibraryWithConfig: [["number"], null],
8663  FPDF_LoadCustomDocument: [["number", "string"], "number"],
8664  FPDF_LoadDocument: [["number", "string"], "number"],
8665  FPDF_LoadMemDocument: [["number", "number", "string"], "number"],
8666  FPDF_LoadMemDocument64: [["number", "number", "string"], "number"],
8667  FPDF_LoadPage: [["number", "number"], "number"],
8668  FPDF_LoadXFA: [["number"], "boolean"],
8669  FPDF_MovePages: [["number", "number", "number", "number"], "boolean"],
8670  FPDF_NewFormObjectFromXObject: [["number"], "number"],
8671  FPDF_NewXObjectFromPage: [["number", "number", "number"], "number"],
8672  FPDF_PageToDevice: [
8673    [
8674      "number",
8675      "number",
8676      "number",
8677      "number",
8678      "number",
8679      "number",
8680      "number",
8681      "number",
8682      "number",
8683      "number"
8684    ],
8685    "boolean"
8686  ],
8687  FPDF_RemoveFormFieldHighlight: [["number"], null],
8688  FPDF_RenderPage_Close: [["number"], null],
8689  FPDF_RenderPage_Continue: [["number", "number"], "number"],
8690  FPDF_RenderPageBitmap: [
8691    ["number", "number", "number", "number", "number", "number", "number", "number"],
8692    null
8693  ],
8694  FPDF_RenderPageBitmap_Start: [
8695    [
8696      "number",
8697      "number",
8698      "number",
8699      "number",
8700      "number",
8701      "number",
8702      "number",
8703      "number",
8704      "number"
8705    ],
8706    "number"
8707  ],
8708  FPDF_RenderPageBitmapWithColorScheme_Start: [
8709    [
8710      "number",
8711      "number",
8712      "number",
8713      "number",
8714      "number",
8715      "number",
8716      "number",
8717      "number",
8718      "number",
8719      "number"
8720    ],
8721    "number"
8722  ],
8723  FPDF_RenderPageBitmapWithMatrix: [
8724    ["number", "number", "number", "number", "number"],
8725    null
8726  ],
8727  FPDF_SaveAsCopy: [["number", "number", "number"], "boolean"],
8728  FPDF_SaveWithVersion: [["number", "number", "number", "number"], "boolean"],
8729  FPDF_SetFormFieldHighlightAlpha: [["number", "number"], null],
8730  FPDF_SetFormFieldHighlightColor: [["number", "number", "number"], null],
8731  FPDF_SetSandBoxPolicy: [["number", "boolean"], null],
8732  FPDF_SetSystemFontInfo: [["number"], null],
8733  FPDF_StructElement_Attr_CountChildren: [["number"], "number"],
8734  FPDF_StructElement_Attr_GetBlobValue: [
8735    ["number", "number", "number", "number"],
8736    "boolean"
8737  ],
8738  FPDF_StructElement_At
8738tr_GetBooleanValue: [["number", "number"], "boolean"],
8739  FPDF_StructElement_Attr_GetChildAtIndex: [["number", "number"], "number"],
8740  FPDF_StructElement_Attr_GetCount: [["number"], "number"],
8741  FPDF_StructElement_Attr_GetName: [
8742    ["number", "number", "number", "number", "number"],
8743    "boolean"
8744  ],
8745  FPDF_StructElement_Attr_GetNumberValue: [["number", "number"], "boolean"],
8746  FPDF_StructElement_Attr_GetStringValue: [
8747    ["number", "number", "number", "number"],
8748    "boolean"
8749  ],
8750  FPDF_StructElement_Attr_GetType: [["number"], "number"],
8751  FPDF_StructElement_Attr_GetValue: [["number", "string"], "number"],
8752  FPDF_StructElement_CountChildren: [["number"], "number"],
8753  FPDF_StructElement_GetActualText: [["number", "number", "number"], "number"],
8754  FPDF_StructElement_GetAltText: [["number", "number", "number"], "number"],
8755  FPDF_StructElement_GetAttributeAtIndex: [["number", "number"], "number"],
8756  FPDF_StructElement_GetAttributeCount: [["number"], "number"],
8757  FPDF_StructElement_GetChildAtIndex: [["number", "number"], "number"],
8758  FPDF_StructElement_GetChildMarkedContentID: [["number", "number"], "number"],
8759  FPDF_StructElement_GetID: [["number", "number", "number"], "number"],
8760  FPDF_StructElement_GetLang: [["number", "number", "number"], "number"],
8761  FPDF_StructElement_GetMarkedContentID: [["number"], "number"],
8762  FPDF_StructElement_GetMarkedContentIdAtIndex: [["number", "number"], "number"],
8763  FPDF_StructElement_GetMarkedContentIdCount: [["number"], "number"],
8764  FPDF_StructElement_GetObjType: [["number", "number", "number"], "number"],
8765  FPDF_StructElement_GetParent: [["number"], "number"],
8766  FPDF_StructElement_GetStringAttribute: [
8767    ["number", "string", "number", "number"],
8768    "number"
8769  ],
8770  FPDF_StructElement_GetTitle: [["number", "number", "number"], "number"],
8771  FPDF_StructElement_GetType: [["number", "number", "number"], "number"],
8772  FPDF_StructTree_Close: [["number"], null],
8773  FPDF_StructTree_CountChildren: [["number"], "number"],
8774  FPDF_StructTree_GetChildAtIndex: [["number", "number"], "number"],
8775  FPDF_StructTree_GetForPage: [["number"], "number"],
8776  FPDF_VIEWERREF_GetDuplex: [["number"], "number"],
8777  FPDF_VIEWERREF_GetName: [["number", "string", "number", "number"], "number"],
8778  FPDF_VIEWERREF_GetNumCopies: [["number"], "number"],
8779  FPDF_VIEWERREF_GetPrintPageRange: [["number"], "number"],
8780  FPDF_VIEWERREF_GetPrintPageRangeCount: [["number"], "number"],
8781  FPDF_VIEWERREF_GetPrintPageRangeElement: [["number", "number"], "number"],
8782  FPDF_VIEWERREF_GetPrintScaling: [["number"], "boolean"],
8783  FPDFAction_GetDest: [["number", "number"], "number"],
8784  FPDFAction_GetFilePath: [["number", "number", "number"], "number"],
8785  FPDFAction_GetType: [["number"], "number"],
8786  FPDFAction_GetURIPath: [["number", "number", "number", "number"], "number"],
8787  FPDFAnnot_AddFileAttachment: [["number", "number"], "number"],
8788  FPDFAnnot_AddInkStroke: [["number", "number", "number"], "number"],
8789  FPDFAnnot_AppendAttachmentPoints: [["number", "number"], "boolean"],
8790  FPDFAnnot_AppendObject: [["number", "number"], "boolean"],
8791  FPDFAnnot_CountAttachmentPoints: [["number"], "number"],
8792  FPDFAnnot_GetAP: [["number", "number", "number", "number"], "number"],
8793  FPDFAnnot_GetAttachmentPoints: [["number", "number", "number"], "boolean"],
8794  FPDFAnnot_GetBorder: [["number", "number", "number", "number"], "boolean"],
8795  FPDFAnnot_GetColor: [
8796    ["number", "number", "number", "number", "number", "number"],
8797    "boolean"
8798  ],
8799  FPDFAnnot_GetFileAttachment: [["number"], "number"],
8800  FPDFAnnot_GetFlags: [["number"], "number"],
8801  FPDFAnnot_GetFocusableSubtypes: [["number", "number", "number"], "boolean"],
8802  FPDFAnnot_GetFocusableSubtypesCount: [["number"], "number"],
8803  FPDFAnnot_GetFontColor: [
8804    ["number", "number", "number", "number", "number"],
8805    "boolean"
8806  ],
8807  FPDFAnnot_GetFontSize: [["number", "number", "number"], "boolean"],
8808  FPDFAnnot_GetFormAdditionalActionJavaScript: [
8809    ["number", "number", "number", "number", "number"],
8810    "number"
8811  ],
8812  FPDFAnnot_GetFormControlCount: [["number", "number"], "number"],
8813  FPDFAnnot_GetFormControlIndex: [["number", "number"], "number"],
8814  FPDFAnnot_GetFormFieldAlternateName: [
8815    ["number", "number", "number", "number"],
8816    "number"
8817  ],
8818  FPDFAnnot_GetFormFieldAtPoint: [["number", "number", "number"], "number"],
8819  FPDFAnnot_GetFormFieldExportValue: [
8820    ["number", "number", "number", "number"],
8821    "number"
8822  ],
8823  FPDFAnnot_GetFormFieldFlags: [["number", "number"], "number"],
8824  FPDFAnnot_GetFormFieldName: [
8825    ["number", "number", "number", "number"],
8826    "number"
8827  ],
8828  FPDFAnnot_GetFormFieldType: [["number", "number"], "number"],
8829  FPDFAnnot_GetFormFieldValue: [
8830    ["number", "number", "number", "number"],
8831    "number"
8832  ],
8833  FPDFAnnot_GetInkListCount: [["number"], "number"],
8834  FPDFAnnot_GetInkListPath: [["number", "number", "number", "number"], "number"],
8835  FPDFAnnot_GetLine: [["number", "number", "number"], "boolean"],
8836  FPDFAnnot_GetLink: [["number"], "number"],
8837  FPDFAnnot_GetLinkedAnnot: [["number", "string"], "number"],
8838  FPDFAnnot_GetNumberValue: [["number", "string", "number"], "boolean"],
8839  FPDFAnnot_GetObject: [["number", "number"], "number"],
8840  FPDFAnnot_GetObjectCount: [["number"], "number"],
8841  FPDFAnnot_GetOptionCount: [["number", "number"], "number"],
8842  FPDFAnnot_GetOptionLabel: [
8843    ["number", "number", "number", "number", "number"],
8844    "number"
8845  ],
8846  FPDFAnnot_GetRect: [["number", "number"], "boolean"],
8847  FPDFAnnot_GetStringValue: [["number", "string", "number", "number"], "number"],
8848  FPDFAnnot_GetSubtype: [["number"], "number"],
8849  FPDFAnnot_GetValueType: [["number", "string"], "number"],
8850  FPDFAnnot_GetVertices: [["number", "number", "number"], "number"],
8851  FPDFAnnot_HasAttachmentPoints: [["number"], "boolean"],
8852  FPDFAnnot_HasKey: [["number", "string"], "boolean"],
8853  FPDFAnnot_IsChecked: [["number", "number"], "boolean"],
8854  FPDFAnnot_IsObjectSupportedSubtype: [["number"], "boolean"],
8855  FPDFAnnot_IsOptionSelected: [["number", "number", "number"], "boolean"],
8856  FPDFAnnot_IsSupportedSubtype: [["number"], "boolean"],
8857  FPDFAnnot_RemoveInkList: [["number"], "boolean"],
8858  FPDFAnnot_RemoveObject: [["number", "number"], "boolean"],
8859  FPDFAnnot_SetAP: [["number", "number", "number"], "boolean"],
8860  FPDFAnnot_SetAttachmentPoints: [["number", "number", "number"], "boolean"],
8861  FPDFAnnot_SetBorder: [["number", "number", "number", "number"], "boolean"],
8862  FPDFAnnot_SetColor: [
8863    ["number", "number", "number", "number", "number", "number"],
8864    "boolean"
8865  ],
8866  FPDFAnnot_SetFlags: [["number", "number"], "boolean"],
8867  FPDFAnnot_SetFocusableSubtypes: [["number", "number", "number"], "boolean"],
8868  FPDFAnnot_SetFontColor: [
8869    ["number", "number", "number", "number", "number"],
8870    "boolean"
8871  ],
8872  FPDFAnnot_SetFormFieldFlags: [["number", "number", "number"], "boolean"],
8873  FPDFAnnot_SetRect: [["number", "number"], "boolean"],
8874  FPDFAnnot_SetStringValue: [["number", "string", "number"], "boolean"],
8875  FPDFAnnot_SetURI: [["number", "number"], "boolean"],
8876  FPDFAnnot_UpdateObject: [["number", "number"], "boolean"],
8877  FPDFAttachment_GetFile: [["number", "number", "number", "number"], "boolean"],
8878  FPDFAttachment_GetName: [["number", "number", "number"], "number"],
8879  FPDFAttachment_GetStringValue: [
8880    ["number", "string", "number", "number"],
8881    "number"
8882  ],
8883  FPDFAttachment_GetSubtype: [["number", "number", "number"], "number"],
8884  FPDFAttachment_GetValueType: [["number", "string"], "number"],
8885  FPDFAttachment_HasKey: [["number", "string"], "boolean"],
8886  FPDFAttachment_SetFile: [["number", "number", "number", "number"], "boolean"],
8887  FPDFAttachment_SetStringValue: [["number", "string", "number"], "boolean"],
8888  FPDFAvail_Create: [["number", "number"], "number"],
8889  FPDFAvail_Destroy: [["number"], null],
8890  FPDFAvail_GetDocument: [["number", "string"], "number"],
8891  FPDFAvail_GetFirstPageNum: [["number"], "number"],
8892  FPDFAvail_IsDocAvail: [["number", "number"], "number"],
8893  FPDFAvail_IsFormAvail: [["number", "number"], "number"],
8894  FPDFAvail_IsLinearized: [["number"], "number"],
8895  FPDFAvail_IsPageAvail: [["number", "number", "number"], "number"],
8896  FPDFBitmap_Create: [["number", "number", "number"], "number"],
8897  FPDFBitmap_CreateEx: [
8898    ["number", "number", "number", "number", "number"],
8899    "number"
8900  ],
8901  FPDFBitmap_Destroy: [["number"], null],
8902  FPDFBitmap_FillRect: [
8903    ["number", "number", "number", "number", "number", "number"],
8904    "boolean"
8905  ],
8906  FPDFBitmap_GetBuffer: [["number"], "number"],
8907  FPDFBitmap_GetFormat: [["number"], "number"],
8908  FPDFBitmap_GetHeight: [["number"], "number"],
8909  FPDFBitmap_GetStride: [["number"], "number"],
8910  FPDFBitmap_GetWidth: [["number"], "number"],
8911  FPDFBookmark_Find: [["number", "number"], "number"],
8912  FPDFBookmark_GetAction: [["number"], "number"],
8913  FPDFBookmark_GetCount: [["number"], "number"],
8914  FPDFBookmark_GetDest: [["number", "number"], "number"],
8915  FPDFBookmark_GetFirstChild: [["number", "number"], "number"],
8916  FPDFBookmark_GetNextSibling: [["number", "number"], "number"],
8917  FPDFBookmark_GetTitle: [["number", "number", "number"], "number"],
8918  FPDFCatalog_GetLanguage: [["number", "number", "number"], "number"],
8919  FPDFCatalog_IsTagged: [["number"], "boolean"],
8920  FPDFCatalog_SetLanguage: [["number", "number"], "boolean"],
8921  FPDFClipPath_CountPaths: [["number"], "number"],
8922  FPDFClipPath_CountPathSegments: [["number", "number"], "number"],
8923  FPDFClipPath_GetPathSegment: [["number", "number", "number"], "number"],
8924  FPDFDest_GetDestPageIndex: [["number", "number"], "number"],
8925  FPDFDest_GetLocationInPage: [
8926    ["number", "number", "number", "number", "number", "number", "number"],
8927    "boolean"
8928  ],
8929  FPDFDest_GetView: [["number", "number", "number"], "number"],
8930  FPDFDoc_AddAttachment: [["number", "number"], "number"],
8931  FPDFDoc_CloseJavaScriptAction: [["number"], null],
8932  FPDFDoc_DeleteAttachment: [["number", "number"], "boolean"],
8933  FPDFDOC_ExitFormFillEnvironment: [["number"], null],
8934  FPDFDoc_GetAttachment: [["number", "number"], "number"],
8935  FPDFDoc_GetAttachmentCount: [["number"], "number"],
8936  FPDFDoc_GetJavaScriptAction: [["number", "number"], "number"],
8937  FPDFDoc_GetJavaScriptActionCount: [["number"], "number"],
8938  FPDFDoc_GetPageMode: [["number"], "number"],
8939  FPDFDOC_InitFormFillEnvironment: [["number", "number"], "number"],
8940  FPDFFont_Close: [["number"], null],
8941  FPDFFont_GetAscent: [["number", "number", "number"], "boolean"],
8942  FPDFFont_GetBaseFontName: [["number", "number", "number"], "number"],
8943  FPDFFont_GetDescent: [["number", "number", "number"], "boolean"],
8944  FPDFFont_GetFamilyName: [["number", "number", "number"], "number"],
8945  FPDFFont_GetFlags: [["number"], "number"],
8946  FPDFFont_GetFontData: [["number", "number", "number", "number"], "boolean"],
8947  FPDFFont_GetGlyphPath: [["number", "number", "number"], "number"],
8948  FPDFFont_GetGlyphWidth: [["number", "number", "number", "number"], "boolean"],
8949  FPDFFont_GetIsEmbedded: [["number"], "number"],
8950  FPDFFont_GetItalicAngle: [["number", "number"], "boolean"],
8951  FPDFFont_GetWeight: [["number"], "number"],
8952  FPDFFormObj_CountObjects: [["number"], "number"],
8953  FPDFFormObj_GetObject: [["number", "number"], "number"],
8954  FPDFFormObj_RemoveObject: [["number", "number"], "boolean"],
8955  FPDFGlyphPath_CountGlyphSegments: [["number"], "number"],
8956  FPDFGlyphPath_GetGlyphPathSegment: [["number", "number"], "number"],
8957  FPDFImageObj_GetBitmap: [["number"], "number"],
8958  FPDFImageObj_GetIccProfileDataDecoded: [
8959    ["number", "number", "number", "number", "number"],
8960    "boolean"
8961  ],
8962  FPDFImageObj_GetImageDataDecoded: [["number", "number", "number"], "number"],
8963  FPDFImageObj_GetImageDataRaw: [["number", "number", "number"], "number"],
8964  FPDFImageObj_GetImageFilter: [
8965    ["number", "number", "number", "number"],
8966    "number"
8967  ],
8968  FPDFImageObj_GetImageFilterCount: [["number"], "number"],
8969  FPDFImageObj_GetImageMetadata: [["number", "number", "number"], "boolean"],
8970  FPDFImageObj_GetImagePixelSize: [["number", "number", "number"], "boolean"],
8971  FPDFImageObj_GetRenderedBitmap: [["number", "number", "number"], "number"],
8972  FPDFImageObj_LoadJpegFile: [
8973    ["number", "number", "number", "number"],
8974    "boolean"
8975  ],
8976  FPDFImageObj_LoadJpegFileInline: [
8977    ["number", "number", "number", "number"],
8978    "boolean"
8979  ],
8980  FPDFImageObj_SetBitmap: [["number", "number", "number", "number"], "boolean"],
vendor: 9,163 bytes, lines 8981-9188
8981  FPDFImageObj_SetMatrix: [
8982    ["number", "number", "number", "number", "number", "number", "number"],
8983    "boolean"
8984  ],
8985  FPDFJavaScriptAction_GetName: [["number", "number", "number"], "number"],
8986  FPDFJavaScriptAction_GetScript: [["number", "number", "number"], "number"],
8987  FPDFLink_CloseWebLinks: [["number"], null],
8988  FPDFLink_CountQuadPoints: [["number"], "number"],
8989  FPDFLink_CountRects: [["number", "number"], "number"],
8990  FPDFLink_CountWebLinks: [["number"], "number"],
8991  FPDFLink_Enumerate: [["number", "number", "number"], "boolean"],
8992  FPDFLink_GetAction: [["number"], "number"],
8993  FPDFLink_GetAnnot: [["number", "number"], "number"],
8994  FPDFLink_GetAnnotRect: [["number", "number"], "boolean"],
8995  FPDFLink_GetDest: [["number", "number"], "number"],
8996  FPDFLink_GetLinkAtPoint: [["number", "number", "number"], "number"],
8997  FPDFLink_GetLinkZOrderAtPoint: [["number", "number", "number"], "number"],
8998  FPDFLink_GetQuadPoints: [["number", "number", "number"], "boolean"],
8999  FPDFLink_GetRect: [
9000    ["number", "number", "number", "number", "number", "number", "number"],
9001    "boolean"
9002  ],
9003  FPDFLink_GetTextRange: [["number", "number", "number", "number"], "boolean"],
9004  FPDFLink_GetURL: [["number", "number", "number", "number"], "number"],
9005  FPDFLink_LoadWebLinks: [["number"], "number"],
9006  FPDFPage_CloseAnnot: [["number"], null],
9007  FPDFPage_CountObjects: [["number"], "number"],
9008  FPDFPage_CreateAnnot: [["number", "number"], "number"],
9009  FPDFPage_Delete: [["number", "number"], null],
9010  FPDFPage_Flatten: [["number", "number"], "number"],
9011  FPDFPage_FormFieldZOrderAtPoint: [
9012    ["number", "number", "number", "number"],
9013    "number"
9014  ],
9015  FPDFPage_GenerateContent: [["number"], "boolean"],
9016  FPDFPage_GetAnnot: [["number", "number"], "number"],
9017  FPDFPage_GetAnnotCount: [["number"], "number"],
9018  FPDFPage_GetAnnotIndex: [["number", "number"], "number"],
9019  FPDFPage_GetArtBox: [
9020    ["number", "number", "number", "number", "number"],
9021    "boolean"
9022  ],
9023  FPDFPage_GetBleedBox: [
9024    ["number", "number", "number", "number", "number"],
9025    "boolean"
9026  ],
9027  FPDFPage_GetCropBox: [
9028    ["number", "number", "number", "number", "number"],
9029    "boolean"
9030  ],
9031  FPDFPage_GetDecodedThumbnailData: [["number", "number", "number"], "number"],
9032  FPDFPage_GetMediaBox: [
9033    ["number", "number", "number", "number", "number"],
9034    "boolean"
9035  ],
9036  FPDFPage_GetObject: [["number", "number"], "number"],
9037  FPDFPage_GetRawThumbnailData: [["number", "number", "number"], "number"],
9038  FPDFPage_GetRotation: [["number"], "number"],
9039  FPDFPage_GetThumbnailAsBitmap: [["number"], "number"],
9040  FPDFPage_GetTrimBox: [
9041    ["number", "number", "number", "number", "number"],
9042    "boolean"
9043  ],
9044  FPDFPage_HasFormFieldAtPoint: [
9045    ["number", "number", "number", "number"],
9046    "number"
9047  ],
9048  FPDFPage_HasTransparency: [["number"], "boolean"],
9049  FPDFPage_InsertClipPath: [["number", "number"], null],
9050  FPDFPage_InsertObject: [["number", "number"], null],
9051  FPDFPage_InsertObjectAtIndex: [["number", "number", "number"], "boolean"],
9052  FPDFPage_New: [["number", "number", "number", "number"], "number"],
9053  FPDFPage_RemoveAnnot: [["number", "number"], "boolean"],
9054  FPDFPage_RemoveObject: [["number", "number"], "boolean"],
9055  FPDFPage_SetArtBox: [["number", "number", "number", "number", "number"], null],
9056  FPDFPage_SetBleedBox: [
9057    ["number", "number", "number", "number", "number"],
9058    null
9059  ],
9060  FPDFPage_SetCropBox: [["number", "number", "number", "number", "number"], null],
9061  FPDFPage_SetMediaBox: [
9062    ["number", "number", "number", "number", "number"],
9063    null
9064  ],
9065  FPDFPage_SetRotation: [["number", "number"], null],
9066  FPDFPage_SetTrimBox: [["number", "number", "number", "number", "number"], null],
9067  FPDFPage_TransformAnnots: [
9068    ["number", "number", "number", "number", "number", "number", "number"],
9069    null
9070  ],
9071  FPDFPage_TransFormWithClip: [["number", "number", "number"], "boolean"],
9072  FPDFPageObj_AddMark: [["number", "string"], "number"],
9073  FPDFPageObj_CountMarks: [["number"], "number"],
9074  FPDFPageObj_CreateNewPath: [["number", "number"], "number"],
9075  FPDFPageObj_CreateNewRect: [["number", "number", "number", "number"], "number"],
9076  FPDFPageObj_CreateTextObj: [["number", "number", "number"], "number"],
9077  FPDFPageObj_Destroy: [["number"], null],
9078  FPDFPageObj_GetBounds: [
9079    ["number", "number", "number", "number", "number"],
9080    "boolean"
9081  ],
9082  FPDFPageObj_GetClipPath: [["number"], "number"],
9083  FPDFPageObj_GetDashArray: [["number", "number", "number"], "boolean"],
9084  FPDFPageObj_GetDashCount: [["number"], "number"],
9085  FPDFPageObj_GetDashPhase: [["number", "number"], "boolean"],
9086  FPDFPageObj_GetFillColor: [
9087    ["number", "number", "number", "number", "number"],
9088    "boolean"
9089  ],
9090  FPDFPageObj_GetIsActive: [["number", "number"], "boolean"],
9091  FPDFPageObj_GetLineCap: [["number"], "number"],
9092  FPDFPageObj_GetLineJoin: [["number"], "number"],
9093  FPDFPageObj_GetMark: [["number", "number"], "number"],
9094  FPDFPageObj_GetMarkedContentID: [["number"], "number"],
9095  FPDFPageObj_GetMatrix: [["number", "number"], "boolean"],
9096  FPDFPageObj_GetRotatedBounds: [["number", "number"], "boolean"],
9097  FPDFPageObj_GetStrokeColor: [
9098    ["number", "number", "number", "number", "number"],
9099    "boolean"
9100  ],
9101  FPDFPageObj_GetStrokeWidth: [["number", "number"], "boolean"],
9102  FPDFPageObj_GetType: [["number"], "number"],
9103  FPDFPageObj_HasTransparency: [["number"], "boolean"],
9104  FPDFPageObj_NewImageObj: [["number"], "number"],
9105  FPDFPageObj_NewTextObj: [["number", "string", "number"], "number"],
9106  FPDFPageObj_RemoveMark: [["number", "number"], "boolean"],
9107  FPDFPageObj_SetBlendMode: [["number", "string"], null],
9108  FPDFPageObj_SetDashArray: [["number", "number", "number", "number"], "boolean"],
9109  FPDFPageObj_SetDashPhase: [["number", "number"], "boolean"],
9110  FPDFPageObj_SetFillColor: [
9111    ["number", "number", "number", "number", "number"],
9112    "boolean"
9113  ],
9114  FPDFPageObj_SetIsActive: [["number", "boolean"], "boolean"],
9115  FPDFPageObj_SetLineCap: [["number", "number"], "boolean"],
9116  FPDFPageObj_SetLineJoin: [["number", "number"], "boolean"],
9117  FPDFPageObj_SetMatrix: [["number", "number"], "boolean"],
9118  FPDFPageObj_SetStrokeColor: [
9119    ["number", "number", "number", "number", "number"],
9120    "boolean"
9121  ],
9122  FPDFPageObj_SetStrokeWidth: [["number", "number"], "boolean"],
9123  FPDFPageObj_Transform: [
9124    ["number", "number", "number", "number", "number", "number", "number"],
9125    null
9126  ],
9127  FPDFPageObj_TransformClipPath: [
9128    ["number", "number", "number", "number", "number", "number", "number"],
9129    null
9130  ],
9131  FPDFPageObj_TransformF: [["number", "number"], "boolean"],
9132  FPDFPageObjMark_CountParams: [["number"], "number"],
9133  FPDFPageObjMark_GetName: [["number", "number", "number", "number"], "boolean"],
9134  FPDFPageObjMark_GetParamBlobValue: [
9135    ["number", "string", "number", "number", "number"],
9136    "boolean"
9137  ],
9138  FPDFPageObjMark_GetParamFloatValue: [["number", "string", "number"], "boolean"],
9139  FPDFPageObjMark_GetParamIntValue: [["number", "string", "number"], "boolean"],
9140  FPDFPageObjMark_GetParamKey: [
9141    ["number", "number", "number", "number", "number"],
9142    "boolean"
9143  ],
9144  FPDFPageObjMark_GetParamStringValue: [
9145    ["number", "string", "number", "number", "number"],
9146    "boolean"
9147  ],
9148  FPDFPageObjMark_GetParamValueType: [["number", "string"], "number"],
9149  FPDFPageObjMark_RemoveParam: [["number", "number", "string"], "boolean"],
9150  FPDFPageObjMark_SetBlobParam: [
9151    ["number", "number", "number", "string", "number", "number"],
9152    "boolean"
9153  ],
9154  FPDFPageObjMark_SetFloatParam: [
9155    ["number", "number", "number", "string", "number"],
9156    "boolean"
9157  ],
9158  FPDFPageObjMark_SetIntParam: [
9159    ["number", "number", "number", "string", "number"],
9160    "boolean"
9161  ],
9162  FPDFPageObjMark_SetStringParam: [
9163    ["number", "number", "number", "string", "string"],
9164    "boolean"
9165  ],
9166  FPDFPath_BezierTo: [
9167    ["number", "number", "number", "number", "number", "number", "number"],
9168    "boolean"
9169  ],
9170  FPDFPath_Close: [["number"], "boolean"],
9171  FPDFPath_CountSegments: [["number"], "number"],
9172  FPDFPath_GetDrawMode: [["number", "number", "number"], "boolean"],
9173  FPDFPath_GetPathSegment: [["number", "number"], "number"],
9174  FPDFPath_LineTo: [["number", "number", "number"], "boolean"],
9175  FPDFPath_MoveTo: [["number", "number", "number"], "boolean"],
9176  FPDFPath_SetDrawMode: [["number", "number", "boolean"], "boolean"],
9177  FPDFPathSegment_GetClose: [["number"], "boolean"],
9178  FPDFPathSegment_GetPoint: [["number", "number", "number"], "boolean"],
9179  FPDFPathSegment_GetType: [["number"], "number"],
9180  FPDFSignatureObj_GetByteRange: [["number", "number", "number"], "number"],
9181  FPDFSignatureObj_GetContents: [["number", "number", "number"], "number"],
9182  FPDFSignatureObj_GetDocMDPPermission: [["number"], "number"],
9183  FPDFSignatureObj_GetReason: [["number", "number", "number"], "number"],
9184  FPDFSignatureObj_GetSubFilter: [["number", "number", "number"], "number"],
9185  FPDFSignatureObj_GetTime: [["number", "number", "number"], "number"],
9186  FPDFText_ClosePage: [["number"], null],
9187  FPDFText_CountChars: [["number"], "number"],
9188  FPDFText_CountRects: [["number", "number", "number"], "number"],
9189  FPDFText_FindClose: [["number"], null],
9190  FPDFText_FindNext: [["number"], "boolean"],
9191  FPDFText_FindPrev: [["number"], "boolean"],
9192  FPDFText_FindStart: [["number", "number", "number", "number"], "number"],
9193  FPDFText_GetBoundedText: [
9194    ["number", "number", "number", "number", "number", "number", "number"],
9195    "number"
9196  ],
9197  FPDFText_GetCharAngle: [["number", "number"], "number"],
9198  FPDFText_GetCharBox: [
9199    ["number", "number", "number", "number", "number", "number"],
9200    "boolean"
9201  ],
9202  FPDFText_GetCharIndexAtPos: [
9203    ["number", "number", "number", "number", "number"],
9204    "number"
9205  ],
9206  FPDFText_GetCharIndexFromTextIndex: [["number", "number"], "number"],
9207  FPDFText_GetCharOrigin: [["number", "number", "number", "number"], "boolean"],
9208  FPDFText_GetFillColor: [
9209    ["number", "number", "number", "number", "number", "number"],
9210    "boolean"
9211  ],
9212  FPDFText_GetFontInfo: [
9213    ["number", "number", "number", "number", "number"],
9214    "number"
9215  ],
9216  FPDFText_GetFontSize: [["number", "number"], "number"],
9217  FPDFText_GetFontWeight: [["number", "number"], "number"],
9218  FPDFText_GetLooseCharBox: [["number", "number", "number"], "boolean"],
9219  FPDFText_GetMatrix: [["number", "number", "number"], "boolean"],
9220  FPDFText_GetRect: [
9221    ["number", "number", "number", "number", "number", "number"],
9222    "boolean"
9223  ],
9224  FPDFText_GetSchCount: [["number"], "number"],
9225  FPDFText_GetSchResultIndex: [["number"], "number"],
9226  FPDFText_GetStrokeColor: [
9227    ["number", "number", "number", "number", "number", "number"],
9228    "boolean"
9229  ],
9230  FPDFText_GetText: [["number", "number", "number", "number"], "number"],
9231  FPDFText_GetTextIndexFromCharIndex: [["number", "number"], "number"],
9232  FPDFText_GetTextObject: [["number", "number"], "number"],
9233  FPDFText_GetUnicode: [["number", "number"], "number"],
9234  FPDFText_HasUnicodeMapError: [["number", "number"], "number"],
9235  FPDFText_IsGenerated: [["number", "number"], "number"],
9236  FPDFText_IsHyphen: [["number", "number"], "number"],
9237  FPDFText_LoadCidType2Font: [
9238    ["number", "number", "number", "string", "number", "number"],
9239    "number"
9240  ],
9241  FPDFText_LoadFont: [
9242    ["number", "number", "number", "number", "boolean"],
9243    "number"
9244  ],
9245  FPDFText_LoadPage: [["number"], "number"],
9246  FPDFText_LoadStandardFont: [["number", "string"], "number"],
9247  FPDFText_SetCharcodes: [["number", "number", "number"], "boolean"],
9248  FPDFText_SetText: [["number", "number"], "boolean"],
9249  FPDFTextObj_GetFont: [["number"], "number"],
9250  FPDFTextObj_GetFontSize: [["number", "number"], "boolean"],
9251  FPDFTextObj_GetRenderedBitmap: [
9252    ["number", "number", "number", "number"],
9253    "number"
9254  ],
9255  FPDFTextObj_GetText: [["number", "number", "number", "number"], "number"],
9256  FPDFTextObj_GetTextRenderMode: [["number"], "number"],
9257  FPDFTextObj_SetTextRenderMode: [["number", "number"], "boolean"],
9258  PDFiumExt_CloseFileWriter: [["number"], null],
9259  PDFiumExt_CloseFormFillInfo: [["number"], null],
9260  PDFiumExt_ExitFormFillEnvironment: [["number"], null],
9261  PDFiumExt_GetFileWriterData: [["number", "number", "number"], "number"],
9262  PDFiumExt_GetFileWriterSize: [["number"], "number"],
9263  PDFiumExt_Init: [[], null],
9264  PDFiumExt_InitFormFillEnvironment: [["number", "number"], "number"],
9265  PDFiumExt_OpenFileWriter: [[], "number"],
9266  PDFiumExt_OpenFormFillInfo: [[], "number"],
9267  PDFiumExt_SaveAsCopy: [["number", "number"], "number"]
9268};
9269async function createWrappedModule(pdfium) {
9270  const module = {
9271    pdfium
9272  };
9273  for (const key in functions) {
9274    const ident = key;
9275    const args = functions[ident][0];
9276    const ret = functions[ident][1];
9277    module[ident] = pdfium.cwrap(key, ret, args);
9278  }
9279  return module;
9280}
9281async function init(moduleOverrides) {
9282  const pdfium = await createPdfium(moduleOverrides);
9283  return createWrappedModule(pdfium);
9284}
9285function readString(wasmModule, readChars, parseChars, defaultLength = 100) {
9286  let buffer = wasmModule.wasmExports.malloc(defaultLength);
9287  for (let i = 0; i < defaultLength; i++) {
9288    wasmModule.HEAP8[buffer + i] = 0;
9289  }
9290  const actualLength = readChars(buffer, defaultLength);
9291  let str;
9292  if (actualLength > defaultLength) {
9293    wasmModule.wasmExports.free(buffer);
9294    buffer = wasmModule.wasmExports.malloc(actualLength);
9295    for (let i = 0; i < actualLength; i++) {
9296      wasmModule.HEAP8[buffer + i] = 0;
9297    }
9298    readChars(buffer, actualLength);
9299    str = parseChars(buffer);
9300  } else {
9301    str = parseChars(buffer);
9302  }
9303  wasmModule.wasmExports.free(buffer);
9304  return str;
9305}
9306function readArrayBuffer(wasmModule, readChars) {
9307  const bufferSize = readChars(0, 0);
9308  const bufferPtr = wasmModule.wasmExports.malloc(bufferSize);
9309  readChars(bufferPtr, bufferSize);
9310  const arrayBuffer = new ArrayBuffer(bufferSize);
9311  const view = new DataView(arrayBuffer);
9312  for (let i = 0; i < bufferSize; i++) {
9313    view.setInt8(i, wasmModule.getValue(bufferPtr + i, "i8"));
9314  }
9315  wasmModule.wasmExports.free(bufferPtr);
9316  return arrayBuffer;
9317}
9318const RESERVED_INFO_KEYS = /* @__PURE__ */ new Set([
9319  "Title",
9320  "Author",
9321  "Subject",
9322  "Keywords",
9323  "Producer",
9324  "Creator",
9325  "CreationDate",
9326  "ModDate",
9327  "Trapped"
9328]);
9329function isValidCustomKey(key) {
9330  if (!key || key.length > 127) return false;
9331  if (RESERVED_INFO_KEYS.has(key)) return false;
9332  if (key[0] === "/") return false;
9333  for (let i = 0; i < key.length; i++) {
9334    const c = key.charCodeAt(i);
9335    if (c < 32 || c > 126) return false;
9336  }
9337  return true;
9338}
9339function computeFormDrawParams(matrix, rect, pageSize, rotation) {
9340  const rectLeft = rect.origin.x;
9341  const rectBottom = rect.origin.y;
9342  const rectRight = rectLeft + rect.size.width;
9343  const rectTop = rectBottom + rect.size.height;
9344  const pageWidth = pageSize.width;
9345  const pageHeight = pageSize.height;
9346  const scaleX = Math.hypot(matrix.a, matrix.b);
9347  const scaleY = Math.hypot(matrix.c, matrix.d);
9348  const swap2 = (rotation & 1) === 1;
9349  const formsWidth = swap2 ? Math.max(1, Math.round(pageHeight * scaleX)) : Math.max(1, Math.round(pageWidth * scaleX));
9350  const formsHeight = swap2 ? Math.max(1, Math.round(pageWidth * scaleY)) : Math.max(1, Math.round(pageHeight * scaleY));
9351  let startX;
9352  let startY;
9353  switch (rotation) {
9354    case Rotation.Degree0:
9355      startX = -Math.round(rectLeft * scaleX);
9356      startY = -Math.round(rectBottom * scaleY);
9357      break;
9358    case Rotation.Degree90:
9359      startX = Math.round((rectTop - pageHeight) * scaleX);
9360      startY = -Math.round(rectLeft * scaleY);
9361      break;
9362    case Rotation.Degree180:
9363      startX = Math.round((rectRight - pageWidth) * scaleX);
9364      startY = Math.round((rectTop - pageHeight) * scaleY);
9365      break;
9366    case Rotation.Degree270:
9367      startX = -Math.round(rectBottom * scaleX);
9368      startY = Math.round((rectRight - pageWidth) * scaleY);
9369      break;
9370    default:
9371      startX = -Math.round(rectLeft * scaleX);
9372      startY = -Math.round(rectBottom * scaleY);
9373      break;
9374  }
9375  return { startX, startY, formsWidth, formsHeight, scaleX, scaleY };
9376}
9377const WasmPointer = (ptr) => ptr;
9378const DEFAULT_CONFIG = {
9379  pageTtl: 5e3,
9380  // 5 seconds
9381  maxPagesPerDocument: 10,
9382  normalizeRotation: false
9383};
9384class PdfCache {
9385  constructor(pdfium, memoryManager, config = {}) {
9386    this.pdfium = pdfium;
9387    this.memoryManager = memoryManager;
9388    this.docs = /* @__PURE__ */ new Map();
9389    this.config = { ...DEFAULT_CONFIG, ...config };
9390  }
9391  /** Open (or re-use) a document */
9392  setDocument(id, filePtr, docPtr, normalizeRotation = false) {
9393    let ctx = this.docs.get(id);
9394    if (!ctx) {
9395      const docConfig = { ...this.config, normalizeRotation };
9396      ctx = new DocumentContext(filePtr, docPtr, this.pdfium, this.memoryManager, docConfig);
9397      this.docs.set(id, ctx);
9398    }
9399  }
9400  /** Retrieve the DocumentContext for a given PdfDocumentObject */
9401  getContext(docId) {
9402    return this.docs.get(docId);
9403  }
9404  /** Close & fully release a document and all its pages */
9405  closeDocument(docId) {
9406    const ctx = this.docs.get(docId);
9407    if (!ctx) return false;
9408    this.docs.delete(docId);
9409    ctx.dispose();
9410    return true;
9411  }
9412  /** Close all documents */
9413  closeAllDocuments() {
9414    for (const ctx of this.docs.values()) {
9415      ctx.dispose();
9416    }
9417    this.docs.clear();
9418  }
9419  /** Update cache configuration for all existing documents */
9420  updateConfig(newConfig) {
9421    Object.assign(this.config, newConfig);
9422    for (const ctx of this.docs.values()) {
9423      ctx.updateConfig(this.config);
9424    }
9425  }
9426  /** Get current cache statistics */
9427  getCacheStats() {
9428    const pagesByDocument = {};
9429    let totalPages = 0;
9430    for (const [docId, ctx] of this.docs.entries()) {
9431      const pageCount = ctx.getCacheSize();
9432      pagesByDocument[docId] = pageCount;
9433      totalPages += pageCount;
9434    }
9435    return {
9436      documents: this.docs.size,
9437      totalPages,
9438      pagesByDocument
9439    };
9440  }
9441}
9442class DocumentContext {
9443  constructor(filePtr, docPtr, pdfium, memoryManager, config) {
9444    this.filePtr = filePtr;
9445    this.docPtr = docPtr;
9446    this.memoryManager = memoryManager;
9447    this.disposed = false;
9448    this.normalizeRotation = config.normalizeRotation;
9449    this.pageCache = new PageCache(pdfium, docPtr, config);
9450  }
9451  /** Main accessor for pages */
9452  acquirePage(pageIdx) {
9453    return this.pageCache.acquire(pageIdx);
9454  }
9455  /** Scoped accessor for one-off / bulk operations */
9456  borrowPage(pageIdx, fn) {
9457    return this.pageCache.borrowPage(pageIdx, fn);
9458  }
9459  /** Update cache configuration */
9460  updateConfig(config) {
9461    this.pageCache.updateConfig(config);
9462  }
9463  /** Get number of pages currently in cache */
9464  getCacheSize() {
9465    return this.pageCache.size();
9466  }
9467  /** Tear down all pages + this document */
9468  dispose() {
9469    if (this.disposed) return;
9470    this.disposed = true;
9471    this.pageCache.forceReleaseAll();
9472    this.pageCache.pdf.FPDF_CloseDocument(this.docPtr);
9473    this.memoryManager.free(WasmPointer(this.filePtr));
9474  }
9475}
9476class PageCache {
9477  constructor(pdf, docPtr, config) {
9478    this.pdf = pdf;
9479    this.docPtr = docPtr;
9480    this.cache = /* @__PURE__ */ new Map();
9481    this.accessOrder = [];
9482    this.config = config;
9483  }
9484  acquire(pageIdx) {
9485    let ctx = this.cache.get(pageIdx);
9486    if (!ctx) {
9487      this.evictIfNeeded();
9488      let pagePtr;
9489      if (this.config.normalizeRotation) {
9490        pagePtr = this.pdf.EPDF_LoadPageNormalized(this.docPtr, pageIdx, 0);
9491      } else {
9492        pagePtr = this.pdf.FPDF_LoadPage(this.docPtr, pageIdx);
9493      }
9494      ctx = new PageContext(this.pdf, this.docPtr, pageIdx, pagePtr, this.config.pageTtl, () => {
9495        this.cache.delete(pageIdx);
9496        this.removeFromAccessOrder(pageIdx);
9497      });
9498      this.cache.set(pageIdx, ctx);
9499    }
9500    this.updateAccessOrder(pageIdx);
9501    ctx.clearExpiryTimer();
9502    ctx.bumpRefCount();
9503    return ctx;
9504  }
9505  /** Helper: run a function "scoped" to a page.
9506   *    – if the page was already cached  → .release() (keeps TTL logic)
9507   *    – if the page was loaded just now → .disposeImmediate() (free right away)
9508   */
9509  borrowPage(pageIdx, fn) {
9510    const existed = this.cache.has(pageIdx);
9511    const ctx = this.acquire(pageIdx);
9512    try {
9513      return fn(ctx);
9514    } finally {
9515      existed ? ctx.release() : ctx.disposeImmediate();
9516    }
9517  }
9518  forceReleaseAll() {
9519    for (const ctx of this.cache.values()) {
9520      ctx.disposeImmediate();
9521    }
9522    this.cache.clear();
9523    this.accessOrder.length = 0;
9524  }
9525  /** Update cache configuration */
9526  updateConfig(config) {
9527    this.config = config;
9528    for (const ctx of this.cache.values()) {
9529      ctx.updateTtl(config.pageTtl);
9530    }
9531    this.evictIfNeeded();
9532  }
9533  /** Get current cache size */
9534  size() {
9535    return this.cache.size;
9536  }
9537  /** Evict least recently used pages if cache exceeds max size */
9538  evictIfNeeded() {
9539    while (this.cache.size >= this.config.maxPagesPerDocument) {
9540      const lruPageIdx = this.accessOrder[0];
9541      if (lruPageIdx !== void 0) {
9542        const ctx = this.cache.get(lruPageIdx);
9543        if (ctx) {
9544          if (ctx.getRefCount() === 0) {
9545            ctx.disposeImmediate();
9546          } else {
9547            break;
9548          }
9549        } else {
9550          this.removeFromAccessOrder(lruPageIdx);
9551        }
9552      } else {
9553        break;
9554      }
9555    }
9556  }
9557  /** Update the access order for LRU tracking */
9558  updateAccessOrder(pageIdx) {
9559    this.removeFromAccessOrder(pageIdx);
9560    this.accessOrder.push(pageIdx);
9561  }
9562  /** Remove a page from the access order array */
9563  removeFromAccessOrder(pageIdx) {
9564    const index = this.accessOrder.indexOf(pageIdx);
9565    if (index > -1) {
9566      this.accessOrder.splice(index, 1);
9567    }
9568  }
9569}
9570class PageContext {
9571  constructor(pdf, docPtr, pageIdx, pagePtr, ttl, onFinalDispose) {
9572    this.pdf = pdf;
9573    this.docPtr = docPtr;
9574    this.pageIdx = pageIdx;
9575    this.pagePtr = pagePtr;
9576    this.onFinalDispose = onFinalDispose;
9577    this.refCount = 0;
9578    this.disposed = false;
9579    this.ttl = ttl;
9580  }
9581  /** Called by PageCache.acquire() */
9582  bumpRefCount() {
9583    if (this.disposed) throw new Error("Context already disposed");
9584    this.refCount++;
9585  }
9586  /** Get current reference count */
9587  getRefCount() {
9588    return this.refCount;
9589  }
9590  /** Called by PageCache.acquire() */
9591  clearExpiryTimer() {
9592    if (this.expiryTimer) {
9593      clearTimeout(this.expiryTimer);
9594      this.expiryTimer = void 0;
9595    }
9596  }
9597  /** Update TTL configuration */
9598  updateTtl(newTtl) {
9599    this.ttl = newTtl;
9600    if (this.expiryTimer && this.refCount === 0) {
9601      this.clearExpiryTimer();
9602      this.expiryTimer = setTimeout(() => this.disposeImmediate(), this.ttl);
9603    }
9604  }
9605  /** Called by PageCache.release() internally */
9606  release() {
9607    if (this.disposed) return;
9608    this.refCount--;
9609    if (this.refCount === 0) {
9610      this.expiryTimer = setTimeout(() => this.disposeImmediate(), this.ttl);
9611    }
9612  }
9613  /** Tear down _all_ sub-pointers & the page. */
9614  disposeImmediate() {
9615    if (this.disposed) return;
9616    this.disposed = true;
9617    this.clearExpiryTimer();
9618    if (this.textPagePtr !== void 0) {
9619      this.pdf.FPDFText_ClosePage(this.textPagePtr);
9620    }
9621    this.pdf.FPDF_ClosePage(this.pagePtr);
9622    this.onFinalDispose();
9623  }
9624  // ── public helpers ──
9625  /** Always safe: opens (once) and returns the text-page ptr. */
9626  getTextPage() {
9627    this.ensureAlive();
9628    if (this.textPagePtr === void 0) {
9629      this.textPagePtr = this.pdf.FPDFText_LoadPage(this.pagePtr);
9630    }
9631    return this.textPagePtr;
9632  }
9633  /**
9634   * Safely execute \`fn\` with an annotation pointer.
9635   * Pointer is ALWAYS closed afterwards.
9636   */
9637  withAnnotation(annotIdx, fn) {
9638    this.ensureAlive();
9639    const annotPtr = this.pdf.FPDFPage_GetAnnot(this.pagePtr, annotIdx);
9640    try {
9641      return fn(annotPtr);
9642    } finally {
9643      this.pdf.FPDFPage_CloseAnnot(annotPtr);
9644    }
9645  }
9646  /**
9647   * Safely execute \`fn\` with a fresh form-fill handle.
9648   * Handle is ALWAYS torn down afterwards — no caching, no stale state.
9649   */
9650  withFormHandle(fn) {
9651    this.ensureAlive();
9652    const formInfoPtr = this.pdf.PDFiumExt_OpenFormFillInfo();
9653    const formHandle = this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr, formInfoPtr);
9654    this.pdf.FORM_OnAfterLoadPage(this.pagePtr, formHandle);
9655    try {
9656      return fn(formHandle);
9657    } finally {
9658      this.pdf.FORM_OnBeforeClosePage(this.pagePtr, formHandle);
9659      this.pdf.PDFiumExt_ExitFormFillEnvironment(formHandle);
9660      this.pdf.PDFiumExt_CloseFormFillInfo(formInfoPtr);
9661    }
9662  }
9663  ensureAlive() {
9664    if (this.disposed) throw new Error("PageContext already disposed");
9665  }
9666}
9667const MEMORY_LIMITS = {
9668  /** Maximum total memory that can be allocated (2GB) */
9669  MAX_TOTAL_MEMORY: 2 * 1024 * 1024 * 1024
9670};
9671const LIMITS = {
9672  MEMORY: MEMORY_LIMITS
9673};
9674const LOG_SOURCE$3 = "PDFiumEngine";
9675const LOG_CATEGORY$3 = "MemoryManager";
9676class MemoryManager {
9677  constructor(pdfiumModule, logger) {
9678    this.pdfiumModule = pdfiumModule;
9679    this.logger = logger;
9680    this.allocations = /* @__PURE__ */ new Map();
9681    this.totalAllocated = 0;
9682  }
9683  /**
9684   * Allocate memory with tracking and validation
9685   */
9686  malloc(size) {
9687    if (this.totalAllocated + size > LIMITS.MEMORY.MAX_TOTAL_MEMORY) {
9688      throw new Error(
9689        \`Total memory usage would exceed limit: \${this.totalAllocated + size} > \${LIMITS.MEMORY.MAX_TOTAL_MEMORY}\`
9690      );
9691    }
9692    const ptr = this.pdfiumModule.pdfium.wasmExports.malloc(size);
9693    if (!ptr) {
9694      throw new Error(\`Failed to allocate \${size} bytes\`);
9695    }
9696    const allocation = {
9697      ptr: WasmPointer(ptr),
9698      size,
9699      timestamp: Date.now(),
9700      stack: this.logger.isEnabled("debug") ? new Error().stack : void 0
9701    };
9702    this.allocations.set(ptr, allocation);
9703    this.totalAllocated += size;
9704    return WasmPointer(ptr);
9705  }
9706  /**
9707   * Free memory with validation
9708   */
9709  free(ptr) {
9710    const allocation = this.allocations.get(ptr);
9711    if (!allocation) {
9712      this.logger.warn(LOG_SOURCE$3, LOG_CATEGORY$3, \`Freeing untracked pointer: \${ptr}\`);
9713    } else {
9714      this.totalAllocated -= allocation.size;
9715      this.allocations.delete(ptr);
9716    }
9717    this.pdfiumModule.pdfium.wasmExports.free(ptr);
9718  }
9719  /**
9720   * Get memory statistics
9721   */
9722  getStats() {
9723    return {
9724      totalAllocated: this.totalAllocated,
9725      allocationCount: this.allocations.size,
9726      allocations: this.logger.isEnabled("debug") ? Array.from(this.allocations.values()) : []
9727    };
9728  }
9729  /**
9730   * Check for memory leaks
9731   */
9732  checkLeaks() {
9733    if (this.allocations.size > 0) {
9734      this.logger.warn(
9735        LOG_SOURCE$3,
9736        LOG_CATEGORY$3,
9737        \`Potential memory leak: \${this.allocations.size} unfreed allocations\`
9738      );
9739      for (const [ptr, alloc] of this.allocations) {
9740        this.logger.warn(LOG_SOURCE$3, LOG_CATEGORY$3, \`  - \${ptr}: \${alloc.size} bytes\`, alloc.stack);
9741      }
9742    }
9743  }
9744}
9745const SYSFONTINFO_SIZE = 36;
9746const OFFSET_VERSION = 0;
9747const OFFSET_RELEASE = 4;
9748const OFFSET_ENUMFONTS = 8;
9749const OFFSET_MAPFONT = 12;
9750const OFFSET_GETFONT = 16;
9751const OFFSET_GETFONTDATA = 20;
9752const OFFSET_GETFACENAME = 24;
9753const OFFSET_GETFONTCHARSET = 28;
9754const OFFSET_DELETEFONT = 32;
9755const LOG_SOURCE$2 = "pdfium";
9756const LOG_CATEGORY$2 = "font-fallback";
9757class FontFallbackManager {
9758  constructor(config, logger = new NoopLogger()) {
9759    this.fontHandles = /* @__PURE__ */ new Map();
9760    this.fontCache = /* @__PURE__ */ new Map();
9761    this.nextHandleId = 1;
9762    this.module = null;
9763    this.enabled = false;
9764    this.structPtr = 0;
9765    this.releaseFnPtr = 0;
9766    this.enumFontsFnPtr = 0;
9767    this.mapFontFnPtr = 0;
9768    this.getFontFnPtr = 0;
9769    this.getFontDataFnPtr = 0;
9770    this.getFaceNameFnPtr = 0;
9771    this.getFontCharsetFnPtr = 0;
9772    this.deleteFontFnPtr = 0;
9773    this.fontConfig = config;
9774    this.logger = logger;
9775  }
9776  /**
9777   * Initialize the font fallback system and attach to PDFium module
9778   */
9779  initialize(module) {
9780    if (this.enabled) {
9781      this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, "Font fallback already initialized");
9782      return;
9783    }
9784    this.module = module;
9785    const pdfium = module.pdfium;
9786    if (typeof pdfium.addFunction !== "function") {
9787      this.logger.error(
9788        LOG_SOURCE$2,
9789        LOG_CATEGORY$2,
9790        "addFunction not available. Make sure WASM is compiled with -sALLOW_TABLE_GROWTH"
9791      );
9792      return;
9793    }
9794    try {
9795      this.structPtr = pdfium.wasmExports.malloc(SYSFONTINFO_SIZE);
9796      if (!this.structPtr) {
9797        throw new Error("Failed to allocate FPDF_SYSFONTINFO struct");
9798      }
9799      for (let i = 0; i < SYSFONTINFO_SIZE; i++) {
9800        pdfium.setValue(this.structPtr + i, 0, "i8");
9801      }
9802      this.releaseFnPtr = pdfium.addFunction((_pThis) => {
9803      }, "vi");
9804      this.enumFontsFnPtr = pdfium.addFunction((_pThis, _pMapper) => {
9805      }, "vii");
9806      this.mapFontFnPtr = pdfium.addFunction(
9807        (_pThis, weight, bItalic, charset, pitchFamily, facePtr, bExactPtr) => {
9808          const face = facePtr ? pdfium.UTF8ToString(facePtr) : "";
9809          const handle = this.mapFont(weight, bItalic, charset, pitchFamily, face);
9810          if (bExactPtr) {
9811            pdfium.setValue(bExactPtr, 0, "i32");
9812          }
9813          return handle;
9814        },
9815        "iiiiiiii"
9816      );
9817      this.getFontFnPtr = pdfium.addFunction((_pThis, facePtr) => {
9818        const face = facePtr ? pdfium.UTF8ToString(facePtr) : "";
9819        return this.mapFont(400, 0, 0, 0, face);
9820      }, "iii");
9821      this.getFontDataFnPtr = pdfium.addFunction(
9822        (_pThis, hFont, table, buffer, bufSize) => {
9823          return this.getFontData(hFont, table, buffer, bufSize);
9824        },
9825        "iiiiii"
9826      );
9827      this.getFaceNameFnPtr = pdfium.addFunction(
9828        (_pThis, _hFont, _buffer, _bufSize) => {
9829          return 0;
9830        },
9831        "iiiii"
9832      );
9833      this.getFontCharsetFnPtr = pdfium.addFunction((_pThis, hFont) => {
9834        const handle = this.fontHandles.get(hFont);
9835        return (handle == null ? void 0 : handle.charset) ?? 0;
9836      }, "iii");
9837      this.deleteFontFnPtr = pdfium.addFunction((_pThis, hFont) => {
9838        this.deleteFont(hFont);
9839      }, "vii");
9840      pdfium.setValue(this.structPtr + OFFSET_VERSION, 1, "i32");
9841      pdfium.setValue(this.structPtr + OFFSET_RELEASE, this.releaseFnPtr, "i32");
9842      pdfium.setValue(this.structPtr + OFFSET_ENUMFONTS, this.enumFontsFnPtr, "i32");
9843      pdfium.setValue(this.structPtr + OFFSET_MAPFONT, this.mapFontFnPtr, "i32");
9844      pdfium.setValue(this.structPtr + OFFSET_GETFONT, this.getFontFnPtr, "i32");
9845      pdfium.setValue(this.structPtr + OFFSET_GETFONTDATA, this.getFontDataFnPtr, "i32");
9846      pdfium.setValue(this.structPtr + OFFSET_GETFACENAME, this.getFaceNameFnPtr, "i32");
9847      pdfium.setValue(this.structPtr + OFFSET_GETFONTCHARSET, this.getFontCharsetFnPtr, "i32");
9848      pdfium.setValue(this.structPtr + OFFSET_DELETEFONT, this.deleteFontFnPtr, "i32");
9849      module.FPDF_SetSystemFontInfo(this.structPtr);
9850      this.enabled = true;
9851      this.logger.info(
9852        LOG_SOURCE$2,
9853        LOG_CATEGORY$2,
9854        "Font fallback system initialized (pure TypeScript)",
9855        Object.keys(this.fontConfig.fonts)
9856      );
9857    } catch (error) {
9858      this.logger.error(LOG_SOURCE$2, LOG_CATEGORY$2, "Failed to initialize font fallback", error);
9859      this.cleanup();
9860      throw error;
9861    }
9862  }
9863  /**
9864   * Disable the font fallback system and clean up resources
9865   */
9866  disable() {
9867    if (!this.enabled || !this.module) {
9868      return;
9869    }
9870    this.module.FPDF_SetSystemFontInfo(0);
9871    this.cleanup();
9872    this.enabled = false;
9873    this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, "Font fallback system disabled");
9874  }
9875  /**
9876   * Clean up allocated resources
9877   */
9878  cleanup() {
9879    if (!this.module) return;
9880    const pdfium = this.module.pdfium;
9881    if (this.structPtr) {
9882      pdfium.wasmExports.free(this.structPtr);
9883      this.structPtr = 0;
9884    }
9885    const removeIfExists = (ptr) => {
9886      if (ptr && typeof pdfium.removeFunction === "function") {
9887        try {
9888          pdfium.removeFunction(ptr);
9889        } catch {
9890        }
9891      }
9892    };
9893    removeIfExists(this.releaseFnPtr);
9894    removeIfExists(this.enumFontsFnPtr);
9895    removeIfExists(this.mapFontFnPtr);
9896    removeIfExists(this.getFontFnPtr);
9897    removeIfExists(this.getFontDataFnPtr);
9898    removeIfExists(this.getFaceNameFnPtr);
9899    removeIfExists(this.getFontCharsetFnPtr);
9900    removeIfExists(this.deleteFontFnPtr);
9901    this.releaseFnPtr = 0;
9902    this.enumFontsFnPtr = 0;
9903    this.mapFontFnPtr = 0;
9904    this.getFontFnPtr = 0;
9905    this.getFontDataFnPtr = 0;
9906    this.getFaceNameFnPtr = 0;
9907    this.getFontCharsetFnPtr = 0;
9908    this.deleteFontFnPtr = 0;
9909  }
9910  /**
9911   * Check if font fallback is enabled
9912   */
9913  isEnabled() {
9914    return this.enabled;
9915  }
9916  /**
9917   * Get statistics about font loading
9918   */
9919  getStats() {
9920    return {
9921      handleCount: this.fontHandles.size,
9922      cacheSize: this.fontCache.size,
9923      cachedUrls: Array.from(this.fontCache.keys())
9924    };
9925  }
9926  /**
9927   * Pre-load fonts for specific charsets (optional optimization)
9928   * This can be called to warm the cache before rendering
9929   */
9930  async preloadFonts(charsets) {
9931    const urls = charsets.map((charset) => this.getFontUrlForCharset(charset)).filter((url) => url !== null);
9932    const uniqueUrls = [...new Set(urls)];
9933    await Promise.all(
9934      uniqueUrls.map(async (url) => {
9935        if (!this.fontCache.has(url)) {
9936          try {
9937            const data = await this.fetchFontAsync(url);
9938            if (data) {
9939              this.fontCache.set(url, data);
9940              this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, \`Pre-loaded font: \${url}\`);
9941            }
9942          } catch (error) {
9943            this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, \`Failed to pre-load font: \${url}\`, error);
9944          }
9945        }
9946      })
9947    );
9948  }
9949  // ============================================================================
9950  // PDFium Callback Implementations
9951  // ============================================================================
9952  /**
9953   * MapFont - called by PDFium when it needs a font
9954   */
9955  mapFont(weight, bItalic, charset, pitchFamily, face) {
9956    const italic = bItalic !== 0;
9957    this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, "MapFont called", {
9958      weight,
9959      italic,
9960      charset,
9961      pitchFamily,
9962      face
9963    });
9964    const result = this.findBestFontMatch(charset, weight, italic);
9965    if (!result) {
9966      this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, \`No font configured for charset \${charset}\`);
9967      return 0;
9968    }
9969    const handle = {
9970      id: this.nextHandleId++,
9971      charset,
9972      weight,
9973      italic,
9974      url: result.url,
9975      data: null
9976    };
9977    this.fontHandles.set(handle.id, handle);
9978    this.logger.debug(
9979      LOG_SOURCE$2,
9980      LOG_CATEGORY$2,
9981      \`Created font handle \${handle.id} for \${result.url} (requested: weight=\${weight}, italic=\${italic}, matched: weight=\${result.matchedWeight}, italic=\${result.matchedItalic})\`
9982    );
9983    return handle.id;
9984  }
9985  /**
9986   * GetFontData - called by PDFium to get font bytes
9987   */
9988  getFontData(fontHandle, table, bufferPtr, bufSize) {
9989    const handle = this.fontHandles.get(fontHandle);
9990    if (!handle) {
9991      this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, \`Unknown font handle: \${fontHandle}\`);
9992      return 0;
9993    }
9994    if (!handle.data) {
9995      if (this.fontCache.has(handle.url)) {
9996        handle.data = this.fontCache.get(handle.url);
9997      } else {
9998        handle.data = this.fetchFontSync(handle.url);
9999        if (handle.data) {
10000          this.fontCache.set(handle.url, handle.data);
10001        }
10002      }
10003    }
10004    if (!handle.data) {
10005      this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, \`Failed to load font: \${handle.url}\`);
10006      return 0;
10007    }
10008    const fontData = handle.data;
10009    if (table !== 0) {
10010      this.logger.debug(
10011        LOG_SOURCE$2,
10012        LOG_CATEGORY$2,
10013        \`Table \${table} requested - returning 0 to request whole file\`
10014      );
10015      return 0;
10016    }
10017    if (bufferPtr === 0 || bufSize < fontData.length) {
10018      return fontData.length;
10019    }
10020    if (this.module) {
10021      const heap = this.module.pdfium.HEAPU8;
10022      heap.set(fontData, bufferPtr);
10023      this.logger.debug(
10024        LOG_SOURCE$2,
10025        LOG_CATEGORY$2,
10026        \`Copied \${fontData.length} bytes to buffer for handle \${fontHandle}\`
10027      );
10028    }
10029    return fontData.length;
10030  }
10031  /**
10032   * DeleteFont - called by PDFium when done with a font
10033   */
10034  deleteFont(fontHandle) {
10035    const handle = this.fontHandles.get(fontHandle);
10036    if (handle) {
10037      this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, \`Deleting font handle \${fontHandle}\`);
10038      this.fontHandles.delete(fontHandle);
10039    }
10040  }
10041  // ============================================================================
10042  // Helper Methods
10043  // ============================================================================
10044  /**
10045   * Find the best matching font variant for the given parameters
10046   */
10047  findBestFontMatch(charset, requestedWeight, requestedItalic) {
10048    const { fonts: fonts2, defaultFont, baseUrl } = this.fontConfig;
10049    const entry = fonts2[charset] ?? defaultFont;
10050    if (!entry) {
10051      return null;
10052    }
10053    const variants = this.normalizeToVariants(entry);
10054    if (variants.length === 0) {
10055      return null;
10056    }
10057    const best = this.selectBestVariant(variants, requestedWeight, requestedItalic);
10058    let url = best.url;
10059    if (baseUrl && !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("/")) {
10060      url = \`\${baseUrl}/\${url}\`;
10061    }
10062    return {
10063      url,
10064      matchedWeight: best.weight ?? 400,
10065      matchedItalic: best.italic ?? false
10066    };
10067  }
10068  /**
10069   * Normalize a FontEntry to an array of FontVariants
10070   */
10071  normalizeToVariants(entry) {
10072    if (typeof entry === "string") {
10073      return [{ url: entry, weight: 400, italic: false }];
10074    }
10075    if (Array.isArray(entry)) {
10076      return entry.map((v) => ({
10077        url: v.url,
10078        weight: v.weight ?? 400,
10079        italic: v.italic ?? false
10080      }));
10081    }
10082    return [{ url: entry.url, weight: entry.weight ?? 400, italic: entry.italic ?? false }];
10083  }
10084  /**
10085   * Select the best matching variant based on weight and italic
10086   * Uses CSS font matching algorithm principles:
10087   * 1. Exact italic match preferred
10088   * 2. Closest weight (with bias toward bolder for weights >= 400)
10089   */
10090  selectBestVariant(variants, requestedWeight, requestedItalic) {
10091    if (variants.length === 1) {
10092      return variants[0];
10093    }
10094    const italicMatches = variants.filter((v) => (v.italic ?? false) === requestedItalic);
10095    const candidates = italicMatches.length > 0 ? italicMatches : variants;
10096    let bestMatch = candidates[0];
10097    let bestDistance = Math.abs((bestMatch.weight ?? 400) - requestedWeight);
10098    for (const variant of candidates) {
10099      const variantWeight = variant.weight ?? 400;
10100      const distance = Math.abs(variantWeight - requestedWeight);
10101      if (distance < bestDistance) {
10102        bestMatch = variant;
10103        bestDistance = distance;
10104      } else if (distance === bestDistance) {
10105        const currentWeight = bestMatch.weight ?? 400;
10106        if (requestedWeight >= 500) {
10107          if (variantWeight > currentWeight) {
10108            bestMatch = variant;
10109          }
10110        } else {
10111          if (variantWeight < currentWeight) {
10112            bestMatch = variant;
10113          }
10114        }
10115      }
10116    }
10117    return bestMatch;
10118  }
10119  /**
10120   * Get font URL for a charset (backward compatible helper)
10121   */
10122  getFontUrlForCharset(charset) {
10123    const result = this.findBestFontMatch(charset, 400, false);
10124    return (result == null ? void 0 : result.url) ?? null;
10125  }
10126  /**
10127   * Fetch font data synchronously
10128   * Uses custom fontLoader if provided, otherwise falls back to XMLHttpRequest (browser)
10129   */
10130  fetchFontSync(pathOrUrl) {
10131    this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, \`Fetching font synchronously: \${pathOrUrl}\`);
10132    if (this.fontConfig.fontLoader) {
10133      try {
10134        const data = this.fontConfig.fontLoader(pathOrUrl);
10135        if (data) {
10136          this.logger.info(
10137            LOG_SOURCE$2,
10138            LOG_CATEGORY$2,
10139            \`Loaded font via custom loader: \${pathOrUrl} (\${data.length} bytes)\`
10140          );
10141        } else {
10142          this.logger.warn(
10143            LOG_SOURCE$2,
10144            LOG_CATEGORY$2,
10145            \`Custom font loader returned null for: \${pathOrUrl}\`
10146          );
10147        }
10148        return data;
10149      } catch (error) {
10150        this.logger.error(
10151          LOG_SOURCE$2,
10152          LOG_CATEGORY$2,
10153          \`Error in custom font loader: \${pathOrUrl}\`,
10154          error
10155        );
10156        return null;
10157      }
10158    }
10159    try {
10160      const xhr = new XMLHttpRequest();
10161      xhr.open("GET", pathOrUrl, false);
10162      xhr.responseType = "arraybuffer";
10163      xhr.send();
10164      if (xhr.status === 200) {
10165        const data = new Uint8Array(xhr.response);
10166        this.logger.info(
10167          LOG_SOURCE$2,
10168          LOG_CATEGORY$2,
10169          \`Loaded font: \${pathOrUrl} (\${data.length} bytes)\`
10170        );
10171        return data;
10172      } else {
10173        this.logger.error(
10174          LOG_SOURCE$2,
10175          LOG_CATEGORY$2,
10176          \`Failed to load font: \${pathOrUrl} (HTTP \${xhr.status})\`
10177        );
10178        return null;
10179      }
10180    } catch (error) {
10181      this.logger.error(LOG_SOURCE$2, LOG_CATEGORY$2, \`Error fetching font: \${pathOrUrl}\`, error);
10182      return null;
10183    }
10184  }
10185  /**
10186   * Fetch font data asynchronously (for preloading)
10187   * Uses custom fontLoader if provided, otherwise falls back to fetch API
10188   */
10189  async fetchFontAsync(pathOrUrl) {
10190    if (this.fontConfig.fontLoader) {
10191      try {
10192        return this.fontConfig.fontLoader(pathOrUrl);
10193      } catch {
10194        return null;
10195      }
10196    }
10197    try {
10198      const response = await fetch(pathOrUrl);
10199      if (response.ok) {
10200        const buffer = await response.arrayBuffer();
10201        return new Uint8Array(buffer);
10202      }
10203      return null;
10204    } catch {
10205      return null;
10206    }
10207  }
10208}
10209const LOG_SOURCE$1 = "PDFiumEngine";
10210const LOG_CATEGORY$1 = "Engine";
10211class PdfiumNative {
10212  /**
10213   * Create an instance of PdfiumNative and initialize PDFium
10214   * @param wasmModule - pdfium wasm module
10215   * @param options - configuration options
10216   */
10217  constructor(pdfiumModule, options = {}) {
10218    this.pdfiumModule = pdfiumModule;
10219    this.memoryLeakCheckInterval = null;
10220    this.fontFallbackManager = null;
10221    const { logger = new NoopLogger(), fontFallback } = options;
10222    this.logger = logger;
10223    this.memoryManager = new MemoryManager(this.pdfiumModule, this.logger);
10224    this.cache = new PdfCache(this.pdfiumModule, this.memoryManager);
10225    if (this.logger.isEnabled("debug")) {
10226      this.memoryLeakCheckInterval = setInterval(() => {
10227        this.memoryManager.checkLeaks();
10228      }, 1e4);
10229    }
10230    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "initialize");
10231    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Initialize\`, "Begin", "General");
10232    this.pdfiumModule.PDFiumExt_Init();
10233    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Initialize\`, "End", "General");
10234    if (fontFallback) {
10235      this.fontFallbackManager = new FontFallbackManager(fontFallback, this.logger);
10236      this.fontFallbackManager.initialize(this.pdfiumModule);
10237      this.logger.info(LOG_SOURCE$1, LOG_CATEGORY$1, "Font fallback system enabled");
10238    }
10239  }
10240  /**
10241   * {@inheritDoc @embedpdf/models!PdfEngine.destroy}
10242   *
10243   * @public
10244   */
10245  destroy() {
10246    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "destroy");
10247    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Destroy\`, "Begin", "General");
10248    if (this.fontFallbackManager) {
10249      this.fontFallbackManager.disable();
10250      this.fontFallbackManager = null;
10251    }
10252    this.pdfiumModule.FPDF_DestroyLibrary();
10253    if (this.memoryLeakCheckInterval) {
10254      clearInterval(this.memoryLeakCheckInterval);
10255      this.memoryLeakCheckInterval = null;
10256    }
10257    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Destroy\`, "End", "General");
10258    return PdfTaskHelper.resolve(true);
10259  }
10260  /**
10261   * Get the font fallback manager instance
10262   * Useful for pre-loading fonts or checking stats
10263   */
10264  getFontFallbackManager() {
10265    return this.fontFallbackManager;
10266  }
10267  /** Write a UTF-16LE (WIDESTRING) to wasm, call \`fn(ptr)\`, then free. */
10268  withWString(value, fn) {
10269    const length = (value.length + 1) * 2;
10270    const ptr = this.memoryManager.malloc(length);
10271    try {
10272      this.pdfiumModule.pdfium.stringToUTF16(value, ptr, length);
10273      return fn(ptr);
10274    } finally {
10275      this.memoryManager.free(ptr);
10276    }
10277  }
10278  /** Write a float[] to wasm, call \`fn(ptr, count)\`, then free. */
10279  withFloatArray(values, fn) {
10280    const arr = values ?? [];
10281    const bytes = arr.length * 4;
10282    const ptr = bytes ? this.memoryManager.malloc(bytes) : WasmPointer(0);
10283    try {
10284      if (bytes) {
10285        for (let i = 0; i < arr.length; i++) {
10286          this.pdfiumModule.pdfium.setValue(ptr + i * 4, arr[i], "float");
10287        }
10288      }
10289      return fn(ptr, arr.length);
10290    } finally {
10291      if (bytes) this.memoryManager.free(ptr);
10292    }
10293  }
10294  /**
10295   * {@inheritDoc @embedpdf/models!PdfEngine.openDocument}
10296   *
10297   * @public
10298   */
10299  openDocumentBuffer(file, options) {
10300    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "openDocumentBuffer", file, options);
10301    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`OpenDocumentBuffer\`, "Begin", file.id);
10302    const normalizeRotation = (options == null ? void 0 : options.normalizeRotation) ?? false;
10303    const array = new Uint8Array(file.content);
10304    const length = array.length;
10305    const filePtr = this.memoryManager.malloc(length);
10306    this.pdfiumModule.pdfium.HEAPU8.set(array, filePtr);
10307    const docPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, length, (options == null ? void 0 : options.password) ?? "");
10308    if (!docPtr) {
10309      const lastError = this.pdfiumModule.FPDF_GetLastError();
10310      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, \`FPDF_LoadMemDocument failed with \${lastError}\`);
10311      this.memoryManager.free(filePtr);
10312      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`OpenDocumentBuffer\`, "End", file.id);
10313      return PdfTaskHelper.reject({
10314        code: lastError,
10315        message: \`FPDF_LoadMemDocument failed\`
10316      });
10317    }
10318    const pageCount = this.pdfiumModule.FPDF_GetPageCount(docPtr);
10319    const pages = [];
10320    const sizePtr = this.memoryManager.malloc(8);
10321    for (let index = 0; index < pageCount; index++) {
10322      const result = normalizeRotation ? this.pdfiumModule.EPDF_GetPageSizeByIndexNormalized(docPtr, index, sizePtr) : this.pdfiumModule.FPDF_GetPageSizeByIndexF(docPtr, index, sizePtr);
10323      if (!result) {
10324        const lastError = this.pdfiumModule.FPDF_GetLastError();
10325        this.logger.error(
10326          LOG_SOURCE$1,
10327          LOG_CATEGORY$1,
10328          \`\${normalizeRotation ? "EPDF_GetPageSizeByIndexNormalized" : "FPDF_GetPageSizeByIndexF"} failed with \${lastError}\`
10329        );
10330        this.memoryManager.free(sizePtr);
10331        this.pdfiumModule.FPDF_CloseDocument(docPtr);
10332        this.memoryManager.free(filePtr);
10333        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`OpenDocumentBuffer\`, "End", file.id);
10334        return PdfTaskHelper.reject({
10335          code: lastError,
10336          message: \`\${normalizeRotation ? "EPDF_GetPageSizeByIndexNormalized" : "FPDF_GetPageSizeByIndexF"} failed\`
10337        });
10338      }
10339      const rotation = this.pdfiumModule.EPDF_GetPageRotationByIndex(docPtr, index);
10340      const page = {
10341        index,
10342        size: {
10343          width: this.pdfiumModule.pdfium.getValue(sizePtr, "float"),
10344          height: this.pdfiumModule.pdfium.getValue(sizePtr + 4, "float")
10345        },
10346        rotation
10347      };
10348      pages.push(page);
10349    }
10350    this.memoryManager.free(sizePtr);
10351    const isEncrypted = this.pdfiumModule.EPDF_IsEncrypted(docPtr);
10352    const isOwnerUnlocked = this.pdfiumModule.EPDF_IsOwnerUnlocked(docPtr);
10353    const permissions = this.pdfiumModule.FPDF_GetDocPermissions(docPtr);
10354    const pdfDoc = {
10355      id: file.id,
10356      pageCount,
10357      pages,
10358      isEncrypted,
10359      isOwnerUnlocked,
10360      permissions,
10361      normalizedRotation: normalizeRotation
10362    };
10363    this.cache.setDocument(file.id, filePtr, docPtr, normalizeRotation);
10364    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`OpenDocumentBuffer\`, "End", file.id);
10365    return PdfTaskHelper.resolve(pdfDoc);
10366  }
10367  /**
10368   * Create a new empty PDF document and register it in the cache.
10369   *
10370   * @param id - unique document identifier
10371   * @returns task containing the empty PdfDocumentObject
10372   */
10373  createDocument(id) {
10374    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "createDocument", id);
10375    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "CreateDocument", "Begin", id);
10376    const docPtr = this.pdfiumModule.FPDF_CreateNewDocument();
10377    if (!docPtr) {
10378      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "CreateDocument", "End", id);
10379      return PdfTaskHelper.reject({
10380        code: PdfErrorCode.CantCreateNewDoc,
10381        message: "can not create new document"
10382      });
10383    }
10384    const pdfDoc = {
10385      id,
10386      pageCount: 0,
10387      pages: [],
10388      isEncrypted: false,
10389      isOwnerUnlocked: true,
10390      permissions: 4294967295,
10391      normalizedRotation: false
10392    };
10393    this.cache.setDocument(id, 0, docPtr, false);
10394    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "CreateDocument", "End", id);
10395    return PdfTaskHelper.resolve(pdfDoc);
10396  }
10397  /**
10398   * {@inheritDoc @embedpdf/models!PdfEngine.getMetadata}
10399   *
10400   * @public
10401   */
10402  getMetadata(doc) {
10403    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getMetadata", doc);
10404    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetMetadata\`, "Begin", doc.id);
10405    const ctx = this.cache.getContext(doc.id);
10406    if (!ctx) {
10407      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetMetadata\`, "End", doc.id);
10408      return PdfTaskHelper.reject({
10409        code: PdfErrorCode.DocNotOpen,
10410        message: "document does not open"
10411      });
10412    }
10413    const creationRaw = this.readMetaText(ctx.docPtr, "CreationDate");
10414    const modRaw = this.readMetaText(ctx.docPtr, "ModDate");
10415    const metadata = {
10416      title: this.readMetaText(ctx.docPtr, "Title"),
10417      author: this.readMetaText(ctx.docPtr, "Author"),
10418      subject: this.readMetaText(ctx.docPtr, "Subject"),
10419      keywords: this.readMetaText(ctx.docPtr, "Keywords"),
10420      producer: this.readMetaText(ctx.docPtr, "Producer"),
10421      creator: this.readMetaText(ctx.docPtr, "Creator"),
10422      creationDate: creationRaw ? pdfDateToDate(creationRaw) ?? null : null,
10423      modificationDate: modRaw ? pdfDateToDate(modRaw) ?? null : null,
10424      trapped: this.getMetaTrapped(ctx.docPtr),
10425      custom: this.readAllMeta(ctx.docPtr, true)
10426    };
10427    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetMetadata\`, "End", doc.id);
10428    return PdfTaskHelper.resolve(metadata);
10429  }
10430  /**
10431   * {@inheritDoc @embedpdf/models!PdfEngine.setMetadata}
10432   *
10433   * @public
10434   */
10435  setMetadata(doc, meta) {
10436    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setMetadata", doc, meta);
10437    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "Begin", doc.id);
10438    const ctx = this.cache.getContext(doc.id);
10439    if (!ctx) {
10440      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "End", doc.id);
10441      return PdfTaskHelper.reject({
10442        code: PdfErrorCode.DocNotOpen,
10443        message: "document does not open"
10444      });
10445    }
10446    const strMap = [
10447      ["title", "Title"],
10448      ["author", "Author"],
10449      ["subject", "Subject"],
10450      ["keywords", "Keywords"],
10451      ["producer", "Producer"],
10452      ["creator", "Creator"]
10453    ];
10454    let ok = true;
10455    for (const [field, key] of strMap) {
10456      const v = meta[field];
10457      if (v === void 0) continue;
10458      const s = v === null ? null : v;
10459      if (!this.setMetaText(ctx.docPtr, key, s)) ok = false;
10460    }
10461    const writeDate = (field, key) => {
10462      const v = meta[field];
10463      if (v === void 0) return;
10464      if (v === null) {
10465        if (!this.setMetaText(ctx.docPtr, key, null)) ok = false;
10466        return;
10467      }
10468      const d = v;
10469      const raw = dateToPdfDate(d);
10470      if (!this.setMetaText(ctx.docPtr, key, raw)) ok = false;
10471    };
10472    writeDate("creationDate", "CreationDate");
10473    writeDate("modificationDate", "ModDate");
10474    if (meta.trapped !== void 0) {
10475      if (!this.setMetaTrapped(ctx.docPtr, meta.trapped ?? null)) ok = false;
10476    }
10477    if (meta.custom !== void 0) {
10478      for (const [key, value] of Object.entries(meta.custom)) {
10479        if (!isValidCustomKey(key)) {
10480          this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, "Invalid custom metadata key skipped", key);
10481          continue;
10482        }
10483        if (!this.setMetaText(ctx.docPtr, key, value ?? null)) ok = false;
10484      }
10485    }
10486    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "End", doc.id);
10487    return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({
10488      code: PdfErrorCode.Unknown,
10489      message: "one or more metadata fields could not be written"
10490    });
10491  }
10492  /**
10493   * {@inheritDoc @embedpdf/models!PdfEngine.getDocPermissions}
10494   *
10495   * @public
10496   */
10497  getDocPermissions(doc) {
10498    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocPermissions", doc);
10499    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getDocPermissions\`, "Begin", doc.id);
10500    const ctx = this.cache.getContext(doc.id);
10501    if (!ctx) {
10502      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getDocPermissions\`, "End", doc.id);
10503      return PdfTaskHelper.reject({
10504        code: PdfErrorCode.DocNotOpen,
10505        message: "document does not open"
10506      });
10507    }
10508    const permissions = this.pdfiumModule.FPDF_GetDocPermissions(ctx.docPtr);
10509    return PdfTaskHelper.resolve(permissions);
10510  }
10511  /**
10512   * {@inheritDoc @embedpdf/models!PdfEngine.getDocUserPermissions}
10513   *
10514   * @public
10515   */
10516  getDocUserPermissions(doc) {
10517    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocUserPermissions", doc);
10518    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getDocUserPermissions\`, "Begin", doc.id);
10519    const ctx = this.cache.getContext(doc.id);
10520    if (!ctx) {
10521      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getDocUserPermissions\`, "End", doc.id);
10522      return PdfTaskHelper.reject({
10523        code: PdfErrorCode.DocNotOpen,
10524        message: "document does not open"
10525      });
10526    }
10527    const permissions = this.pdfiumModule.FPDF_GetDocUserPermissions(ctx.docPtr);
10528    return PdfTaskHelper.resolve(permissions);
10529  }
10530  /**
10531   * {@inheritDoc @embedpdf/models!PdfEngine.getSignatures}
10532   *
10533   * @public
10534   */
10535  getSignatures(doc) {
10536    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getSignatures", doc);
10537    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetSignatures\`, "Begin", doc.id);
10538    const ctx = this.cache.getContext(doc.id);
10539    if (!ctx) {
10540      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetSignatures\`, "End", doc.id);
10541      return PdfTaskHelper.reject({
10542        code: PdfErrorCode.DocNotOpen,
10543        message: "document does not open"
10544      });
10545    }
10546    const signatures = [];
10547    const count = this.pdfiumModule.FPDF_GetSignatureCount(ctx.docPtr);
10548    for (let i = 0; i < count; i++) {
10549      const signatureObjPtr = this.pdfiumModule.FPDF_GetSignatureObject(ctx.docPtr, i);
10550      const contents = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {
10551        return this.pdfiumModule.FPDFSignatureObj_GetContents(signatureObjPtr, buffer, bufferSize);
10552      });
10553      const byteRange = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {
10554        return this.pdfiumModule.FPDFSignatureObj_GetByteRange(signatureObjPtr, buffer, bufferSize) * 4;
10555      });
10556      const subFilter = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {
10557        return this.pdfiumModule.FPDFSignatureObj_GetSubFilter(signatureObjPtr, buffer, bufferSize);
10558      });
10559      const reason = readString(
10560        this.pdfiumModule.pdfium,
10561        (buffer, bufferLength) => {
10562          return this.pdfiumModule.FPDFSignatureObj_GetReason(
10563            signatureObjPtr,
10564            buffer,
10565            bufferLength
10566          );
10567        },
10568        this.pdfiumModule.pdfium.UTF16ToString
10569      );
10570      const time = readString(
10571        this.pdfiumModule.pdfium,
10572        (buffer, bufferLength) => {
10573          return this.pdfiumModule.FPDFSignatureObj_GetTime(signatureObjPtr, buffer, bufferLength);
10574        },
10575        this.pdfiumModule.pdfium.UTF8ToString
10576      );
10577      const docMDP = this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(signatureObjPtr);
10578      signatures.push({
10579        contents,
10580        byteRange,
10581        subFilter,
10582        reason,
10583        time,
10584        docMDP
10585      });
10586    }
10587    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetSignatures\`, "End", doc.id);
10588    return PdfTaskHelper.resolve(signatures);
10589  }
10590  /**
10591   * {@inheritDoc @embedpdf/models!PdfEngine.getBookmarks}
10592   *
10593   * @public
10594   */
10595  getBookmarks(doc) {
10596    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getBookmarks", doc);
10597    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetBookmarks\`, "Begin", doc.id);
10598    const ctx = this.cache.getContext(doc.id);
10599    if (!ctx) {
10600      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getBookmarks\`, "End", doc.id);
10601      return PdfTaskHelper.reject({
10602        code: PdfErrorCode.DocNotOpen,
10603        message: "document does not open"
10604      });
10605    }
10606    const bookmarks = this.readPdfBookmarks(ctx.docPtr, 0);
10607    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetBookmarks\`, "End", doc.id);
10608    return PdfTaskHelper.resolve({
10609      bookmarks
10610    });
10611  }
10612  /**
10613   * {@inheritDoc @embedpdf/models!PdfEngine.setBookmarks}
10614   *
10615   * @public
10616   */
10617  setBookmarks(doc, list) {
10618    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setBookmarks", doc, list);
10619    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SetBookmarks\`, "Begin", doc.id);
10620    const ctx = this.cache.getContext(doc.id);
10621    if (!ctx) {
10622      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SetBookmarks\`, "End", doc.id);
10623      return PdfTaskHelper.reject({
10624        code: PdfErrorCode.DocNotOpen,
10625        message: "document does not open"
10626      });
10627    }
10628    if (!this.pdfiumModule.EPDFBookmark_Clear(ctx.docPtr)) {
10629      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SetBookmarks\`, "End", doc.id);
10630      return PdfTaskHelper.reject({
10631        code: PdfErrorCode.Unknown,
10632        message: "failed to clear existing bookmarks"
10633      });
10634    }
10635    const build = (parentPtr, items) => {
10636      var _a;
10637      for (const item of items) {
10638        const bmPtr = this.withWString(
10639          item.title ?? "",
10640          (wptr) => this.pdfiumModule.EPDFBookmark_AppendChild(ctx.docPtr, parentPtr, wptr)
10641        );
10642        if (!bmPtr) return false;
10643        if (item.target) {
10644          const ok2 = this.applyBookmarkTarget(ctx.docPtr, bmPtr, item.target);
10645          if (!ok2) return false;
10646        }
10647        if ((_a = item.children) == null ? void 0 : _a.length) {
10648          const ok2 = build(bmPtr, item.children);
10649          if (!ok2) return false;
10650        }
10651      }
10652      return true;
10653    };
10654    const ok = build(
10655      /*top-level*/
10656      0,
10657      list
10658    );
10659    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SetBookmarks\`, "End", doc.id);
10660    if (!ok) {
10661      return PdfTaskHelper.reject({
10662        code: PdfErrorCode.Unknown,
10663        message: "failed to build bookmark tree"
10664      });
10665    }
10666    return PdfTaskHelper.resolve(true);
10667  }
10668  /**
10669   * {@inheritDoc @embedpdf/models!PdfEngine.deleteBookmarks}
10670   *
10671   * @public
10672   */
10673  deleteBookmarks(doc) {
10674    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deleteBookmarks", doc);
10675    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteBookmarks\`, "Begin", doc.id);
10676    const ctx = this.cache.getContext(doc.id);
10677    if (!ctx) {
10678      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteBookmarks\`, "End", doc.id);
10679      return PdfTaskHelper.reject({
10680        code: PdfErrorCode.DocNotOpen,
10681        message: "document does not open"
10682      });
10683    }
10684    const ok = this.pdfiumModule.EPDFBookmark_Clear(ctx.docPtr);
10685    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteBookmarks\`, "End", doc.id);
10686    return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({
10687      code: PdfErrorCode.Unknown,
10688      message: "failed to clear bookmarks"
10689    });
10690  }
10691  /**
10692   * {@inheritDoc @embedpdf/models!PdfEngine.renderPage}
10693   *
10694   * @public
10695   */
10696  renderPageRaw(doc, page, options) {
10697    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPage", doc, page, options);
10698    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`RenderPage\`, "Begin", \`\${doc.id}-\${page.index}\`);
10699    const rect = { origin: { x: 0, y: 0 }, size: page.size };
10700    const task = this.renderRectEncoded(doc, page, rect, options);
10701    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`RenderPage\`, "End", \`\${doc.id}-\${page.index}\`);
10702    return task;
10703  }
10704  /**
10705   * {@inheritDoc @embedpdf/models!PdfEngine.renderPageRect}
10706   *
10707   * @public
10708   */
10709  renderPageRect(doc, page, rect, options) {
10710    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPageRect", doc, page, rect, options);
10711    this.logger.perf(
10712      LOG_SOURCE$1,
10713      LOG_CATEGORY$1,
10714      \`RenderPageRect\`,
10715      "Begin",
10716      \`\${doc.id}-\${page.index}\`
10717    );
10718    const task = this.renderRectEncoded(doc, page, rect, options);
10719    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`RenderPageRect\`, "End", \`\${doc.id}-\${page.index}\`);
10720    return task;
10721  }
10722  getDocumentJavaScriptActions(doc) {
10723    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocumentJavaScriptActions", doc);
10724    const ctx = this.cache.getContext(doc.id);
10725    if (!ctx) {
10726      return PdfTaskHelper.reject({
10727        code: PdfErrorCode.DocNotOpen,
10728        message: "document does not open"
10729      });
10730    }
10731    const count = this.pdfiumModule.FPDFDoc_GetJavaScriptActionCount(ctx.docPtr);
10732    if (count < 0) {
10733      return PdfTaskHelper.reject({
10734        code: PdfErrorCode.Unknown,
10735        message: "failed to read document javascript actions"
10736      });
10737    }
10738    const actions = [];
10739    for (let index = 0; index < count; index++) {
10740      const actionPtr = this.pdfiumModule.FPDFDoc_GetJavaScriptAction(ctx.docPtr, index);
10741      if (!actionPtr) continue;
10742      try {
10743        const name = readString(
10744          this.pdfiumModule.pdfium,
10745          (buffer, bufferLength) => this.pdfiumModule.FPDFJavaScriptAction_GetName(actionPtr, buffer, bufferLength),
10746          this.pdfiumModule.pdfium.UTF16ToString
10747        ) ?? "";
10748        const script = readString(
10749          this.pdfiumModule.pdfium,
10750          (buffer, bufferLength) => this.pdfiumModule.FPDFJavaScriptAction_GetScript(actionPtr, buffer, bufferLength),
10751          this.pdfiumModule.pdfium.UTF16ToString
10752        ) ?? "";
10753        if (!script) continue;
10754        actions.push({
10755          id: \`document:\${index}:\${name}\`,
10756          trigger: PdfJavaScriptActionTrigger.DocumentNamed,
10757          name,
10758          script
10759        });
10760      } finally {
10761        this.pdfiumModule.FPDFDoc_CloseJavaScriptAction(actionPtr);
10762      }
10763    }
10764    return PdfTaskHelper.resolve(actions);
10765  }
10766  getPageAnnoWidgets(doc, page) {
10767    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnoWidgets", doc, page);
10768    this.logger.perf(
10769      LOG_SOURCE$1,
10770      LOG_CATEGORY$1,
10771      \`GetPageAnnoWidgets\`,
10772      "Begin",
10773      \`\${doc.id}-\${page.index}\`
10774    );
10775    const ctx = this.cache.getContext(doc.id);
10776    if (!ctx) {
10777      this.logger.perf(
10778        LOG_SOURCE$1,
10779        LOG_CATEGORY$1,
10780        \`GetPageAnnoWidgets\`,
10781        "End",
10782        \`\${doc.id}-\${page.index}\`
10783      );
10784      return PdfTaskHelper.reject({
10785        code: PdfErrorCode.DocNotOpen,
10786        message: "document does not open"
10787      });
10788    }
10789    const annotationWidgets = this.readPageAnnoWidgets(doc, ctx, page);
10790    this.logger.perf(
10791      LOG_SOURCE$1,
10792      LOG_CATEGORY$1,
10793      \`GetPageAnnoWidgets\`,
10794      "End",
10795      \`\${doc.id}-\${page.index}\`
10796    );
10797    this.logger.debug(
10798      LOG_SOURCE$1,
10799      LOG_CATEGORY$1,
10800      \`GetPageAnnoWidgets\`,
10801      \`\${doc.id}-\${page.index}\`,
10802      annotationWidgets
10803    );
10804    return PdfTaskHelper.resolve(annotationWidgets);
10805  }
10806  getPageWidgetJavaScriptActions(doc, page) {
10807    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageWidgetJavaScriptActions", doc, page);
10808    const ctx = this.cache.getContext(doc.id);
10809    if (!ctx) {
10810      return PdfTaskHelper.reject({
10811        code: PdfErrorCode.DocNotOpen,
10812        message: "document does not open"
10813      });
10814    }
10815    const actions = [];
10816    ctx.borrowPage(page.index, (pageCtx) => {
10817      pageCtx.withFormHandle((formHandle) => {
10818        const annotCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
10819        for (let i = 0; i < annotCount; i++) {
10820          pageCtx.withAnnotation(i, (annotPtr) => {
10821            const subtype = this.pdfiumModule.FPDFAnnot_GetSubtype(
10822              annotPtr
10823            );
10824            if (subtype !== PdfAnnotationSubtype.WIDGET) return;
10825            let annotationId = this.getAnnotString(annotPtr, "NM");
10826            if (!annotationId || !isUuidV4(annotationId)) {
10827              annotationId = uuidV4();
10828              this.setAnnotString(annotPtr, "NM", annotationId);
10829            }
10830            const fieldName = readString(
10831              this.pdfiumModule.pdfium,
10832              (buffer, bufferLength) => this.pdfiumModule.FPDFAnnot_GetFormFieldName(
10833                formHandle,
10834                annotPtr,
10835                buffer,
10836                bufferLength
10837              ),
10838              this.pdfiumModule.pdfium.UTF16ToString
10839            ) ?? "";
10840            const eventConfigs = [
10841              {
10842                event: PDF_ANNOT_AACTION_EVENT.KEY_STROKE,
10843                eventType: PdfJavaScriptWidgetEventType.Keystroke,
10844                trigger: PdfJavaScriptActionTrigger.WidgetKeystroke
10845              },
10846              {
10847                event: PDF_ANNOT_AACTION_EVENT.FORMAT,
10848                eventType: PdfJavaScriptWidgetEventType.Format,
10849                trigger: PdfJavaScriptActionTrigger.WidgetFormat
10850              },
10851              {
10852                event: PDF_ANNOT_AACTION_EVENT.VALIDATE,
10853                eventType: PdfJavaScriptWidgetEventType.Validate,
10854                trigger: PdfJavaScriptActionTrigger.WidgetValidate
10855              },
10856              {
10857                event: PDF_ANNOT_AACTION_EVENT.CALCULATE,
10858                eventType: PdfJavaScriptWidgetEventType.Calculate,
10859                trigger: PdfJavaScriptActionTrigger.WidgetCalculate
10860              }
10861            ];
10862            for (const config of eventConfigs) {
10863              const script = readString(
10864                this.pdfiumModule.pdfium,
10865                (buffer, bufferLength) => this.pdfiumModule.FPDFAnnot_GetFormAdditionalActionJavaScript(
10866                  formHandle,
10867                  annotPtr,
10868                  config.event,
10869                  buffer,
10870                  bufferLength
10871                ),
10872                this.pdfiumModule.pdfium.UTF16ToString
10873              ) ?? "";
10874              if (!script) continue;
10875              actions.push({
10876                id: \`widget:\${page.index}:\${annotationId}:\${config.eventType}\`,
10877                trigger: config.trigger,
10878                eventType: config.eventType,
10879                pageIndex: page.index,
10880                annotationId,
10881                fieldName,
10882                script
10883              });
10884            }
10885          });
10886        }
10887      });
10888    });
10889    return PdfTaskHelper.resolve(actions);
10890  }
10891  regenerateWidgetAppearances(doc, page, annotationIds) {
10892    const ctx = this.cache.getContext(doc.id);
10893    if (!ctx) {
10894      return PdfTaskHelper.reject({
10895        code: PdfErrorCode.DocNotOpen,
10896        message: "document does not open"
10897      });
10898    }
10899    const idSet = new Set(annotationIds);
10900    let regenerated = 0;
10901    ctx.borrowPage(page.index, (pageCtx) => {
10902      const count = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
10903      for (let i = 0; i < count; i++) {
10904        pageCtx.withAnnotation(i, (annotPtr) => {
10905          const nm = this.getAnnotString(annotPtr, "NM");
10906          if (nm && idSet.has(nm)) {
10907            this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotPtr);
10908            regenerated++;
10909          }
10910        });
10911      }
10912      if (regenerated > 0) {
10913        this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
10914      }
10915    });
10916    return PdfTaskHelper.resolve(regenerated > 0);
10917  }
10918  /**
10919   * {@inheritDoc @embedpdf/models!PdfEngine.getPageAnnotations}
10920   *
10921   * @public
10922   */
10923  getPageAnnotations(doc, page) {
10924    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnotations", doc, page);
10925    this.logger.perf(
10926      LOG_SOURCE$1,
10927      LOG_CATEGORY$1,
10928      \`GetPageAnnotations\`,
10929      "Begin",
10930      \`\${doc.id}-\${page.index}\`
10931    );
10932    const ctx = this.cache.getContext(doc.id);
10933    if (!ctx) {
10934      this.logger.perf(
10935        LOG_SOURCE$1,
10936        LOG_CATEGORY$1,
10937        \`GetPageAnnotations\`,
10938        "End",
10939        \`\${doc.id}-\${page.index}\`
10940      );
10941      return PdfTaskHelper.reject({
10942        code: PdfErrorCode.DocNotOpen,
10943        message: "document does not open"
10944      });
10945    }
10946    const annotations = this.readPageAnnotations(doc, ctx, page);
10947    this.logger.perf(
10948      LOG_SOURCE$1,
10949      LOG_CATEGORY$1,
10950      \`GetPageAnnotations\`,
10951      "End",
10952      \`\${doc.id}-\${page.index}\`
10953    );
10954    this.logger.debug(
10955      LOG_SOURCE$1,
10956      LOG_CATEGORY$1,
10957      \`GetPageAnnotations\`,
10958      \`\${doc.id}-\${page.index}\`,
10959      annotations
10960    );
10961    return PdfTaskHelper.resolve(annotations);
10962  }
10963  /**
10964   * {@inheritDoc @embedpdf/models!PdfEngine.createPageAnnotation}
10965   *
10966   * @public
10967   */
10968  createPageAnnotation(doc, page, annotation, context) {
10969    var _a;
10970    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "createPageAnnotation", doc, page, annotation);
10971    this.logger.perf(
10972      LOG_SOURCE$1,
10973      LOG_CATEGORY$1,
10974      \`CreatePageAnnotation\`,
10975      "Begin",
10976      \`\${doc.id}-\${page.index}\`
10977    );
10978    const ctx = this.cache.getContext(doc.id);
10979    if (!ctx) {
10980      this.logger.perf(
10981        LOG_SOURCE$1,
10982        LOG_CATEGORY$1,
10983        \`CreatePageAnnotation\`,
10984        "End",
10985        \`\${doc.id}-\${page.index}\`
10986      );
10987      return PdfTaskHelper.reject({
10988        code: PdfErrorCode.DocNotOpen,
10989        message: "document does not open"
10990      });
10991    }
10992    const pageCtx = ctx.acquirePage(page.index);
10993    let annotationPtr;
10994    let widgetFormInfoPtr;
10995    let widgetFormHandle;
10996    if (annotation.type === PdfAnnotationSubtype.WIDGET) {
10997      const widget = annotation;
10998      widgetFormInfoPtr = this.pdfiumModule.PDFiumExt_OpenFormFillInfo();
10999      widgetFormHandle = this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(
11000        ctx.docPtr,
11001        widgetFormInfoPtr
11002      );
11003      this.pdfiumModule.FORM_OnAfterLoadPage(pageCtx.pagePtr, widgetFormHandle);
11004      const fieldName = ((_a = widget.field) == null ? void 0 : _a.name) ?? "";
11005      annotationPtr = this.withWString(
11006        fieldName,
11007        (namePtr) => this.pdfiumModule.EPDFPage_CreateFormField(
11008          pageCtx.pagePtr,
11009          widgetFormHandle,
11010          widget.field.type,
11011          namePtr
11012        )
11013      );
11014    } else {
11015      annotationPtr = this.pdfiumModule.EPDFPage_CreateAnnot(pageCtx.pagePtr, annotation.type);
11016    }
11017    if (!annotationPtr) {
11018      this.logger.perf(
11019        LOG_SOURCE$1,
11020        LOG_CATEGORY$1,
11021        \`CreatePageAnnotation\`,
11022        "End",
11023        \`\${doc.id}-\${page.index}\`
11024      );
11025      pageCtx.release();
11026      return PdfTaskHelper.reject({
11027        code: PdfErrorCode.CantCreateAnnot,
11028        message: "can not create annotation with specified type"
11029      });
11030    }
11031    if (!isUuidV4(annotation.id)) {
11032      annotation.id = uuidV4();
11033    }
11034    if (!this.setAnnotString(annotationPtr, "NM", annotation.id)) {
11035      this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
11036      pageCtx.release();
11037      return PdfTaskHelper.reject({
11038        code: PdfErrorCode.CantSetAnnotString,
11039        message: "can not set the name of the annotation"
11040      });
11041    }
11042    if (!this.setPageAnnoRect(doc, page, annotationPtr, annotation.rect)) {
11043      this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
11044      pageCtx.release();
11045      this.logger.perf(
11046        LOG_SOURCE$1,
11047        LOG_CATEGORY$1,
11048        \`CreatePageAnnotation\`,
11049        "End",
11050        \`\${doc.id}-\${page.index}\`
11051      );
11052      return PdfTaskHelper.reject({
11053        code: PdfErrorCode.CantSetAnnotRect,
11054        message: "can not set the rect of the annotation"
11055      });
11056    }
11057    const saveAnnotation = this.prepareAnnotationForSave(annotation);
11058    let isSucceed = false;
11059    switch (saveAnnotation.type) {
11060      case PdfAnnotationSubtype.INK:
11061        isSucceed = this.addInkStroke(
11062          doc,
11063          page,
11064          pageCtx.pagePtr,
11065          annotationPtr,
11066          saveAnnotation
11067        );
11068        break;
11069      case PdfAnnotationSubtype.STAMP:
11070        isSucceed = this.addStampContent(
11071          doc,
11072          ctx.docPtr,
11073          page,
11074          pageCtx.pagePtr,
11075          annotationPtr,
11076          saveAnnotation,
11077          context
11078        );
11079        break;
11080      case PdfAnnotationSubtype.TEXT:
11081        isSucceed = this.addTextContent(
11082          doc,
11083          page,
11084          pageCtx.pagePtr,
11085          annotationPtr,
11086          saveAnnotation
11087        );
11088        break;
11089      case PdfAnnotationSubtype.FREETEXT:
11090        isSucceed = this.addFreeTextContent(
11091          doc,
11092          page,
11093          pageCtx.pagePtr,
11094          annotationPtr,
11095          saveAnnotation
11096        );
11097        break;
11098      case PdfAnnotationSubtype.LINE:
11099        isSucceed = this.addLineContent(
11100          doc,
11101          page,
11102          pageCtx.pagePtr,
11103          annotationPtr,
11104          saveAnnotation
11105        );
11106        break;
11107      case PdfAnnotationSubtype.POLYLINE:
11108      case PdfAnnotationSubtype.POLYGON:
11109        isSucceed = this.addPolyContent(
11110          doc,
11111          page,
11112          pageCtx.pagePtr,
11113          annotationPtr,
11114          saveAnnotation
11115        );
11116        break;
11117      case PdfAnnotationSubtype.CIRCLE:
11118      case PdfAnnotationSubtype.SQUARE:
11119        isSucceed = this.addShapeContent(doc, page, pageCtx.pagePtr, annotationPtr, saveAnnotation);
11120        break;
11121      case PdfAnnotationSubtype.UNDERLINE:
11122      case PdfAnnotationSubtype.STRIKEOUT:
11123      case PdfAnnotationSubtype.SQUIGGLY:
11124      case PdfAnnotationSubtype.HIGHLIGHT:
11125        isSucceed = this.addTextMarkupContent(
11126          doc,
11127          page,
11128          pageCtx.pagePtr,
11129          annotationPtr,
11130          saveAnnotation
11131        );
11132        break;
11133      case PdfAnnotationSubtype.LINK:
11134        isSucceed = this.addLinkContent(
11135          doc,
11136          page,
11137          ctx.docPtr,
11138          pageCtx.pagePtr,
11139          annotationPtr,
11140          saveAnnotation
11141        );
11142        break;
11143      case PdfAnnotationSubtype.CARET:
11144        isSucceed = this.addCaretContent(
11145          doc,
11146          page,
11147          pageCtx.pagePtr,
11148          annotationPtr,
11149          saveAnnotation
11150        );
11151        break;
11152      case PdfAnnotationSubtype.REDACT:
11153        isSucceed = this.addRedactContent(
11154          doc,
11155          page,
11156          pageCtx.pagePtr,
11157          annotationPtr,
11158          saveAnnotation
11159        );
11160        break;
11161      case PdfAnnotationSubtype.WIDGET: {
11162        const widget = saveAnnotation;
11163        if (widgetFormHandle !== void 0) {
11164          switch (widget.field.type) {
11165            case PDF_FORM_FIELD_TYPE.TEXTFIELD:
11166              isSucceed = this.addTextFieldContent(widgetFormHandle, annotationPtr, widget);
11167              break;
11168            case PDF_FORM_FIELD_TYPE.CHECKBOX:
11169            case PDF_FORM_FIELD_TYPE.RADIOBUTTON:
11170              isSucceed = this.addToggleFieldContent(widgetFormHandle, annotationPtr, widget);
11171              break;
11172            case PDF_FORM_FIELD_TYPE.COMBOBOX:
11173            case PDF_FORM_FIELD_TYPE.LISTBOX:
11174              isSucceed = this.addChoiceFieldContent(widgetFormHandle, annotationPtr, widget);
11175              break;
11176          }
11177        }
11178        break;
11179      }
11180    }
11181    if (widgetFormHandle !== void 0) {
11182      this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, widgetFormHandle);
11183      this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(widgetFormHandle);
11184    }
11185    if (widgetFormInfoPtr !== void 0) {
11186      this.pdfiumModule.PDFiumExt_CloseFormFillInfo(widgetFormInfoPtr);
11187    }
11188    if (!isSucceed) {
11189      this.pdfiumModule.FPDFPage_RemoveAnnot(pageCtx.pagePtr, annotationPtr);
11190      pageCtx.release();
11191      this.logger.perf(
11192        LOG_SOURCE$1,
11193        LOG_CATEGORY$1,
11194        \`CreatePageAnnotation\`,
11195        "End",
11196        \`\${doc.id}-\${page.index}\`
11197      );
11198      return PdfTaskHelper.reject({
11199        code: PdfErrorCode.CantSetAnnotContent,
11200        message: "can not add content of the annotation"
11201      });
11202    }
11203    if (annotation.type === PdfAnnotationSubtype.WIDGET) {
11204      this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotationPtr);
11205    } else if (annotation.blendMode !== void 0) {
11206      this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(annotationPtr, annotation.blendMode);
11207    } else {
11208      this.pdfiumModule.EPDFAnnot_GenerateAppearance(annotationPtr);
11209    }
11210    this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
11211    this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
11212    pageCtx.release();
11213    this.logger.perf(
11214      LOG_SOURCE$1,
11215      LOG_CATEGORY$1,
11216      \`CreatePageAnnotation\`,
11217      "End",
11218      \`\${doc.id}-\${page.index}\`
11219    );
11220    return PdfTaskHelper.resolve(annotation.id);
11221  }
11222  /**
11223   * Update an existing page annotation in-place
11224   *
11225   *  • Locates the annot by page-local index (\`annotation.id\`)
11226   *  • Re-writes its /Rect and type-specific payload
11227   *  • Calls FPDFPage_GenerateContent so the new appearance is rendered
11228   *
11229   * @returns PdfTask<boolean>  –  true on success
11230   */
11231  updatePageAnnotation(doc, page, annotation, options) {
11232    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "updatePageAnnotation", doc, page, annotation);
11233    this.logger.perf(
11234      LOG_SOURCE$1,
11235      LOG_CATEGORY$1,
11236      "UpdatePageAnnotation",
11237      "Begin",
11238      \`\${doc.id}-\${page.index}\`
11239    );
11240    const ctx = this.cache.getContext(doc.id);
11241    if (!ctx) {
11242      this.logger.perf(
11243        LOG_SOURCE$1,
11244        LOG_CATEGORY$1,
11245        "UpdatePageAnnotation",
11246        "End",
11247        \`\${doc.id}-\${page.index}\`
11248      );
11249      return PdfTaskHelper.reject({
11250        code: PdfErrorCode.DocNotOpen,
11251        message: "document does not open"
11252      });
11253    }
11254    const pageCtx = ctx.acquirePage(page.index);
11255    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
11256    if (!annotPtr) {
11257      pageCtx.release();
11258      this.logger.perf(
11259        LOG_SOURCE$1,
11260        LOG_CATEGORY$1,
11261        "UpdatePageAnnotation",
11262        "End",
11263        \`\${doc.id}-\${page.index}\`
11264      );
11265      return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });
11266    }
11267    if (!this.setPageAnnoRect(doc, page, annotPtr, annotation.rect)) {
11268      this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
11269      pageCtx.release();
11270      this.logger.perf(
11271        LOG_SOURCE$1,
11272        LOG_CATEGORY$1,
11273        "UpdatePageAnnotation",
11274        "End",
11275        \`\${doc.id}-\${page.index}\`
11276      );
11277      return PdfTaskHelper.reject({
11278        code: PdfErrorCode.CantSetAnnotRect,
11279        message: "failed to move annotation"
11280      });
11281    }
11282    const saveAnnotation = this.prepareAnnotationForSave(annotation);
11283    let ok = false;
11284    switch (saveAnnotation.type) {
11285      /* ── Ink ─────────────────────────────────────────────────────────────── */
11286      case PdfAnnotationSubtype.INK: {
11287        if (!this.pdfiumModule.FPDFAnnot_RemoveInkList(annotPtr)) break;
11288        ok = this.addInkStroke(
11289          doc,
11290          page,
11291          pageCtx.pagePtr,
11292          annotPtr,
11293          saveAnnotation
11294        );
11295        break;
11296      }
11297      /* ── Stamp ───────────────────────────────────────────────────────────── */
11298      case PdfAnnotationSubtype.STAMP: {
11299        ok = this.addStampContent(
11300          doc,
11301          ctx.docPtr,
11302          page,
11303          pageCtx.pagePtr,
11304          annotPtr,
11305          saveAnnotation
11306        );
11307        break;
11308      }
11309      case PdfAnnotationSubtype.TEXT: {
11310        ok = this.addTextContent(
11311          doc,
11312          page,
11313          pageCtx.pagePtr,
11314          annotPtr,
11315          saveAnnotation
11316        );
11317        break;
11318      }
11319      /* ── Free text ────────────────────────────────────────────────────────── */
11320      case PdfAnnotationSubtype.FREETEXT: {
11321        ok = this.addFreeTextContent(
11322          doc,
11323          page,
11324          pageCtx.pagePtr,
11325          annotPtr,
11326          saveAnnotation
11327        );
11328        break;
11329      }
11330      /* ── Shape ───────────────────────────────────────────────────────────── */
11331      case PdfAnnotationSubtype.CIRCLE:
11332      case PdfAnnotationSubtype.SQUARE: {
11333        ok = this.addShapeContent(doc, page, pageCtx.pagePtr, annotPtr, saveAnnotation);
11334        break;
11335      }
11336      /* ── Line ─────────────────────────────────────────────────────────────── */
11337      case PdfAnnotationSubtype.LINE: {
11338        ok = this.addLineContent(
11339          doc,
11340          page,
11341          pageCtx.pagePtr,
11342          annotPtr,
11343          saveAnnotation
11344        );
11345        break;
11346      }
11347      /* ── Polygon / Polyline ───────────────────────────────────────────────── */
11348      case PdfAnnotationSubtype.POLYGON:
11349      case PdfAnnotationSubtype.POLYLINE: {
11350        ok = this.addPolyContent(
11351          doc,
11352          page,
11353          pageCtx.pagePtr,
11354          annotPtr,
11355          saveAnnotation
11356        );
11357        break;
11358      }
11359      /* ── Text-markup family ──────────────────────────────────────────────── */
11360      case PdfAnnotationSubtype.HIGHLIGHT:
11361      case PdfAnnotationSubtype.UNDERLINE:
11362      case PdfAnnotationSubtype.STRIKEOUT:
11363      case PdfAnnotationSubtype.SQUIGGLY: {
11364        ok = this.addTextMarkupContent(
11365          doc,
11366          page,
11367          pageCtx.pagePtr,
11368          annotPtr,
11369          saveAnnotation
11370        );
11371        break;
11372      }
11373      /* ── Link ─────────────────────────────────────────────────────────────── */
11374      case PdfAnnotationSubtype.LINK: {
11375        ok = this.addLinkContent(
11376          doc,
11377          page,
11378          ctx.docPtr,
11379          pageCtx.pagePtr,
11380          annotPtr,
11381          saveAnnotation
11382        );
11383        break;
11384      }
11385      /* ── Caret ────────────────────────────────────────────────────────────── */
11386      case PdfAnnotationSubtype.CARET: {
11387        ok = this.addCaretContent(
11388          doc,
11389          page,
11390          pageCtx.pagePtr,
11391          annotPtr,
11392          saveAnnotation
11393        );
11394        break;
11395      }
11396      /* ── Redact ───────────────────────────────────────────────────────────── */
11397      case PdfAnnotationSubtype.REDACT: {
11398        ok = this.addRedactContent(
11399          doc,
11400          page,
11401          pageCtx.pagePtr,
11402          annotPtr,
11403          saveAnnotation
11404        );
11405        break;
11406      }
11407      /* ── Widget (form field) ─────────────────────────────────────────────── */
11408      case PdfAnnotationSubtype.WIDGET: {
11409        const widget = saveAnnotation;
11410        pageCtx.withFormHandle((formHandle) => {
11411          switch (widget.field.type) {
11412            case PDF_FORM_FIELD_TYPE.TEXTFIELD:
11413              ok = this.addTextFieldContent(formHandle, annotPtr, widget);
11414              break;
11415            case PDF_FORM_FIELD_TYPE.CHECKBOX:
11416            case PDF_FORM_FIELD_TYPE.RADIOBUTTON:
11417              ok = this.addToggleFieldContent(formHandle, annotPtr, widget);
11418              break;
11419            case PDF_FORM_FIELD_TYPE.COMBOBOX:
11420            case PDF_FORM_FIELD_TYPE.LISTBOX:
11421              ok = this.addChoiceFieldContent(formHandle, annotPtr, widget);
11422              break;
11423          }
11424        });
11425        break;
11426      }
11427      /* ── Unsupported edits – fall through to error ───────────────────────── */
11428      default:
11429        ok = false;
11430    }
11431    if (ok && (options == null ? void 0 : options.regenerateAppearance) !== false) {
11432      if (annotation.type === PdfAnnotationSubtype.WIDGET) {
11433        this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotPtr);
11434      } else if (annotation.blendMode !== void 0) {
11435        this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(annotPtr, annotation.blendMode);
11436      } else {
11437        this.pdfiumModule.EPDFAnnot_GenerateAppearance(annotPtr);
11438      }
11439      this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
11440    }
11441    this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
11442    pageCtx.release();
11443    this.logger.perf(
11444      LOG_SOURCE$1,
11445      LOG_CATEGORY$1,
11446      "UpdatePageAnnotation",
11447      "End",
11448      \`\${doc.id}-\${page.index}\`
11449    );
11450    return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({
11451      code: PdfErrorCode.CantSetAnnotContent,
11452      message: "failed to update annotation"
11453    });
11454  }
11455  /**
11456   * {@inheritDoc @embedpdf/models!PdfEngine.removePageAnnotation}
11457   *
11458   * @public
11459   */
11460  removePageAnnotation(doc, page, annotation) {
11461    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "removePageAnnotation", doc, page, annotation);
11462    this.logger.perf(
11463      LOG_SOURCE$1,
11464      LOG_CATEGORY$1,
11465      \`RemovePageAnnotation\`,
11466      "Begin",
11467      \`\${doc.id}-\${page.index}\`
11468    );
11469    const ctx = this.cache.getContext(doc.id);
11470    if (!ctx) {
11471      this.logger.perf(
11472        LOG_SOURCE$1,
11473        LOG_CATEGORY$1,
11474        \`RemovePageAnnotation\`,
11475        "End",
11476        \`\${doc.id}-\${page.index}\`
11477      );
11478      return PdfTaskHelper.reject({
11479        code: PdfErrorCode.DocNotOpen,
11480        message: "document does not open"
11481      });
11482    }
11483    const pageCtx = ctx.acquirePage(page.index);
11484    let result = false;
11485    result = this.removeAnnotationByName(pageCtx.pagePtr, annotation.id);
11486    if (!result) {
11487      this.logger.error(
11488        LOG_SOURCE$1,
11489        LOG_CATEGORY$1,
11490        \`FPDFPage_RemoveAnnot Failed\`,
11491        \`\${doc.id}-\${page.index}\`
11492      );
11493    } else {
11494      result = this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
11495      if (!result) {
11496        this.logger.error(
11497          LOG_SOURCE$1,
11498          LOG_CATEGORY$1,
11499          \`FPDFPage_GenerateContent Failed\`,
11500          \`\${doc.id}-\${page.index}\`
11501        );
11502      }
11503    }
11504    pageCtx.release();
11505    this.logger.perf(
11506      LOG_SOURCE$1,
11507      LOG_CATEGORY$1,
11508      \`RemovePageAnnotation\`,
11509      "End",
11510      \`\${doc.id}-\${page.index}\`
11511    );
11512    return PdfTaskHelper.resolve(result);
11513  }
11514  /**
11515   * {@inheritDoc @embedpdf/models!PdfEngine.getPageTextRects}
11516   *
11517   * @public
11518   */
11519  getPageTextRects(doc, page) {
11520    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageTextRects", doc, page);
11521    this.logger.perf(
11522      LOG_SOURCE$1,
11523      LOG_CATEGORY$1,
11524      \`GetPageTextRects\`,
11525      "Begin",
11526      \`\${doc.id}-\${page.index}\`
11527    );
11528    const ctx = this.cache.getContext(doc.id);
11529    if (!ctx) {
11530      this.logger.perf(
11531        LOG_SOURCE$1,
11532        LOG_CATEGORY$1,
11533        \`GetPageTextRects\`,
11534        "End",
11535        \`\${doc.id}-\${page.index}\`
11536      );
11537      return PdfTaskHelper.reject({
11538        code: PdfErrorCode.DocNotOpen,
11539        message: "document does not open"
11540      });
11541    }
11542    const pageCtx = ctx.acquirePage(page.index);
11543    const textPagePtr = this.pdfiumModule.FPDFText_LoadPage(pageCtx.pagePtr);
11544    const textRects = this.readPageTextRects(page, pageCtx.docPtr, pageCtx.pagePtr, textPagePtr);
11545    this.pdfiumModule.FPDFText_ClosePage(textPagePtr);
11546    pageCtx.release();
11547    this.logger.perf(
11548      LOG_SOURCE$1,
11549      LOG_CATEGORY$1,
11550      \`GetPageTextRects\`,
11551      "End",
11552      \`\${doc.id}-\${page.index}\`
11553    );
11554    return PdfTaskHelper.resolve(textRects);
11555  }
11556  /**
11557   * {@inheritDoc @embedpdf/models!PdfEngine.renderThumbnail}
11558   *
11559   * @public
11560   */
11561  renderThumbnailRaw(doc, page, options) {
11562    const { scaleFactor = 1, ...rest } = options ?? {};
11563    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderThumbnail", doc, page, options);
11564    this.logger.perf(
11565      LOG_SOURCE$1,
11566      LOG_CATEGORY$1,
11567      \`RenderThumbnail\`,
11568      "Begin",
11569      \`\${doc.id}-\${page.index}\`
11570    );
11571    const ctx = this.cache.getContext(doc.id);
11572    if (!ctx) {
11573      this.logger.perf(
11574        LOG_SOURCE$1,
11575        LOG_CATEGORY$1,
11576        \`RenderThumbnail\`,
11577        "End",
11578        \`\${doc.id}-\${page.index}\`
11579      );
11580      return PdfTaskHelper.reject({
11581        code: PdfErrorCode.DocNotOpen,
11582        message: "document does not open"
11583      });
11584    }
11585    const result = this.renderPageRaw(doc, page, {
11586      scaleFactor: Math.max(scaleFactor, 0.5),
11587      ...rest
11588    });
11589    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`RenderThumbnail\`, "End", \`\${doc.id}-\${page.index}\`);
11590    return result;
11591  }
11592  /**
11593   * {@inheritDoc @embedpdf/models!PdfEngine.getAttachments}
11594   *
11595   * @public
11596   */
11597  getAttachments(doc) {
11598    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getAttachments", doc);
11599    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetAttachments\`, "Begin", doc.id);
11600    const ctx = this.cache.getContext(doc.id);
11601    if (!ctx) {
11602      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetAttachments\`, "End", doc.id);
11603      return PdfTaskHelper.reject({
11604        code: PdfErrorCode.DocNotOpen,
11605        message: "document does not open"
11606      });
11607    }
11608    const attachments = [];
11609    const count = this.pdfiumModule.FPDFDoc_GetAttachmentCount(ctx.docPtr);
11610    for (let i = 0; i < count; i++) {
11611      const attachment = this.readPdfAttachment(ctx.docPtr, i);
11612      attachments.push(attachment);
11613    }
11614    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetAttachments\`, "End", doc.id);
11615    return PdfTaskHelper.resolve(attachments);
11616  }
11617  /**
11618   * {@inheritDoc @embedpdf/models!PdfEngine.addAttachment}
11619   *
11620   * @public
11621   */
11622  addAttachment(doc, params) {
11623    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "addAttachment", doc, params == null ? void 0 : params.name);
11624    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "Begin", doc.id);
11625    const ctx = this.cache.getContext(doc.id);
11626    if (!ctx) {
11627      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11628      return PdfTaskHelper.reject({
11629        code: PdfErrorCode.DocNotOpen,
11630        message: "document does not open"
11631      });
11632    }
11633    const { name, description, mimeType, data } = params ?? {};
11634    if (!name) {
11635      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11636      return PdfTaskHelper.reject({
11637        code: PdfErrorCode.NotFound,
11638        message: "attachment name is required"
11639      });
11640    }
11641    if (!data || (data instanceof Uint8Array ? data.byteLength === 0 : data.byteLength === 0)) {
11642      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11643      return PdfTaskHelper.reject({
11644        code: PdfErrorCode.NotFound,
11645        message: "attachment data is empty"
11646      });
11647    }
11648    const attachmentPtr = this.withWString(
11649      name,
11650      (wNamePtr) => this.pdfiumModule.FPDFDoc_AddAttachment(ctx.docPtr, wNamePtr)
11651    );
11652    if (!attachmentPtr) {
11653      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11654      return PdfTaskHelper.reject({
11655        code: PdfErrorCode.Unknown,
11656        message: \`An attachment named "\${name}" already exists\`
11657      });
11658    }
11659    this.withWString(
11660      description,
11661      (wDescriptionPtr) => this.pdfiumModule.EPDFAttachment_SetDescription(attachmentPtr, wDescriptionPtr)
11662    );
11663    this.pdfiumModule.EPDFAttachment_SetSubtype(attachmentPtr, mimeType);
11664    const u8 = data instanceof Uint8Array ? data : new Uint8Array(data);
11665    const len = u8.byteLength;
11666    const contentPtr = this.memoryManager.malloc(len);
11667    try {
11668      this.pdfiumModule.pdfium.HEAPU8.set(u8, contentPtr);
11669      const ok = this.pdfiumModule.FPDFAttachment_SetFile(
11670        attachmentPtr,
11671        ctx.docPtr,
11672        contentPtr,
11673        len
11674      );
11675      if (!ok) {
11676        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11677        return PdfTaskHelper.reject({
11678          code: PdfErrorCode.Unknown,
11679          message: "failed to write attachment bytes"
11680        });
11681      }
11682    } finally {
11683      this.memoryManager.free(contentPtr);
11684    }
11685    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11686    return PdfTaskHelper.resolve(true);
11687  }
11688  /**
11689   * {@inheritDoc @embedpdf/models!PdfEngine.removeAttachment}
11690   *
11691   * @public
11692   */
11693  removeAttachment(doc, attachment) {
11694    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deleteAttachment", doc, attachment);
11695    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteAttachment\`, "Begin", doc.id);
11696    const ctx = this.cache.getContext(doc.id);
11697    if (!ctx) {
11698      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteAttachment\`, "End", doc.id);
11699      return PdfTaskHelper.reject({
11700        code: PdfErrorCode.DocNotOpen,
11701        message: "document does not open"
11702      });
11703    }
11704    const count = this.pdfiumModule.FPDFDoc_GetAttachmentCount(ctx.docPtr);
11705    if (attachment.index < 0 || attachment.index >= count) {
11706      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteAttachment\`, "End", doc.id);
11707      return PdfTaskHelper.reject({
11708        code: PdfErrorCode.Unknown,
11709        message: \`attachment index \${attachment.index} out of range\`
11710      });
11711    }
11712    const ok = this.pdfiumModule.FPDFDoc_DeleteAttachment(ctx.docPtr, attachment.index);
11713    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteAttachment\`, "End", doc.id);
11714    if (!ok) {
11715      return PdfTaskHelper.reject({
11716        code: PdfErrorCode.Unknown,
11717        message: "failed to delete attachment"
11718      });
11719    }
11720    return PdfTaskHelper.resolve(true);
11721  }
11722  /**
11723   * {@inheritDoc @embedpdf/models!PdfEngine.readAttachmentContent}
11724   *
11725   * @public
11726   */
11727  readAttachmentContent(doc, attachment) {
11728    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "readAttachmentContent", doc, attachment);
11729    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "Begin", doc.id);
11730    const ctx = this.cache.getContext(doc.id);
11731    if (!ctx) {
11732      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "End", doc.id);
11733      return PdfTaskHelper.reject({
11734        code: PdfErrorCode.DocNotOpen,
11735        message: "document does not open"
11736      });
11737    }
11738    const attachmentPtr = this.pdfiumModule.FPDFDoc_GetAttachment(ctx.docPtr, attachment.index);
11739    const sizePtr = this.memoryManager.malloc(4);
11740    if (!this.pdfiumModule.FPDFAttachment_GetFile(attachmentPtr, 0, 0, sizePtr)) {
11741      this.memoryManager.free(sizePtr);
11742      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "End", doc.id);
11743      return PdfTaskHelper.reject({
11744        code: PdfErrorCode.CantReadAttachmentSize,
11745        message: "can not read attachment size"
11746      });
11747    }
11748    const size = this.pdfiumModule.pdfium.getValue(sizePtr, "i32") >>> 0;
11749    const contentPtr = this.memoryManager.malloc(size);
11750    if (!this.pdfiumModule.FPDFAttachment_GetFile(attachmentPtr, contentPtr, size, sizePtr)) {
11751      this.memoryManager.free(sizePtr);
11752      this.memoryManager.free(contentPtr);
11753      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "End", doc.id);
11754      return PdfTaskHelper.reject({
11755        code: PdfErrorCode.CantReadAttachmentContent,
11756        message: "can not read attachment content"
11757      });
11758    }
11759    const buffer = new ArrayBuffer(size);
11760    const view = new DataView(buffer);
11761    for (let i = 0; i < size; i++) {
11762      view.setInt8(i, this.pdfiumModule.pdfium.getValue(contentPtr + i, "i8"));
11763    }
11764    this.memoryManager.free(sizePtr);
11765    this.memoryManager.free(contentPtr);
11766    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "End", doc.id);
11767    return PdfTaskHelper.resolve(buffer);
11768  }
11769  /**
11770   * {@inheritDoc @embedpdf/models!PdfEngine.setFormFieldValue}
11771   *
11772   * @public
11773   */
11774  setFormFieldValue(doc, page, annotation, value) {
11775    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldValue", doc, annotation, value);
11776    this.logger.perf(
11777      LOG_SOURCE$1,
11778      LOG_CATEGORY$1,
11779      \`SetFormFieldValue\`,
11780      "Begin",
11781      \`\${doc.id}-\${annotation.id}\`
11782    );
11783    const ctx = this.cache.getContext(doc.id);
11784    if (!ctx) {
11785      this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldValue", "document is not opened");
11786      this.logger.perf(
11787        LOG_SOURCE$1,
11788        LOG_CATEGORY$1,
11789        \`SetFormFieldValue\`,
11790        "End",
11791        \`\${doc.id}-\${annotation.id}\`
11792      );
11793      return PdfTaskHelper.reject({
11794        code: PdfErrorCode.DocNotOpen,
11795        message: "document does not open"
11796      });
11797    }
11798    const pageCtx = ctx.acquirePage(page.index);
11799    try {
11800      return pageCtx.withFormHandle((formHandle) => {
11801        const annotationPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
11802        if (!annotationPtr) {
11803          return PdfTaskHelper.reject({
11804            code: PdfErrorCode.NotFound,
11805            message: "annotation not found"
11806          });
11807        }
11808        try {
11809          if (!this.pdfiumModule.FORM_SetFocusedAnnot(formHandle, annotationPtr)) {
11810            return PdfTaskHelper.reject({
11811              code: PdfErrorCode.CantFocusAnnot,
11812              message: "failed to set focused annotation"
11813            });
11814          }
11815          switch (value.kind) {
11816            case "text": {
11817              if (!this.pdfiumModule.FORM_SelectAllText(formHandle, pageCtx.pagePtr)) {
11818                this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11819                return PdfTaskHelper.reject({
11820                  code: PdfErrorCode.CantSelectText,
11821                  message: "failed to select all text"
11822                });
11823              }
11824              const length = 2 * (value.text.length + 1);
11825              const textPtr = this.memoryManager.malloc(length);
11826              this.pdfiumModule.pdfium.stringToUTF16(value.text, textPtr, length);
11827              this.pdfiumModule.FORM_ReplaceSelection(formHandle, pageCtx.pagePtr, textPtr);
11828              this.memoryManager.free(textPtr);
11829              break;
11830            }
11831            case "selection": {
11832              if (!this.pdfiumModule.FORM_SetIndexSelected(
11833                formHandle,
11834                pageCtx.pagePtr,
11835                value.index,
11836                value.isSelected
11837              )) {
11838                this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11839                return PdfTaskHelper.reject({
11840                  code: PdfErrorCode.CantSelectOption,
11841                  message: "failed to set index selected"
11842                });
11843              }
11844              break;
11845            }
11846            case "checked": {
11847              const rawChecked = this.pdfiumModule.FPDFAnnot_IsChecked(formHandle, annotationPtr);
11848              const currentlyChecked = !!rawChecked;
11849              if (currentlyChecked !== value.checked) {
11850                const kReturn = 13;
11851                if (!this.pdfiumModule.FORM_OnChar(formHandle, pageCtx.pagePtr, kReturn, 0)) {
11852                  this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11853                  return PdfTaskHelper.reject({
11854                    code: PdfErrorCode.CantCheckField,
11855                    message: "failed to set field checked"
11856                  });
11857                }
11858              }
11859              break;
11860            }
11861          }
11862          this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11863          this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotationPtr);
11864          return PdfTaskHelper.resolve(true);
11865        } finally {
11866          this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
11867        }
11868      });
11869    } finally {
11870      pageCtx.release();
11871    }
11872  }
11873  /**
11874   * {@inheritDoc @embedpdf/models!PdfEngine.setFormFieldState}
11875   *
11876   * @public
11877   */
11878  setFormFieldState(doc, page, annotation, field) {
11879    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldState", doc, annotation, field);
11880    this.logger.perf(
11881      LOG_SOURCE$1,
11882      LOG_CATEGORY$1,
11883      \`SetFormFieldState\`,
11884      "Begin",
11885      \`\${doc.id}-\${annotation.id}\`
11886    );
11887    const ctx = this.cache.getContext(doc.id);
11888    if (!ctx) {
11889      this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldState", "document is not opened");
11890      this.logger.perf(
11891        LOG_SOURCE$1,
11892        LOG_CATEGORY$1,
11893        \`SetFormFieldState\`,
11894        "End",
11895        \`\${doc.id}-\${annotation.id}\`
11896      );
11897      return PdfTaskHelper.reject({
11898        code: PdfErrorCode.DocNotOpen,
11899        message: "document does not open"
11900      });
11901    }
11902    const pageCtx = ctx.acquirePage(page.index);
11903    try {
11904      return pageCtx.withFormHandle((formHandle) => {
11905        const annotationPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
11906        if (!annotationPtr) {
11907          return PdfTaskHelper.reject({
11908            code: PdfErrorCode.NotFound,
11909            message: "annotation not found"
11910          });
11911        }
11912        try {
11913          if (!this.pdfiumModule.FORM_SetFocusedAnnot(formHandle, annotationPtr)) {
11914            return PdfTaskHelper.reject({
11915              code: PdfErrorCode.CantFocusAnnot,
11916              message: "failed to set focused annotation"
11917            });
11918          }
11919          switch (field.type) {
11920            case PDF_FORM_FIELD_TYPE.TEXTFIELD: {
11921              if (!this.pdfiumModule.FORM_SelectAllText(formHandle, pageCtx.pagePtr)) {
11922                this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11923                return PdfTaskHelper.reject({
11924                  code: PdfErrorCode.CantSelectText,
11925                  message: "failed to select all text"
11926                });
11927              }
11928              const length = 2 * (field.value.length + 1);
11929              const textPtr = this.memoryManager.malloc(length);
11930              this.pdfiumModule.pdfium.stringToUTF16(field.value, textPtr, length);
11931              this.pdfiumModule.FORM_ReplaceSelection(formHandle, pageCtx.pagePtr, textPtr);
11932              this.memoryManager.free(textPtr);
11933              break;
11934            }
11935            case PDF_FORM_FIELD_TYPE.CHECKBOX:
11936            case PDF_FORM_FIELD_TYPE.RADIOBUTTON: {
11937              const currentlyChecked = !!this.pdfiumModule.FPDFAnnot_IsChecked(
11938                formHandle,
11939                annotationPtr
11940              );
11941              const desiredChecked = annotation.exportValue != null && field.value === annotation.exportValue;
11942              if (currentlyChecked !== desiredChecked) {
11943                const kReturn = 13;
11944                if (!this.pdfiumModule.FORM_OnChar(formHandle, pageCtx.pagePtr, kReturn, 0)) {
11945                  this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11946                  return PdfTaskHelper.reject({
11947                    code: PdfErrorCode.CantCheckField,
11948                    message: "failed to set field checked"
11949                  });
11950                }
11951              }
11952              break;
11953            }
11954            case PDF_FORM_FIELD_TYPE.COMBOBOX: {
11955              const selectedIndex = field.options.findIndex((opt) => opt.isSelected);
11956              if (selectedIndex >= 0) {
11957                if (!this.pdfiumModule.FORM_SetIndexSelected(
11958                  formHandle,
11959                  pageCtx.pagePtr,
11960                  selectedIndex,
11961                  true
11962                )) {
11963                  this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11964                  return PdfTaskHelper.reject({
11965                    code: PdfErrorCode.CantSelectOption,
11966                    message: "failed to set index selected"
11967                  });
11968                }
11969              }
11970              break;
11971            }
11972            case PDF_FORM_FIELD_TYPE.LISTBOX: {
11973              for (let i = 0; i < field.options.length; i++) {
11974                if (!this.pdfiumModule.FORM_SetIndexSelected(
11975                  formHandle,
11976                  pageCtx.pagePtr,
11977                  i,
11978                  field.options[i].isSelected
11979                )) {
11980                  this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11981                  return PdfTaskHelper.reject({
11982                    code: PdfErrorCode.CantSelectOption,
11983                    message: "failed to set index selected"
11984                  });
11985                }
11986              }
11987              break;
11988            }
11989            default:
11990              break;
11991          }
11992          this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11993          if (field.type !== PDF_FORM_FIELD_TYPE.CHECKBOX && field.type !== PDF_FORM_FIELD_TYPE.RADIOBUTTON) {
11994            this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotationPtr);
11995          }
11996          this.logger.perf(
11997            LOG_SOURCE$1,
11998            LOG_CATEGORY$1,
11999            \`SetFormFieldState\`,
12000            "End",
12001            \`\${doc.id}-\${annotation.id}\`
12002          );
12003          return PdfTaskHelper.resolve(true);
12004        } finally {
12005          this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
12006        }
12007      });
12008    } finally {
12009      pageCtx.release();
12010    }
12011  }
12012  renameWidgetField(doc, page, annotation, name) {
12013    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "RenameWidgetField", doc, annotation, name);
12014    this.logger.perf(
12015      LOG_SOURCE$1,
12016      LOG_CATEGORY$1,
12017      \`RenameWidgetField\`,
12018      "Begin",
12019      \`\${doc.id}-\${annotation.id}\`
12020    );
12021    const ctx = this.cache.getContext(doc.id);
12022    if (!ctx) {
12023      this.logger.perf(
12024        LOG_SOURCE$1,
12025        LOG_CATEGORY$1,
12026        \`RenameWidgetField\`,
12027        "End",
12028        \`\${doc.id}-\${annotation.id}\`
12029      );
12030      return PdfTaskHelper.reject({
12031        code: PdfErrorCode.DocNotOpen,
12032        message: "document does not open"
12033      });
12034    }
12035    const pageCtx = ctx.acquirePage(page.index);
12036    try {
12037      return pageCtx.withFormHandle((formHandle) => {
12038        const annotationPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
12039        if (!annotationPtr) {
12040          return PdfTaskHelper.reject({
12041            code: PdfErrorCode.NotFound,
12042            message: "annotation not found"
12043          });
12044        }
12045        try {
12046          const ok = this.withWString(
12047            name,
12048            (namePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldName(formHandle, annotationPtr, namePtr)
12049          );
12050          if (!ok) {
12051            return PdfTaskHelper.reject({
12052              code: PdfErrorCode.CantSetAnnotString,
12053              message: "failed to rename widget field"
12054            });
12055          }
12056          this.logger.perf(
12057            LOG_SOURCE$1,
12058            LOG_CATEGORY$1,
12059            \`RenameWidgetField\`,
12060            "End",
12061            \`\${doc.id}-\${annotation.id}\`
12062          );
12063          return PdfTaskHelper.resolve(true);
12064        } finally {
12065          this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
12066        }
12067      });
12068    } finally {
12069      pageCtx.release();
12070    }
12071  }
12072  shareWidgetField(doc, sourcePage, sourceAnnotation, targetPage, targetAnnotation) {
12073    this.logger.debug(
12074      LOG_SOURCE$1,
12075      LOG_CATEGORY$1,
12076      "ShareWidgetField",
12077      doc,
12078      sourceAnnotation,
12079      targetAnnotation
12080    );
12081    this.logger.perf(
12082      LOG_SOURCE$1,
12083      LOG_CATEGORY$1,
12084      \`ShareWidgetField\`,
12085      "Begin",
12086      \`\${doc.id}-\${sourceAnnotation.id}-\${targetAnnotation.id}\`
12087    );
12088    const ctx = this.cache.getContext(doc.id);
12089    if (!ctx) {
12090      this.logger.perf(
12091        LOG_SOURCE$1,
12092        LOG_CATEGORY$1,
12093        \`ShareWidgetField\`,
12094        "End",
12095        \`\${doc.id}-\${sourceAnnotation.id}-\${targetAnnotation.id}\`
12096      );
12097      return PdfTaskHelper.reject({
12098        code: PdfErrorCode.DocNotOpen,
12099        message: "document does not open"
12100      });
12101    }
12102    const sourcePageCtx = ctx.acquirePage(sourcePage.index);
12103    const targetPageCtx = targetPage.index === sourcePage.index ? sourcePageCtx : ctx.acquirePage(targetPage.index);
12104    try {
12105      return sourcePageCtx.withFormHandle((formHandle) => {
12106        let targetPageLoaded = false;
12107        if (targetPageCtx !== sourcePageCtx) {
12108          this.pdfiumModule.FORM_OnAfterLoadPage(targetPageCtx.pagePtr, formHandle);
12109          targetPageLoaded = true;
12110        }
12111        const sourceAnnotationPtr = this.getAnnotationByName(
12112          sourcePageCtx.pagePtr,
12113          sourceAnnotation.id
12114        );
12115        const targetAnnotationPtr = this.getAnnotationByName(
12116          targetPageCtx.pagePtr,
12117          targetAnnotation.id
12118        );
12119        if (!sourceAnnotationPtr || !targetAnnotationPtr) {
12120          if (sourceAnnotationPtr) {
12121            this.pdfiumModule.FPDFPage_CloseAnnot(sourceAnnotationPtr);
12122          }
12123          if (targetAnnotationPtr) {
12124            this.pdfiumModule.FPDFPage_CloseAnnot(targetAnnotationPtr);
12125          }
12126          if (targetPageLoaded) {
12127            this.pdfiumModule.FORM_OnBeforeClosePage(targetPageCtx.pagePtr, formHandle);
12128          }
12129          return PdfTaskHelper.reject({
12130            code: PdfErrorCode.NotFound,
12131            message: "annotation not found"
12132          });
12133        }
12134        try {
12135          const ok = this.pdfiumModule.EPDFAnnot_ShareFormField(
12136            formHandle,
12137            sourceAnnotationPtr,
12138            targetAnnotationPtr
12139          );
12140          if (!ok) {
12141            return PdfTaskHelper.reject({
12142              code: PdfErrorCode.Unknown,
12143              message: "failed to share widget field"
12144            });
12145          }
12146          this.logger.perf(
12147            LOG_SOURCE$1,
12148            LOG_CATEGORY$1,
12149            \`ShareWidgetField\`,
12150            "End",
12151            \`\${doc.id}-\${sourceAnnotation.id}-\${targetAnnotation.id}\`
12152          );
12153          return PdfTaskHelper.resolve(true);
12154        } finally {
12155          this.pdfiumModule.FPDFPage_CloseAnnot(sourceAnnotationPtr);
12156          this.pdfiumModule.FPDFPage_CloseAnnot(targetAnnotationPtr);
12157          if (targetPageLoaded) {
12158            this.pdfiumModule.FORM_OnBeforeClosePage(targetPageCtx.pagePtr, formHandle);
12159          }
12160        }
12161      });
12162    } finally {
12163      sourcePageCtx.release();
12164      if (targetPageCtx !== sourcePageCtx) {
12165        targetPageCtx.release();
12166      }
12167    }
12168  }
12169  /**
12170   * {@inheritDoc @embedpdf/models!PdfEngine.flattenPage}
12171   *
12172   * @public
12173   */
12174  flattenPage(doc, page, options) {
12175    const { flag = PdfPageFlattenFlag.Display } = options ?? {};
12176    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "flattenPage", doc, page, flag);
12177    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`flattenPage\`, "Begin", doc.id);
12178    const ctx = this.cache.getContext(doc.id);
12179    if (!ctx) {
12180      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`flattenPage\`, "End", doc.id);
12181      return PdfTaskHelper.reject({
12182        code: PdfErrorCode.DocNotOpen,
12183        message: "document does not open"
12184      });
12185    }
12186    const pageCtx = ctx.acquirePage(page.index);
12187    const result = this.pdfiumModule.FPDFPage_Flatten(pageCtx.pagePtr, flag);
12188    pageCtx.release();
12189    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`flattenPage\`, "End", doc.id);
12190    return PdfTaskHelper.resolve(result);
12191  }
12192  /**
12193   * {@inheritDoc @embedpdf/models!PdfEngine.extractPages}
12194   *
12195   * @public
12196   */
12197  extractPages(doc, pageIndexes) {
12198    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "extractPages", doc, pageIndexes);
12199    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "Begin", doc.id);
12200    const ctx = this.cache.getContext(doc.id);
12201    if (!ctx) {
12202      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "End", doc.id);
12203      return PdfTaskHelper.reject({
12204        code: PdfErrorCode.DocNotOpen,
12205        message: "document does not open"
12206      });
12207    }
12208    const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();
12209    if (!newDocPtr) {
12210      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "End", doc.id);
12211      return PdfTaskHelper.reject({
12212        code: PdfErrorCode.CantCreateNewDoc,
12213        message: "can not create new document"
12214      });
12215    }
12216    const pageIndexesPtr = this.memoryManager.malloc(pageIndexes.length * 4);
12217    for (let i = 0; i < pageIndexes.length; i++) {
12218      this.pdfiumModule.pdfium.setValue(pageIndexesPtr + i * 4, pageIndexes[i], "i32");
12219    }
12220    if (!this.pdfiumModule.FPDF_ImportPagesByIndex(
12221      newDocPtr,
12222      ctx.docPtr,
12223      pageIndexesPtr,
12224      pageIndexes.length,
12225      0
12226    )) {
12227      this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12228      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "End", doc.id);
12229      return PdfTaskHelper.reject({
12230        code: PdfErrorCode.CantImportPages,
12231        message: "can not import pages to new document"
12232      });
12233    }
12234    const buffer = this.saveDocument(newDocPtr);
12235    this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12236    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "End", doc.id);
12237    return PdfTaskHelper.resolve(buffer);
12238  }
12239  /**
12240   * Import pages from a source document into a destination document.
12241   *
12242   * @param destDoc - destination document (must be open in cache)
12243   * @param srcDoc - source document (must be open in cache)
12244   * @param srcPageIndices - zero-based page indices in the source document
12245   * @param insertIndex - position to insert at in destination (defaults to end)
12246   * @returns task containing the newly added PdfPageObjects
12247   */
12248  importPages(destDoc, srcDoc, srcPageIndices, insertIndex) {
12249    this.logger.debug(
12250      LOG_SOURCE$1,
12251      LOG_CATEGORY$1,
12252      "importPages",
12253      destDoc.id,
12254      srcDoc.id,
12255      srcPageIndices
12256    );
12257    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "Begin", destDoc.id);
12258    const destCtx = this.cache.getContext(destDoc.id);
12259    if (!destCtx) {
12260      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12261      return PdfTaskHelper.reject({
12262        code: PdfErrorCode.DocNotOpen,
12263        message: "destination document is not open"
12264      });
12265    }
12266    const srcCtx = this.cache.getContext(srcDoc.id);
12267    if (!srcCtx) {
12268      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12269      return PdfTaskHelper.reject({
12270        code: PdfErrorCode.DocNotOpen,
12271        message: "source document is not open"
12272      });
12273    }
12274    const destInsertIndex = insertIndex ?? this.pdfiumModule.FPDF_GetPageCount(destCtx.docPtr);
12275    const indicesPtr = this.memoryManager.malloc(srcPageIndices.length * 4);
12276    for (let i = 0; i < srcPageIndices.length; i++) {
12277      this.pdfiumModule.pdfium.setValue(indicesPtr + i * 4, srcPageIndices[i], "i32");
12278    }
12279    if (!this.pdfiumModule.FPDF_ImportPagesByIndex(
12280      destCtx.docPtr,
12281      srcCtx.docPtr,
12282      indicesPtr,
12283      srcPageIndices.length,
12284      destInsertIndex
12285    )) {
12286      this.memoryManager.free(indicesPtr);
12287      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12288      return PdfTaskHelper.reject({
12289        code: PdfErrorCode.CantImportPages,
12290        message: "can not import pages into destination document"
12291      });
12292    }
12293    this.memoryManager.free(indicesPtr);
12294    const newPages = [];
12295    const sizePtr = this.memoryManager.malloc(8);
12296    const normalizeRotation = destCtx.normalizeRotation;
12297    for (let i = 0; i < srcPageIndices.length; i++) {
12298      const newPageIndex = destInsertIndex + i;
12299      const result = normalizeRotation ? this.pdfiumModule.EPDF_GetPageSizeByIndexNormalized(destCtx.docPtr, newPageIndex, sizePtr) : this.pdfiumModule.FPDF_GetPageSizeByIndexF(destCtx.docPtr, newPageIndex, sizePtr);
12300      if (!result) {
12301        this.memoryManager.free(sizePtr);
12302        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12303        return PdfTaskHelper.reject({
12304          code: PdfErrorCode.Unknown,
12305          message: \`failed to read metadata for imported page \${newPageIndex}\`
12306        });
12307      }
12308      const rotation = this.pdfiumModule.EPDF_GetPageRotationByIndex(
12309        destCtx.docPtr,
12310        newPageIndex
12311      );
12312      newPages.push({
12313        index: newPageIndex,
12314        size: {
12315          width: this.pdfiumModule.pdfium.getValue(sizePtr, "float"),
12316          height: this.pdfiumModule.pdfium.getValue(sizePtr + 4, "float")
12317        },
12318        rotation
12319      });
12320    }
12321    this.memoryManager.free(sizePtr);
12322    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12323    return PdfTaskHelper.resolve(newPages);
12324  }
12325  deletePage(doc, pageIndex) {
12326    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deletePage", doc.id, pageIndex);
12327    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "DeletePage", "Begin", doc.id);
12328    const ctx = this.cache.getContext(doc.id);
12329    if (!ctx) {
12330      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "DeletePage", "End", doc.id);
12331      return PdfTaskHelper.reject({
12332        code: PdfErrorCode.DocNotOpen,
12333        message: "document is not open"
12334      });
12335    }
12336    const pageCount = this.pdfiumModule.FPDF_GetPageCount(ctx.docPtr);
12337    if (pageIndex < 0 || pageIndex >= pageCount) {
12338      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "DeletePage", "End", doc.id);
12339      return PdfTaskHelper.reject({
12340        code: PdfErrorCode.CantDeletePage,
12341        message: \`page index \${pageIndex} out of range (0..\${pageCount - 1})\`
12342      });
12343    }
12344    this.pdfiumModule.FPDFPage_Delete(ctx.docPtr, pageIndex);
12345    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "DeletePage", "End", doc.id);
12346    return PdfTaskHelper.resolve(true);
12347  }
12348  /**
12349   * {@inheritDoc @embedpdf/models!PdfEngine.extractText}
12350   *
12351   * @public
12352   */
12353  extractText(doc, pageIndexes) {
12354    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "extractText", doc, pageIndexes);
12355    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractText\`, "Begin", doc.id);
12356    const ctx = this.cache.getContext(doc.id);
12357    if (!ctx) {
12358      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractText\`, "End", doc.id);
12359      return PdfTaskHelper.reject({
12360        code: PdfErrorCode.DocNotOpen,
12361        message: "document does not open"
12362      });
12363    }
12364    const strings = [];
12365    for (let i = 0; i < pageIndexes.length; i++) {
12366      const pageCtx = ctx.acquirePage(pageIndexes[i]);
12367      const textPagePtr = this.pdfiumModule.FPDFText_LoadPage(pageCtx.pagePtr);
12368      const charCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
12369      const bufferPtr = this.memoryManager.malloc((charCount + 1) * 2);
12370      this.pdfiumModule.FPDFText_GetText(textPagePtr, 0, charCount, bufferPtr);
12371      const text2 = this.pdfiumModule.pdfium.UTF16ToString(bufferPtr);
12372      this.memoryManager.free(bufferPtr);
12373      strings.push(text2);
12374      this.pdfiumModule.FPDFText_ClosePage(textPagePtr);
12375      pageCtx.release();
12376    }
12377    const text = strings.join("\\n\\n");
12378    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractText\`, "End", doc.id);
12379    return PdfTaskHelper.resolve(text);
12380  }
12381  /**
12382   * {@inheritDoc @embedpdf/models!PdfEngine.getTextSlices}
12383   *
12384   * @public
12385   */
12386  getTextSlices(doc, slices) {
12387    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getTextSlices", doc, slices);
12388    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "Begin", doc.id);
12389    if (slices.length === 0) {
12390      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);
12391      return PdfTaskHelper.resolve([]);
12392    }
12393    const ctx = this.cache.getContext(doc.id);
12394    if (!ctx) {
12395      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);
12396      return PdfTaskHelper.reject({
12397        code: PdfErrorCode.DocNotOpen,
12398        message: "document does not open"
12399      });
12400    }
12401    try {
12402      const out = new Array(slices.length);
12403      const byPage = /* @__PURE__ */ new Map();
12404      slices.forEach((s, i) => {
12405        (byPage.get(s.pageIndex) ?? byPage.set(s.pageIndex, []).get(s.pageIndex)).push({
12406          slice: s,
12407          pos: i
12408        });
12409      });
12410      for (const [pageIdx, list] of byPage) {
12411        const pageCtx = ctx.acquirePage(pageIdx);
12412        const textPagePtr = pageCtx.getTextPage();
12413        for (const { slice, pos } of list) {
12414          const bufPtr = this.memoryManager.malloc(2 * (slice.charCount + 1));
12415          this.pdfiumModule.FPDFText_GetText(textPagePtr, slice.charIndex, slice.charCount, bufPtr);
12416          out[pos] = stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(bufPtr));
12417          this.memoryManager.free(bufPtr);
12418        }
12419        pageCtx.release();
12420      }
12421      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);
12422      return PdfTaskHelper.resolve(out);
12423    } catch (e) {
12424      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "getTextSlices error", e);
12425      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);
12426      return PdfTaskHelper.reject({
12427        code: PdfErrorCode.Unknown,
12428        message: String(e)
12429      });
12430    }
12431  }
12432  /**
12433   * {@inheritDoc @embedpdf/models!PdfEngine.merge}
12434   *
12435   * @public
12436   */
12437  merge(files) {
12438    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "merge", files);
12439    const fileIds = files.map((file2) => file2.id).join(".");
12440    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "Begin", fileIds);
12441    const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();
12442    if (!newDocPtr) {
12443      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "End", fileIds);
12444      return PdfTaskHelper.reject({
12445        code: PdfErrorCode.CantCreateNewDoc,
12446        message: "can not create new document"
12447      });
12448    }
12449    const ptrs = [];
12450    for (const file2 of files.reverse()) {
12451      const array = new Uint8Array(file2.content);
12452      const length = array.length;
12453      const filePtr = this.memoryManager.malloc(length);
12454      this.pdfiumModule.pdfium.HEAPU8.set(array, filePtr);
12455      const docPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, length, "");
12456      if (!docPtr) {
12457        const lastError = this.pdfiumModule.FPDF_GetLastError();
12458        this.logger.error(
12459          LOG_SOURCE$1,
12460          LOG_CATEGORY$1,
12461          \`FPDF_LoadMemDocument failed with \${lastError}\`
12462        );
12463        this.memoryManager.free(filePtr);
12464        for (const ptr of ptrs) {
12465          this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);
12466          this.memoryManager.free(ptr.filePtr);
12467        }
12468        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "End", fileIds);
12469        return PdfTaskHelper.reject({
12470          code: lastError,
12471          message: \`FPDF_LoadMemDocument failed\`
12472        });
12473      }
12474      ptrs.push({ filePtr, docPtr });
12475      if (!this.pdfiumModule.FPDF_ImportPages(newDocPtr, docPtr, "", 0)) {
12476        this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12477        for (const ptr of ptrs) {
12478          this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);
12479          this.memoryManager.free(ptr.filePtr);
12480        }
12481        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "End", fileIds);
12482        return PdfTaskHelper.reject({
12483          code: PdfErrorCode.CantImportPages,
12484          message: "can not import pages to new document"
12485        });
12486      }
12487    }
12488    const buffer = this.saveDocument(newDocPtr);
12489    this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12490    for (const ptr of ptrs) {
12491      this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);
12492      this.memoryManager.free(ptr.filePtr);
12493    }
12494    const file = {
12495      id: \`\${Math.random()}\`,
12496      content: buffer
12497    };
12498    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "End", fileIds);
12499    return PdfTaskHelper.resolve(file);
12500  }
12501  /**
12502   * Merges specific pages from multiple PDF documents in a custom order
12503   *
12504   * @param mergeConfigs Array of configurations specifying which pages to merge from which documents
12505   * @returns A PdfTask that resolves with the merged PDF file
12506   * @public
12507   */
12508  mergePages(mergeConfigs) {
12509    const configIds = mergeConfigs.map((config) => \`\${config.docId}:\${config.pageIndices.join(",")}\`).join("|");
12510    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "mergePages", mergeConfigs);
12511    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`MergePages\`, "Begin", configIds);
12512    const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();
12513    if (!newDocPtr) {
12514      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`MergePages\`, "End", configIds);
12515      return PdfTaskHelper.reject({
12516        code: PdfErrorCode.CantCreateNewDoc,
12517        message: "Cannot create new document"
12518      });
12519    }
12520    try {
12521      for (const config of [...mergeConfigs].reverse()) {
12522        const ctx = this.cache.getContext(config.docId);
12523        if (!ctx) {
12524          this.logger.warn(
12525            LOG_SOURCE$1,
12526            LOG_CATEGORY$1,
12527            \`Document \${config.docId} is not open, skipping\`
12528          );
12529          continue;
12530        }
12531        const pageCount = this.pdfiumModule.FPDF_GetPageCount(ctx.docPtr);
12532        const validPageIndices = config.pageIndices.filter(
12533          (index) => index >= 0 && index < pageCount
12534        );
12535        if (validPageIndices.length === 0) {
12536          continue;
12537        }
12538        const pageString = validPageIndices.map((index) => index + 1).join(",");
12539        try {
12540          if (!this.pdfiumModule.FPDF_ImportPages(
12541            newDocPtr,
12542            ctx.docPtr,
12543            pageString,
12544            0
12545            // Insert at the beginning
12546          )) {
12547            throw new Error(\`Failed to import pages \${pageString} from document \${config.docId}\`);
12548          }
12549        } finally {
12550        }
12551      }
12552      const buffer = this.saveDocument(newDocPtr);
12553      const file = {
12554        id: \`\${Math.random()}\`,
12555        content: buffer
12556      };
12557      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`MergePages\`, "End", configIds);
12558      return PdfTaskHelper.resolve(file);
12559    } catch (error) {
12560      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "mergePages failed", error);
12561      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`MergePages\`, "End", configIds);
12562      return PdfTaskHelper.reject({
12563        code: PdfErrorCode.CantImportPages,
12564        message: error instanceof Error ? error.message : "Failed to merge pages"
12565      });
12566    } finally {
12567      if (newDocPtr) {
12568        this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12569      }
12570    }
12571  }
12572  /**
12573   * Sets AES-256 encryption on a document.
12574   * Must be called before saveAsCopy() for encryption to take effect.
12575   *
12576   * @param doc - Document to encrypt
12577   * @param userPassword - Password to open document (empty = no open password)
12578   * @param ownerPassword - Password to change permissions (required)
12579   * @param allowedFlags - OR'd PdfPermissionFlag values indicating allowed actions
12580   * @returns true on success, false if already encrypted or invalid params
12581   *
12582   * @public
12583   */
12584  setDocumentEncryption(doc, userPassword, ownerPassword, allowedFlags) {
12585    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setDocumentEncryption", doc, allowedFlags);
12586    const ctx = this.cache.getContext(doc.id);
12587    if (!ctx) {
12588      return PdfTaskHelper.reject({
12589        code: PdfErrorCode.DocNotOpen,
12590        message: "document does not open"
12591      });
12592    }
12593    const result = this.pdfiumModule.EPDF_SetEncryption(
12594      ctx.docPtr,
12595      userPassword,
12596      ownerPassword,
12597      allowedFlags
12598    );
12599    return PdfTaskHelper.resolve(result);
12600  }
12601  /**
12602   * Marks document for encryption removal on save.
12603   * When saveAsCopy is called, the document will be saved without encryption.
12604   *
12605   * @param doc - Document to remove encryption from
12606   * @returns true on success
12607   *
12608   * @public
12609   */
12610  removeEncryption(doc) {
12611    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "removeEncryption", doc);
12612    const ctx = this.cache.getContext(doc.id);
12613    if (!ctx) {
12614      return PdfTaskHelper.reject({
12615        code: PdfErrorCode.DocNotOpen,
12616        message: "document does not open"
12617      });
12618    }
12619    const result = this.pdfiumModule.EPDF_RemoveEncryption(ctx.docPtr);
12620    return PdfTaskHelper.resolve(result);
12621  }
12622  /**
12623   * Attempts to unlock owner permissions for an already-opened encrypted document.
12624   *
12625   * @param doc - Document to unlock
12626   * @param ownerPassword - The owner password
12627   * @returns true on success, false on failure
12628   *
12629   * @public
12630   */
12631  unlockOwnerPermissions(doc, ownerPassword) {
12632    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "unlockOwnerPermissions", doc.id);
12633    const ctx = this.cache.getContext(doc.id);
12634    if (!ctx) {
12635      return PdfTaskHelper.reject({
12636        code: PdfErrorCode.DocNotOpen,
12637        message: "document does not open"
12638      });
12639    }
12640    const success = this.pdfiumModule.EPDF_UnlockOwnerPermissions(ctx.docPtr, ownerPassword);
12641    return PdfTaskHelper.resolve(success);
12642  }
12643  /**
12644   * Check if a document is encrypted.
12645   *
12646   * @param doc - Document to check
12647   * @returns true if the document is encrypted
12648   *
12649   * @public
12650   */
12651  isEncrypted(doc) {
12652    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "isEncrypted", doc.id);
12653    const ctx = this.cache.getContext(doc.id);
12654    if (!ctx) {
12655      return PdfTaskHelper.reject({
12656        code: PdfErrorCode.DocNotOpen,
12657        message: "document does not open"
12658      });
12659    }
12660    const result = this.pdfiumModule.EPDF_IsEncrypted(ctx.docPtr);
12661    return PdfTaskHelper.resolve(result);
12662  }
12663  /**
12664   * Check if owner permissions are currently unlocked.
12665   *
12666   * @param doc - Document to check
12667   * @returns true if owner permissions are unlocked
12668   *
12669   * @public
12670   */
12671  isOwnerUnlocked(doc) {
12672    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "isOwnerUnlocked", doc.id);
12673    const ctx = this.cache.getContext(doc.id);
12674    if (!ctx) {
12675      return PdfTaskHelper.reject({
12676        code: PdfErrorCode.DocNotOpen,
12677        message: "document does not open"
12678      });
12679    }
12680    const result = this.pdfiumModule.EPDF_IsOwnerUnlocked(ctx.docPtr);
12681    return PdfTaskHelper.resolve(result);
12682  }
12683  /**
12684   * {@inheritDoc @embedpdf/models!PdfEngine.saveAsCopy}
12685   *
12686   * @public
12687   */
12688  saveAsCopy(doc) {
12689    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "saveAsCopy", doc);
12690    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SaveAsCopy\`, "Begin", doc.id);
12691    const ctx = this.cache.getContext(doc.id);
12692    if (!ctx) {
12693      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SaveAsCopy\`, "End", doc.id);
12694      return PdfTaskHelper.reject({
12695        code: PdfErrorCode.DocNotOpen,
12696        message: "document does not open"
12697      });
12698    }
12699    const buffer = this.saveDocument(ctx.docPtr);
12700    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SaveAsCopy\`, "End", doc.id);
12701    return PdfTaskHelper.resolve(buffer);
12702  }
12703  /**
12704   * {@inheritDoc @embedpdf/models!PdfEngine.closeDocument}
12705   *
12706   * @public
12707   */
12708  closeDocument(doc) {
12709    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "closeDocument", doc);
12710    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`CloseDocument\`, "Begin", doc.id);
12711    this.cache.closeDocument(doc.id);
12712    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`CloseDocument\`, "End", doc.id);
12713    return PdfTaskHelper.resolve(true);
12714  }
12715  /**
12716   * {@inheritDoc @embedpdf/models!PdfEngine.closeAllDocuments}
12717   *
12718   * @public
12719   */
12720  closeAllDocuments() {
12721    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "closeAllDocuments");
12722    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`CloseAllDocuments\`, "Begin");
12723    this.cache.closeAllDocuments();
12724    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`CloseAllDocuments\`, "End");
12725    return PdfTaskHelper.resolve(true);
12726  }
12727  /**
12728   * Add text content to annotation
12729   * @param page - page info
12730   * @param pagePtr - pointer to page object
12731   * @param annotationPtr - pointer to text annotation
12732   * @param annotation - text annotation
12733   * @returns whether text content is added to annotation
12734   *
12735   * @private
12736   */
12737  addTextContent(doc, page, pagePtr, annotationPtr, annotation) {
12738    if (!this.setAnnotationName(
12739      annotationPtr,
12740      annotation.name ?? annotation.icon ?? PdfAnnotationName.Comment
12741    )) {
12742      return false;
12743    }
12744    if (annotation.state && !this.setAnnotString(annotationPtr, "State", annotation.state)) {
12745      return false;
12746    }
12747    if (annotation.stateModel && !this.setAnnotString(annotationPtr, "StateModel", annotation.stateModel)) {
12748      return false;
12749    }
12750    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
12751      return false;
12752    }
12753    const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";
12754    if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {
12755      return false;
12756    }
12757    if (!annotation.flags) {
12758      if (!this.setAnnotationFlags(annotationPtr, ["print", "noZoom", "noRotate"])) {
12759        return false;
12760      }
12761    }
12762    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
12763  }
12764  /**
12765   * Add caret content to annotation
12766   * @param doc - document object
12767   * @param page - page info
12768   * @param pagePtr - pointer to page object
12769   * @param annotationPtr - pointer to caret annotation
12770   * @param annotation - caret annotation
12771   * @returns whether caret content is added to annotation
12772   *
12773   * @private
12774   */
12775  addCaretContent(doc, page, pagePtr, annotationPtr, annotation) {
12776    if (annotation.strokeColor) {
12777      this.setAnnotationColor(annotationPtr, annotation.strokeColor, PdfAnnotationColorType.Color);
12778    }
12779    if (annotation.opacity !== void 0) {
12780      this.setAnnotationOpacity(annotationPtr, annotation.opacity);
12781    }
12782    if (annotation.intent) {
12783      this.setAnnotIntent(annotationPtr, annotation.intent);
12784    }
12785    this.setRectangleDifferences(annotationPtr, annotation.rectangleDifferences);
12786    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
12787  }
12788  /**
12789   * Add free text content to annotation
12790   * @param page - page info
12791   * @param pagePtr - pointer to page object
12792   * @param annotationPtr - pointer to free text annotation
12793   * @param annotation - free text annotation
12794   * @returns whether free text content is added to annotation
12795   *
12796   * @private
12797   */
12798  addFreeTextContent(doc, page, pagePtr, annotationPtr, annotation) {
12799    if (!this.setBorderStyle(
12800      annotationPtr,
12801      PdfAnnotationBorderStyle.SOLID,
12802      annotation.strokeWidth ?? 0
12803    )) {
12804      return false;
12805    }
12806    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
12807      return false;
12808    }
12809    if (!this.setAnnotationTextAlignment(annotationPtr, annotation.textAlign)) {
12810      return false;
12811    }
12812    if (!this.setAnnotationVerticalAlignment(annotationPtr, annotation.verticalAlign)) {
12813      return false;
12814    }
12815    const daColor = annotation.strokeColor ?? annotation.fontColor;
12816    if (!this.setAnnotationDefaultAppearance(
12817      annotationPtr,
12818      annotation.fontFamily === PdfStandardFont.Unknown ? PdfStandardFont.Helvetica : annotation.fontFamily,
12819      annotation.fontSize,
12820      daColor
12821    )) {
12822      return false;
12823    }
12824    if (annotation.strokeColor && annotation.strokeColor !== annotation.fontColor) {
12825      this.setAnnotationColor(
12826        annotationPtr,
12827        annotation.fontColor,
12828        PdfAnnotationColorType.TextColor
12829      );
12830    }
12831    if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {
12832      return false;
12833    }
12834    if (annotation.calloutLine && annotation.calloutLine.length >= 2 && !this.setCalloutLine(doc, page, annotationPtr, annotation.calloutLine)) {
12835      return false;
12836    }
12837    if (annotation.lineEnding !== void 0 && !this.setLineEndings(annotationPtr, PdfAnnotationLineEnding.None, annotation.lineEnding)) {
12838      return false;
12839    }
12840    const bgColor = annotation.color ?? annotation.backgroundColor;
12841    if (!bgColor || bgColor === "transparent") {
12842      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.Color)) {
12843        return false;
12844      }
12845    } else if (!this.setAnnotationColor(annotationPtr, bgColor ?? "#FFFFFF", PdfAnnotationColorType.Color)) {
12846      return false;
12847    }
12848    this.setRectangleDifferences(annotationPtr, annotation.rectangleDifferences);
12849    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
12850  }
12851  addTextFieldContent(formHandle, annotationPtr, annotation) {
12852    if (!this.setAnnotationDefaultAppearance(
12853      annotationPtr,
12854      annotation.fontFamily,
12855      annotation.fontSize,
12856      annotation.fontColor
12857    )) {
12858      return false;
12859    }
12860    if (!this.setBorderStyle(
12861      annotationPtr,
12862      PdfAnnotationBorderStyle.SOLID,
12863      annotation.strokeWidth ?? 1
12864    )) {
12865      return false;
12866    }
12867    if (annotation.strokeColor && annotation.strokeColor !== "transparent") {
12868      this.setMKColor(annotationPtr, 0, annotation.strokeColor);
12869    } else {
12870      this.clearMKColor(annotationPtr, 0);
12871    }
12872    if (annotation.color && annotation.color !== "transparent") {
12873      this.setMKColor(annotationPtr, 1, annotation.color);
12874    } else {
12875      this.clearMKColor(annotationPtr, 1);
12876    }
12877    const userFlags = annotation.field.flag ?? PDF_FORM_FIELD_FLAG.NONE;
12878    this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(formHandle, annotationPtr, userFlags);
12879    if (annotation.field.name) {
12880      this.withWString(
12881        annotation.field.name,
12882        (namePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldName(formHandle, annotationPtr, namePtr)
12883      );
12884    }
12885    this.withWString(
12886      annotation.field.value ?? "",
12887      (valuePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldValue(formHandle, annotationPtr, valuePtr)
12888    );
12889    const textField = annotation.field;
12890    if (textField.maxLen != null && textField.maxLen > 0) {
12891      this.pdfiumModule.EPDFAnnot_SetNumberValue(annotationPtr, "MaxLen", textField.maxLen);
12892    }
12893    return true;
12894  }
12895  addToggleFieldContent(formHandle, annotationPtr, annotation) {
12896    if (!this.setBorderStyle(
12897      annotationPtr,
12898      PdfAnnotationBorderStyle.SOLID,
12899      annotation.strokeWidth ?? 1
12900    )) {
12901      return false;
12902    }
12903    if (annotation.strokeColor && annotation.strokeColor !== "transparent") {
12904      this.setMKColor(annotationPtr, 0, annotation.strokeColor);
12905    } else {
12906      this.clearMKColor(annotationPtr, 0);
12907    }
12908    if (annotation.color && annotation.color !== "transparent") {
12909      this.setMKColor(annotationPtr, 1, annotation.color);
12910    } else {
12911      this.clearMKColor(annotationPtr, 1);
12912    }
12913    let finalFlags = annotation.field.flag ?? PDF_FORM_FIELD_FLAG.NONE;
12914    if (annotation.field.type === PDF_FORM_FIELD_TYPE.RADIOBUTTON) {
12915      finalFlags |= PDF_FORM_FIELD_FLAG.BUTTON_RADIO | PDF_FORM_FIELD_FLAG.BUTTON_NOTOGGLETOOFF;
12916    }
12917    this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(formHandle, annotationPtr, finalFlags);
12918    if (annotation.field.name) {
12919      this.withWString(
12920        annotation.field.name,
12921        (namePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldName(formHandle, annotationPtr, namePtr)
12922      );
12923    }
12924    return true;
12925  }
12926  addChoiceFieldContent(formHandle, annotationPtr, annotation) {
12927    if (!this.setAnnotationDefaultAppearance(
12928      annotationPtr,
12929      annotation.fontFamily,
12930      annotation.fontSize,
12931      annotation.fontColor
12932    )) {
12933      return false;
12934    }
12935    if (!this.setBorderStyle(
12936      annotationPtr,
12937      PdfAnnotationBorderStyle.SOLID,
12938      annotation.strokeWidth ?? 1
12939    )) {
12940      return false;
12941    }
12942    if (annotation.strokeColor && annotation.strokeColor !== "transparent") {
12943      this.setMKColor(annotationPtr, 0, annotation.strokeColor);
12944    } else {
12945      this.clearMKColor(annotationPtr, 0);
12946    }
12947    if (annotation.color && annotation.color !== "transparent") {
12948      this.setMKColor(annotationPtr, 1, annotation.color);
12949    } else {
12950      this.clearMKColor(annotationPtr, 1);
12951    }
12952    let choiceFlags = annotation.field.flag ?? PDF_FORM_FIELD_FLAG.NONE;
12953    if (annotation.field.type === PDF_FORM_FIELD_TYPE.COMBOBOX) {
12954      choiceFlags |= 1 << 17;
12955    }
12956    this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(formHandle, annotationPtr, choiceFlags);
12957    if (annotation.field.name) {
12958      this.withWString(
12959        annotation.field.name,
12960        (namePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldName(formHandle, annotationPtr, namePtr)
12961      );
12962    }
12963    const field = annotation.field;
12964    const options = field.options ?? [];
12965    if (options.length > 0) {
12966      const ptrSize = 4;
12967      const arrayPtr = this.memoryManager.malloc(options.length * ptrSize);
12968      const labelPtrs = [];
12969      try {
12970        for (let i = 0; i < options.length; i++) {
12971          const label = options[i].label;
12972          const byteLen = (label.length + 1) * 2;
12973          const labelPtr = this.memoryManager.malloc(byteLen);
12974          this.pdfiumModule.pdfium.stringToUTF16(label, labelPtr, byteLen);
12975          labelPtrs.push(labelPtr);
12976          this.pdfiumModule.pdfium.setValue(arrayPtr + i * ptrSize, labelPtr, "*");
12977        }
12978        this.pdfiumModule.EPDFAnnot_SetFormFieldOptions(
12979          formHandle,
12980          annotationPtr,
12981          arrayPtr,
12982          options.length
12983        );
12984      } finally {
12985        for (const ptr of labelPtrs) {
12986          this.memoryManager.free(WasmPointer(ptr));
12987        }
12988        this.memoryManager.free(arrayPtr);
12989      }
12990    }
12991    const selectedOption = options.find((opt) => opt.isSelected);
12992    const value = (selectedOption == null ? void 0 : selectedOption.label) ?? annotation.field.value ?? "";
12993    this.withWString(
12994      value,
12995      (valuePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldValue(formHandle, annotationPtr, valuePtr)
12996    );
12997    return true;
12998  }
12999  setMKColor(annotationPtr, mkType, webColor) {
13000    const { red, green, blue } = webColorToPdfColor(webColor);
13001    return this.pdfiumModule.EPDFAnnot_SetMKColor(
13002      annotationPtr,
13003      mkType,
13004      red & 255,
13005      green & 255,
13006      blue & 255
13007    );
13008  }
13009  clearMKColor(annotationPtr, mkType) {
13010    return this.pdfiumModule.EPDFAnnot_ClearMKColor(annotationPtr, mkType);
13011  }
13012  getMKColor(annotationPtr, mkType) {
13013    const rPtr = this.memoryManager.malloc(4);
13014    const gPtr = this.memoryManager.malloc(4);
13015    const bPtr = this.memoryManager.malloc(4);
13016    try {
13017      const ok = this.pdfiumModule.EPDFAnnot_GetMKColor(annotationPtr, mkType, rPtr, gPtr, bPtr);
13018      if (!ok) return void 0;
13019      const r = this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255;
13020      const g = this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255;
13021      const b = this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255;
13022      return pdfColorToWebColor({ red: r, green: g, blue: b });
13023    } finally {
13024      this.memoryManager.free(bPtr);
13025      this.memoryManager.free(gPtr);
13026      this.memoryManager.free(rPtr);
13027    }
13028  }
13029  /**
13030   * Set the rect of specified annotation
13031   * @param page - page info that the annotation is belonged to
13032   * @param pagePtr - pointer of page object
13033   * @param annotationPtr - pointer to annotation object
13034   * @param inkList - ink lists that added to the annotation
13035   * @returns whether the ink lists is setted
13036   *
13037   * @private
13038   */
13039  addInkStroke(doc, page, pagePtr, annotationPtr, annotation) {
13040    if (!this.setBorderStyle(annotationPtr, PdfAnnotationBorderStyle.SOLID, annotation.strokeWidth)) {
13041      return false;
13042    }
13043    if (!this.setInkList(doc, page, annotationPtr, annotation.inkList)) {
13044      return false;
13045    }
13046    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13047      return false;
13048    }
13049    const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";
13050    if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {
13051      return false;
13052    }
13053    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13054  }
13055  /**
13056   * Add line content to annotation
13057   * @param page - page info
13058   * @param pagePtr - pointer to page object
13059   * @param annotationPtr - pointer to line annotation
13060   * @param annotation - line annotation
13061   * @returns whether line content is added to annotation
13062   *
13063   * @private
13064   */
13065  addLineContent(doc, page, pagePtr, annotationPtr, annotation) {
13066    var _a, _b;
13067    if (!this.setLinePoints(
13068      doc,
13069      page,
13070      annotationPtr,
13071      annotation.linePoints.start,
13072      annotation.linePoints.end
13073    )) {
13074      return false;
13075    }
13076    if (!this.setLineEndings(
13077      annotationPtr,
13078      ((_a = annotation.lineEndings) == null ? void 0 : _a.start) ?? PdfAnnotationLineEnding.None,
13079      ((_b = annotation.lineEndings) == null ? void 0 : _b.end) ?? PdfAnnotationLineEnding.None
13080    )) {
13081      return false;
13082    }
13083    if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {
13084      return false;
13085    }
13086    if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {
13087      return false;
13088    }
13089    if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {
13090      return false;
13091    }
13092    if (!annotation.color || annotation.color === "transparent") {
13093      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {
13094        return false;
13095      }
13096    } else if (!this.setAnnotationColor(
13097      annotationPtr,
13098      annotation.color ?? "#FFFF00",
13099      PdfAnnotationColorType.InteriorColor
13100    )) {
13101      return false;
13102    }
13103    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13104      return false;
13105    }
13106    if (!this.setAnnotationColor(
13107      annotationPtr,
13108      annotation.strokeColor ?? "#FFFF00",
13109      PdfAnnotationColorType.Color
13110    )) {
13111      return false;
13112    }
13113    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13114  }
13115  /**
13116   * Add polygon or polyline content to annotation
13117   * @param page - page info
13118   * @param pagePtr - pointer to page object
13119   * @param annotationPtr - pointer to polygon or polyline annotation
13120   * @param annotation - polygon or polyline annotation
13121   * @returns whether polygon or polyline content is added to annotation
13122   *
13123   * @private
13124   */
13125  addPolyContent(doc, page, pagePtr, annotationPtr, annotation) {
13126    var _a, _b;
13127    if (annotation.type === PdfAnnotationSubtype.POLYLINE && !this.setLineEndings(
13128      annotationPtr,
13129      ((_a = annotation.lineEndings) == null ? void 0 : _a.start) ?? PdfAnnotationLineEnding.None,
13130      ((_b = annotation.lineEndings) == null ? void 0 : _b.end) ?? PdfAnnotationLineEnding.None
13131    )) {
13132      return false;
13133    }
13134    if (!this.setPdfAnnoVertices(doc, page, annotationPtr, annotation.vertices)) {
13135      return false;
13136    }
13137    if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {
13138      return false;
13139    }
13140    if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {
13141      return false;
13142    }
13143    if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {
13144      return false;
13145    }
13146    if (!annotation.color || annotation.color === "transparent") {
13147      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {
13148        return false;
13149      }
13150    } else if (!this.setAnnotationColor(
13151      annotationPtr,
13152      annotation.color ?? "#FFFF00",
13153      PdfAnnotationColorType.InteriorColor
13154    )) {
13155      return false;
13156    }
13157    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13158      return false;
13159    }
13160    if (!this.setAnnotationColor(
13161      annotationPtr,
13162      annotation.strokeColor ?? "#FFFF00",
13163      PdfAnnotationColorType.Color
13164    )) {
13165      return false;
13166    }
13167    if (annotation.type === PdfAnnotationSubtype.POLYGON) {
13168      const poly = annotation;
13169      this.setRectangleDifferences(annotationPtr, poly.rectangleDifferences);
13170      this.setBorderEffect(annotationPtr, poly.cloudyBorderIntensity);
13171    }
13172    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13173  }
13174  /**
13175   * Add link content (action or destination) to a link annotation
13176   * @param docPtr - pointer to pdf document
13177   * @param pagePtr - pointer to the page
13178   * @param annotationPtr - pointer to pdf annotation
13179   * @param annotation - the link annotation object
13180   * @returns true if successful
13181   *
13182   * @private
13183   */
13184  addLinkContent(doc, page, docPtr, pagePtr, annotationPtr, annotation) {
13185    const style = annotation.strokeStyle ?? PdfAnnotationBorderStyle.UNDERLINE;
13186    const width = annotation.strokeWidth ?? 2;
13187    if (!this.setBorderStyle(annotationPtr, style, width)) {
13188      return false;
13189    }
13190    if (annotation.strokeDashArray && !this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray)) {
13191      return false;
13192    }
13193    if (annotation.strokeColor) {
13194      if (!this.setAnnotationColor(
13195        annotationPtr,
13196        annotation.strokeColor,
13197        PdfAnnotationColorType.Color
13198      )) {
13199        return false;
13200      }
13201    }
13202    if (annotation.target) {
13203      if (!this.applyLinkTarget(docPtr, annotationPtr, annotation.target)) {
13204        return false;
13205      }
13206    }
13207    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13208  }
13209  /**
13210   * Add shape content to annotation
13211   * @param page - page info
13212   * @param pagePtr - pointer to page object
13213   * @param annotationPtr - pointer to shape annotation
13214   * @param annotation - shape annotation
13215   * @returns whether shape content is added to annotation
13216   *
13217   * @private
13218   */
13219  addShapeContent(doc, page, pagePtr, annotationPtr, annotation) {
13220    if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {
13221      return false;
13222    }
13223    if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {
13224      return false;
13225    }
13226    if (!annotation.color || annotation.color === "transparent") {
13227      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {
13228        return false;
13229      }
13230    } else if (!this.setAnnotationColor(
13231      annotationPtr,
13232      annotation.color ?? "#FFFF00",
13233      PdfAnnotationColorType.InteriorColor
13234    )) {
13235      return false;
13236    }
13237    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13238      return false;
13239    }
13240    if (!this.setAnnotationColor(
13241      annotationPtr,
13242      annotation.strokeColor ?? "#FFFF00",
13243      PdfAnnotationColorType.Color
13244    )) {
13245      return false;
13246    }
13247    this.setRectangleDifferences(annotationPtr, annotation.rectangleDifferences);
13248    this.setBorderEffect(annotationPtr, annotation.cloudyBorderIntensity);
13249    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13250  }
13251  /**
13252   * Add highlight content to annotation
13253   * @param page - page info
13254   * @param annotationPtr - pointer to highlight annotation
13255   * @param annotation - highlight annotation
13256   * @returns whether highlight content is added to annotation
13257   *
13258   * @private
13259   */
13260  addTextMarkupContent(doc, page, pagePtr, annotationPtr, annotation) {
13261    if (!this.syncQuadPointsAnno(doc, page, annotationPtr, annotation.segmentRects)) {
13262      return false;
13263    }
13264    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13265      return false;
13266    }
13267    const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";
13268    if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {
13269      return false;
13270    }
13271    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13272  }
13273  /**
13274   * Add content to redact annotation
13275   * @param page - page info
13276   * @param pagePtr - pointer to page object
13277   * @param annotationPtr - pointer to redact annotation
13278   * @param annotation - redact annotation
13279   * @returns whether redact content is added to annotation
13280   *
13281   * @private
13282   */
13283  addRedactContent(doc, page, pagePtr, annotationPtr, annotation) {
13284    if (!this.syncQuadPointsAnno(doc, page, annotationPtr, annotation.segmentRects)) {
13285      return false;
13286    }
13287    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13288      return false;
13289    }
13290    if (!annotation.color || annotation.color === "transparent") {
13291      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {
13292        return false;
13293      }
13294    } else if (!this.setAnnotationColor(
13295      annotationPtr,
13296      annotation.color,
13297      PdfAnnotationColorType.InteriorColor
13298    )) {
13299      return false;
13300    }
13301    if (!annotation.overlayColor || annotation.overlayColor === "transparent") {
13302      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.OverlayColor)) {
13303        return false;
13304      }
13305    } else if (!this.setAnnotationColor(
13306      annotationPtr,
13307      annotation.overlayColor,
13308      PdfAnnotationColorType.OverlayColor
13309    )) {
13310      return false;
13311    }
13312    if (!annotation.strokeColor || annotation.strokeColor === "transparent") {
13313      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.Color)) {
13314        return false;
13315      }
13316    } else if (!this.setAnnotationColor(annotationPtr, annotation.strokeColor, PdfAnnotationColorType.Color)) {
13317      return false;
13318    }
13319    if (!this.setOverlayText(annotationPtr, annotation.overlayText)) {
13320      return false;
13321    }
13322    if (annotation.overlayTextRepeat !== void 0 && !this.setOverlayTextRepeat(annotationPtr, annotation.overlayTextRepeat)) {
13323      return false;
13324    }
13325    if (annotation.fontFamily !== void 0 || annotation.fontSize !== void 0) {
13326      const font = annotation.fontFamily == null || annotation.fontFamily === PdfStandardFont.Unknown ? PdfStandardFont.Helvetica : annotation.fontFamily;
13327      if (!this.setAnnotationDefaultAppearance(
13328        annotationPtr,
13329        font,
13330        annotation.fontSize ?? 12,
13331        annotation.fontColor ?? "#000000"
13332      )) {
13333        return false;
13334      }
13335    }
13336    if (annotation.textAlign !== void 0 && !this.setAnnotationTextAlignment(annotationPtr, annotation.textAlign)) {
13337      return false;
13338    }
13339    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13340  }
13341  /**
13342   * Add contents to stamp annotation
13343   * @param doc - pdf document object
13344   * @param docPtr - pointer to pdf document object
13345   * @param page - page info
13346   * @param pagePtr - pointer to page object
13347   * @param annotationPtr - pointer to stamp annotation
13348   * @param rect - rect of stamp annotation
13349   * @param contents - contents of stamp annotation
13350   * @returns whether contents is added to annotation
13351   *
13352   * @private
13353   */
13354  addStampContent(doc, docPtr, page, pagePtr, annotationPtr, annotation, context) {
13355    const stampName = annotation.name ?? annotation.icon;
13356    if (stampName && !this.setAnnotationName(annotationPtr, stampName)) {
13357      return false;
13358    }
13359    if (context && "data" in context && context.data) {
13360      const meta = getImageMetadata(context.data);
13361      if (!meta) return false;
13362      if (meta.mimeType === "application/pdf") {
13363        if (!this.setAppearanceFromPdf(docPtr, annotationPtr, context.data)) {
13364          return false;
13365        }
13366      } else {
13367        for (let i = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr) - 1; i >= 0; i--) {
13368          this.pdfiumModule.FPDFAnnot_RemoveObject(annotationPtr, i);
13369        }
13370        if (meta.mimeType === "image/png") {
13371          if (!this.addPngImageObject(
13372            doc,
13373            docPtr,
13374            page,
13375            pagePtr,
13376            annotationPtr,
13377            annotation.rect,
13378            context.data
13379          )) {
13380            return false;
13381          }
13382        } else if (meta.mimeType === "image/jpeg") {
13383          if (!this.addJpegImageObject(
13384            doc,
13385            docPtr,
13386            page,
13387            pagePtr,
13388            annotationPtr,
13389            annotation.rect,
13390            context.data
13391          )) {
13392            return false;
13393          }
13394        }
13395      }
13396    } else if (context && "imageData" in context && context.imageData) {
13397      for (let i = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr) - 1; i >= 0; i--) {
13398        this.pdfiumModule.FPDFAnnot_RemoveObject(annotationPtr, i);
13399      }
13400      if (!this.addImageObject(
13401        doc,
13402        docPtr,
13403        page,
13404        pagePtr,
13405        annotationPtr,
13406        annotation.rect,
13407        context.imageData
13408      )) {
13409        return false;
13410      }
13411    } else if (context && "appearance" in context && context.appearance) {
13412      if (!this.setAppearanceFromPdf(docPtr, annotationPtr, context.appearance)) {
13413        return false;
13414      }
13415    }
13416    if (!this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation)) {
13417      return false;
13418    }
13419    return !!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(annotationPtr, PdfStampFit.Cover);
13420  }
13421  /**
13422   * Set an annotation's appearance from a single-page PDF document.
13423   * Loads the PDF into WASM memory, calls the native SetAppearanceFromPage,
13424   * then cleans up.
13425   */
13426  setAppearanceFromPdf(docPtr, annotationPtr, appearance) {
13427    const data = new Uint8Array(appearance);
13428    const filePtr = this.memoryManager.malloc(data.byteLength);
13429    this.pdfiumModule.pdfium.HEAPU8.set(data, filePtr);
13430    const tempDocPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, data.byteLength, "");
13431    if (!tempDocPtr) {
13432      this.memoryManager.free(filePtr);
13433      return false;
13434    }
13435    const ok = this.pdfiumModule.EPDFAnnot_SetAppearanceFromPage(annotationPtr, tempDocPtr, 0);
13436    this.pdfiumModule.FPDF_CloseDocument(tempDocPtr);
13437    this.memoryManager.free(filePtr);
13438    return !!ok;
13439  }
13440  /**
13441   * Add image object to annotation
13442   * @param doc - pdf document object
13443   * @param docPtr - pointer to pdf document object
13444   * @param page - page info
13445   * @param pagePtr - pointer to page object
13446   * @param annotationPtr - pointer to stamp annotation
13447   * @param position - position of image
13448   * @param imageData - data of image
13449   * @returns whether image is added to annotation
13450   *
13451   * @private
13452   */
13453  addImageObject(doc, docPtr, page, pagePtr, annotationPtr, rect, imageData) {
13454    const bytesPerPixel = 4;
13455    const pixelCount = imageData.width * imageData.height;
13456    const bitmapBufferPtr = this.memoryManager.malloc(bytesPerPixel * pixelCount);
13457    if (!bitmapBufferPtr) {
13458      return false;
13459    }
13460    for (let i = 0; i < pixelCount; i++) {
13461      const red = imageData.data[i * bytesPerPixel];
13462      const green = imageData.data[i * bytesPerPixel + 1];
13463      const blue = imageData.data[i * bytesPerPixel + 2];
13464      const alpha = imageData.data[i * bytesPerPixel + 3];
13465      this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel, blue, "i8");
13466      this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 1, green, "i8");
13467      this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 2, red, "i8");
13468      this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 3, alpha, "i8");
13469    }
13470    const format = 4;
13471    const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(
13472      imageData.width,
13473      imageData.height,
13474      format,
13475      bitmapBufferPtr,
13476      0
13477    );
13478    if (!bitmapPtr) {
13479      this.memoryManager.free(bitmapBufferPtr);
13480      return false;
13481    }
13482    const imageObjectPtr = this.pdfiumModule.FPDFPageObj_NewImageObj(docPtr);
13483    if (!imageObjectPtr) {
13484      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13485      this.memoryManager.free(bitmapBufferPtr);
13486      return false;
13487    }
13488    if (!this.pdfiumModule.FPDFImageObj_SetBitmap(pagePtr, 0, imageObjectPtr, bitmapPtr)) {
13489      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13490      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13491      this.memoryManager.free(bitmapBufferPtr);
13492      return false;
13493    }
13494    const matrixPtr = this.memoryManager.malloc(6 * 4);
13495    this.pdfiumModule.pdfium.setValue(matrixPtr, rect.size.width, "float");
13496    this.pdfiumModule.pdfium.setValue(matrixPtr + 4, 0, "float");
13497    this.pdfiumModule.pdfium.setValue(matrixPtr + 8, 0, "float");
13498    this.pdfiumModule.pdfium.setValue(matrixPtr + 12, rect.size.height, "float");
13499    this.pdfiumModule.pdfium.setValue(matrixPtr + 16, 0, "float");
13500    this.pdfiumModule.pdfium.setValue(matrixPtr + 20, 0, "float");
13501    if (!this.pdfiumModule.FPDFPageObj_SetMatrix(imageObjectPtr, matrixPtr)) {
13502      this.memoryManager.free(matrixPtr);
13503      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13504      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13505      this.memoryManager.free(bitmapBufferPtr);
13506      return false;
13507    }
13508    this.memoryManager.free(matrixPtr);
13509    const pagePos = this.convertDevicePointToPagePoint(doc, page, {
13510      x: rect.origin.x,
13511      y: rect.origin.y + rect.size.height
13512      // shift down by the authored display height
13513    });
13514    this.pdfiumModule.FPDFPageObj_Transform(imageObjectPtr, 1, 0, 0, 1, pagePos.x, pagePos.y);
13515    if (!this.pdfiumModule.FPDFAnnot_AppendObject(annotationPtr, imageObjectPtr)) {
13516      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13517      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13518      this.memoryManager.free(bitmapBufferPtr);
13519      return false;
13520    }
13521    this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13522    this.memoryManager.free(bitmapBufferPtr);
13523    return true;
13524  }
13525  /**
13526   * Add PNG image object to annotation using native PNG import.
13527   * Passes raw PNG bytes to PDFium which decodes and stores them with
13528   * FlateDecode + PNG prediction filters for optimal compression.
13529   *
13530   * @private
13531   */
13532  addPngImageObject(doc, docPtr, page, pagePtr, annotationPtr, rect, pngData) {
13533    const imageObjectPtr = this.pdfiumModule.FPDFPageObj_NewImageObj(docPtr);
13534    if (!imageObjectPtr) {
13535      return false;
13536    }
13537    const pngBytes = new Uint8Array(pngData);
13538    const pngPtr = this.memoryManager.malloc(pngBytes.byteLength);
13539    if (!pngPtr) {
13540      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13541      return false;
13542    }
13543    this.pdfiumModule.pdfium.HEAPU8.set(pngBytes, pngPtr);
13544    if (!this.pdfiumModule.EPDFImageObj_SetPng(
13545      pagePtr,
13546      0,
13547      imageObjectPtr,
13548      pngPtr,
13549      pngBytes.byteLength
13550    )) {
13551      this.memoryManager.free(pngPtr);
13552      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13553      return false;
13554    }
13555    this.memoryManager.free(pngPtr);
13556    const matrixPtr = this.memoryManager.malloc(6 * 4);
13557    this.pdfiumModule.pdfium.setValue(matrixPtr, rect.size.width, "float");
13558    this.pdfiumModule.pdfium.setValue(matrixPtr + 4, 0, "float");
13559    this.pdfiumModule.pdfium.setValue(matrixPtr + 8, 0, "float");
13560    this.pdfiumModule.pdfium.setValue(matrixPtr + 12, rect.size.height, "float");
13561    this.pdfiumModule.pdfium.setValue(matrixPtr + 16, 0, "float");
13562    this.pdfiumModule.pdfium.setValue(matrixPtr + 20, 0, "float");
13563    if (!this.pdfiumModule.FPDFPageObj_SetMatrix(imageObjectPtr, matrixPtr)) {
13564      this.memoryManager.free(matrixPtr);
13565      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13566      return false;
13567    }
13568    this.memoryManager.free(matrixPtr);
13569    const pagePos = this.convertDevicePointToPagePoint(doc, page, {
13570      x: rect.origin.x,
13571      y: rect.origin.y + rect.size.height
13572    });
13573    this.pdfiumModule.FPDFPageObj_Transform(imageObjectPtr, 1, 0, 0, 1, pagePos.x, pagePos.y);
13574    if (!this.pdfiumModule.FPDFAnnot_AppendObject(annotationPtr, imageObjectPtr)) {
13575      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13576      return false;
13577    }
13578    return true;
13579  }
13580  /**
13581   * Add JPEG image object to annotation using native JPEG pass-through.
13582   * Passes raw JPEG bytes to PDFium which embeds them as a DCTDecode
13583   * stream — no decode/re-encode roundtrip.
13584   *
13585   * @private
13586   */
13587  addJpegImageObject(doc, docPtr, page, pagePtr, annotationPtr, rect, jpegData) {
13588    const imageObjectPtr = this.pdfiumModule.FPDFPageObj_NewImageObj(docPtr);
13589    if (!imageObjectPtr) {
13590      return false;
13591    }
13592    const jpegBytes = new Uint8Array(jpegData);
13593    const jpegPtr = this.memoryManager.malloc(jpegBytes.byteLength);
13594    if (!jpegPtr) {
13595      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13596      return false;
13597    }
13598    this.pdfiumModule.pdfium.HEAPU8.set(jpegBytes, jpegPtr);
13599    if (!this.pdfiumModule.EPDFImageObj_SetJpeg(
13600      pagePtr,
13601      0,
13602      imageObjectPtr,
13603      jpegPtr,
13604      jpegBytes.byteLength
13605    )) {
13606      this.memoryManager.free(jpegPtr);
13607      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13608      return false;
13609    }
13610    this.memoryManager.free(jpegPtr);
13611    const matrixPtr = this.memoryManager.malloc(6 * 4);
13612    this.pdfiumModule.pdfium.setValue(matrixPtr, rect.size.width, "float");
13613    this.pdfiumModule.pdfium.setValue(matrixPtr + 4, 0, "float");
13614    this.pdfiumModule.pdfium.setValue(matrixPtr + 8, 0, "float");
13615    this.pdfiumModule.pdfium.setValue(matrixPtr + 12, rect.size.height, "float");
13616    this.pdfiumModule.pdfium.setValue(matrixPtr + 16, 0, "float");
13617    this.pdfiumModule.pdfium.setValue(matrixPtr + 20, 0, "float");
13618    if (!this.pdfiumModule.FPDFPageObj_SetMatrix(imageObjectPtr, matrixPtr)) {
13619      this.memoryManager.free(matrixPtr);
13620      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13621      return false;
13622    }
13623    this.memoryManager.free(matrixPtr);
13624    const pagePos = this.convertDevicePointToPagePoint(doc, page, {
13625      x: rect.origin.x,
13626      y: rect.origin.y + rect.size.height
13627    });
13628    this.pdfiumModule.FPDFPageObj_Transform(imageObjectPtr, 1, 0, 0, 1, pagePos.x, pagePos.y);
13629    if (!this.pdfiumModule.FPDFAnnot_AppendObject(annotationPtr, imageObjectPtr)) {
13630      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13631      return false;
13632    }
13633    return true;
13634  }
13635  /**
13636   * Save document to array buffer
13637   * @param docPtr - pointer to pdf document
13638   * @returns array buffer contains the pdf content
13639   *
13640   * @private
13641   */
13642  saveDocument(docPtr) {
13643    const writerPtr = this.pdfiumModule.PDFiumExt_OpenFileWriter();
13644    this.pdfiumModule.PDFiumExt_SaveAsCopy(docPtr, writerPtr);
13645    const size = this.pdfiumModule.PDFiumExt_GetFileWriterSize(writerPtr);
13646    const dataPtr = this.memoryManager.malloc(size);
13647    this.pdfiumModule.PDFiumExt_GetFileWriterData(writerPtr, dataPtr, size);
13648    const buffer = new ArrayBuffer(size);
13649    const view = new DataView(buffer);
13650    for (let i = 0; i < size; i++) {
13651      view.setInt8(i, this.pdfiumModule.pdfium.getValue(dataPtr + i, "i8"));
13652    }
13653    this.memoryManager.free(dataPtr);
13654    this.pdfiumModule.PDFiumExt_CloseFileWriter(writerPtr);
13655    return buffer;
13656  }
13657  /**
13658   * Read Catalog /Lang via EPDFCatalog_GetLanguage (UTF-16LE → JS string).
13659   * Returns:
13660   *   null  -> /Lang not present (getter returned 0) OR doc not open,
13661   *   ''    -> /Lang exists but is explicitly empty,
13662   *   'en', 'en-US', ... -> normal tag.
13663   *
13664   * Note: EPDFCatalog_GetLanguage lengths are BYTES (incl. trailing NUL).
13665   *
13666   * @private
13667   */
13668  readCatalogLanguage(docPtr) {
13669    const byteLen = this.pdfiumModule.EPDFCatalog_GetLanguage(docPtr, 0, 0) >>> 0;
13670    if (byteLen === 0) return null;
13671    if (byteLen === 2) return "";
13672    return readString(
13673      this.pdfiumModule.pdfium,
13674      (buffer, bufferLength) => this.pdfiumModule.EPDFCatalog_GetLanguage(docPtr, buffer, bufferLength),
13675      this.pdfiumModule.pdfium.UTF16ToString,
13676      byteLen
13677    );
13678  }
13679  /**
13680   * Read metadata from pdf document
13681   * @param docPtr - pointer to pdf document
13682   * @param key - key of metadata field
13683   * @returns metadata value
13684   *
13685   * @private
13686   */
13687  readMetaText(docPtr, key) {
13688    const exists = !!this.pdfiumModule.EPDF_HasMetaText(docPtr, key);
13689    if (!exists) return null;
13690    const len = this.pdfiumModule.FPDF_GetMetaText(docPtr, key, 0, 0);
13691    if (len === 2) return "";
13692    return readString(
13693      this.pdfiumModule.pdfium,
13694      (buffer, bufferLength) => this.pdfiumModule.FPDF_GetMetaText(docPtr, key, buffer, bufferLength),
13695      this.pdfiumModule.pdfium.UTF16ToString,
13696      len
13697    );
13698  }
13699  /**
13700   * Write metadata into the PDF's Info dictionary.
13701   * If \`value\` is null or empty string, the key is removed.
13702   * @param docPtr - pointer to pdf document
13703   * @param key - key of metadata field
13704   * @param value - value of metadata field
13705   * @returns whether metadata is written to the pdf document
13706   *
13707   * @private
13708   */
13709  setMetaText(docPtr, key, value) {
13710    if (value == null || value.length === 0) {
13711      const ok = this.pdfiumModule.EPDF_SetMetaText(docPtr, key, 0);
13712      return !!ok;
13713    }
13714    const bytes = 2 * (value.length + 1);
13715    const ptr = this.memoryManager.malloc(bytes);
13716    try {
13717      this.pdfiumModule.pdfium.stringToUTF16(value, ptr, bytes);
13718      const ok = this.pdfiumModule.EPDF_SetMetaText(docPtr, key, ptr);
13719      return !!ok;
13720    } finally {
13721      this.memoryManager.free(ptr);
13722    }
13723  }
13724  /**
13725   * Read the document's trapped status via PDFium.
13726   * Falls back to \`Unknown\` on unexpected values.
13727   *
13728   * @private
13729   */
13730  getMetaTrapped(docPtr) {
13731    const raw = Number(this.pdfiumModule.EPDF_GetMetaTrapped(docPtr));
13732    switch (raw) {
13733      case PdfTrappedStatus.NotSet:
13734      case PdfTrappedStatus.True:
13735      case PdfTrappedStatus.False:
13736      case PdfTrappedStatus.Unknown:
13737        return raw;
13738      default:
13739        return PdfTrappedStatus.Unknown;
13740    }
13741  }
13742  /**
13743   * Write (or clear) the document's trapped status via PDFium.
13744   * Pass \`null\`/\`undefined\` to remove the \`/Trapped\` key.
13745   *
13746   * @private
13747   */
13748  setMetaTrapped(docPtr, status) {
13749    const toSet = status == null || status === void 0 ? PdfTrappedStatus.NotSet : status;
13750    const valid = toSet === PdfTrappedStatus.NotSet || toSet === PdfTrappedStatus.True || toSet === PdfTrappedStatus.False || toSet === PdfTrappedStatus.Unknown;
13751    if (!valid) return false;
13752    return !!this.pdfiumModule.EPDF_SetMetaTrapped(docPtr, toSet);
13753  }
13754  /**
13755   * Get the number of keys in the document's Info dictionary.
13756   * @param docPtr - pointer to pdf document
13757   * @param customOnly - if true, only count non-reserved (custom) keys; if false, count all keys.
13758   * @returns the number of keys (possibly 0). On error, returns 0.
13759   *
13760   * @private
13761   */
13762  getMetaKeyCount(docPtr, customOnly) {
13763    return Number(this.pdfiumModule.EPDF_GetMetaKeyCount(docPtr, customOnly)) | 0;
13764  }
13765  /**
13766   * Get the name of the Info dictionary key at |index|.
13767   * @param docPtr - pointer to pdf document
13768   * @param index - 0-based key index in the order returned by PDFium.
13769   * @param customOnly - if true, indexes only over non-reserved (custom) keys; if false, indexes over all keys.
13770   * @returns the name of the key, or null if the key is not found.
13771   *
13772   * @private
13773   */
13774  getMetaKeyName(docPtr, index, customOnly) {
13775    const len = this.pdfiumModule.EPDF_GetMetaKeyName(docPtr, index, customOnly, 0, 0);
13776    if (!len) return null;
13777    return readString(
13778      this.pdfiumModule.pdfium,
13779      (buffer, buflen) => this.pdfiumModule.EPDF_GetMetaKeyName(docPtr, index, customOnly, buffer, buflen),
13780      this.pdfiumModule.pdfium.UTF8ToString,
13781      len
13782    );
13783  }
13784  /**
13785   * Read all metadata from the document's Info dictionary.
13786   * @param docPtr - pointer to pdf document
13787   * @param customOnly - if true, only read non-reserved (custom) keys; if false, read all keys.
13788   * @returns all metadata
13789   *
13790   * @private
13791   */
13792  readAllMeta(docPtr, customOnly = true) {
13793    const n = this.getMetaKeyCount(docPtr, customOnly);
13794    const out = {};
13795    for (let i = 0; i < n; i++) {
13796      const key = this.getMetaKeyName(docPtr, i, customOnly);
13797      if (!key) continue;
13798      out[key] = this.readMetaText(docPtr, key);
13799    }
13800    return out;
13801  }
13802  /**
13803   * Read bookmarks in the pdf document
13804   * @param docPtr - pointer to pdf document
13805   * @param rootBookmarkPtr - pointer to root bookmark
13806   * @returns bookmarks in the pdf document
13807   *
13808   * @private
13809   */
13810  readPdfBookmarks(docPtr, rootBookmarkPtr = 0) {
13811    let bookmarkPtr = this.pdfiumModule.FPDFBookmark_GetFirstChild(docPtr, rootBookmarkPtr);
13812    const bookmarks = [];
13813    while (bookmarkPtr) {
13814      const bookmark = this.readPdfBookmark(docPtr, bookmarkPtr);
13815      bookmarks.push(bookmark);
13816      const nextBookmarkPtr = this.pdfiumModule.FPDFBookmark_GetNextSibling(docPtr, bookmarkPtr);
13817      bookmarkPtr = nextBookmarkPtr;
13818    }
13819    return bookmarks;
13820  }
13821  /**
13822   * Read bookmark in the pdf document
13823   * @param docPtr - pointer to pdf document
13824   * @param bookmarkPtr - pointer to bookmark object
13825   * @returns pdf bookmark object
13826   *
13827   * @private
13828   */
13829  readPdfBookmark(docPtr, bookmarkPtr) {
13830    const title = readString(
13831      this.pdfiumModule.pdfium,
13832      (buffer, bufferLength) => {
13833        return this.pdfiumModule.FPDFBookmark_GetTitle(bookmarkPtr, buffer, bufferLength);
13834      },
13835      this.pdfiumModule.pdfium.UTF16ToString
13836    );
13837    const bookmarks = this.readPdfBookmarks(docPtr, bookmarkPtr);
13838    const target = this.readPdfBookmarkTarget(
13839      docPtr,
13840      () => {
13841        return this.pdfiumModule.FPDFBookmark_GetAction(bookmarkPtr);
13842      },
13843      () => {
13844        return this.pdfiumModule.FPDFBookmark_GetDest(docPtr, bookmarkPtr);
13845      }
13846    );
13847    return {
13848      title,
13849      target,
13850      children: bookmarks
13851    };
13852  }
13853  /**
13854   * Read text rects in pdf page
13855   * @param page - pdf page info
13856   * @param docPtr - pointer to pdf document
13857   * @param pagePtr - pointer to pdf page
13858   * @param textPagePtr - pointer to pdf text page
13859   * @returns text rects in the pdf page
13860   *
13861   * @public
13862   */
13863  readPageTextRects(page, docPtr, pagePtr, textPagePtr) {
13864    const rectsCount = this.pdfiumModule.FPDFText_CountRects(textPagePtr, 0, -1);
13865    const textRects = [];
13866    for (let i = 0; i < rectsCount; i++) {
13867      const topPtr = this.memoryManager.malloc(8);
13868      const leftPtr = this.memoryManager.malloc(8);
13869      const rightPtr = this.memoryManager.malloc(8);
13870      const bottomPtr = this.memoryManager.malloc(8);
13871      const isSucceed = this.pdfiumModule.FPDFText_GetRect(
13872        textPagePtr,
13873        i,
13874        leftPtr,
13875        topPtr,
13876        rightPtr,
13877        bottomPtr
13878      );
13879      if (!isSucceed) {
13880        this.memoryManager.free(leftPtr);
13881        this.memoryManager.free(topPtr);
13882        this.memoryManager.free(rightPtr);
13883        this.memoryManager.free(bottomPtr);
13884        continue;
13885      }
13886      const left = this.pdfiumModule.pdfium.getValue(leftPtr, "double");
13887      const top = this.pdfiumModule.pdfium.getValue(topPtr, "double");
13888      const right = this.pdfiumModule.pdfium.getValue(rightPtr, "double");
13889      const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "double");
13890      this.memoryManager.free(leftPtr);
13891      this.memoryManager.free(topPtr);
13892      this.memoryManager.free(rightPtr);
13893      this.memoryManager.free(bottomPtr);
13894      const deviceXPtr = this.memoryManager.malloc(4);
13895      const deviceYPtr = this.memoryManager.malloc(4);
13896      this.pdfiumModule.FPDF_PageToDevice(
13897        pagePtr,
13898        0,
13899        0,
13900        page.size.width,
13901        page.size.height,
13902        0,
13903        left,
13904        top,
13905        deviceXPtr,
13906        deviceYPtr
13907      );
13908      const x = this.pdfiumModule.pdfium.getValue(deviceXPtr, "i32");
13909      const y = this.pdfiumModule.pdfium.getValue(deviceYPtr, "i32");
13910      this.memoryManager.free(deviceXPtr);
13911      this.memoryManager.free(deviceYPtr);
13912      const rect = {
13913        origin: {
13914          x,
13915          y
13916        },
13917        size: {
13918          width: Math.ceil(Math.abs(right - left)),
13919          height: Math.ceil(Math.abs(top - bottom))
13920        }
13921      };
13922      const utf16Length = this.pdfiumModule.FPDFText_GetBoundedText(
13923        textPagePtr,
13924        left,
13925        top,
13926        right,
13927        bottom,
13928        0,
13929        0
13930      );
13931      const bytesCount = (utf16Length + 1) * 2;
13932      const textBuffer = this.memoryManager.malloc(bytesCount);
13933      this.pdfiumModule.FPDFText_GetBoundedText(
13934        textPagePtr,
13935        left,
13936        top,
13937        right,
13938        bottom,
13939        textBuffer,
13940        utf16Length
13941      );
13942      const content = this.pdfiumModule.pdfium.UTF16ToString(textBuffer);
13943      this.memoryManager.free(textBuffer);
13944      const charIndex = this.pdfiumModule.FPDFText_GetCharIndexAtPos(textPagePtr, left, top, 2, 2);
13945      let fontFamily = "";
13946      let fontSize = rect.size.height;
13947      if (charIndex >= 0) {
13948        fontSize = this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, charIndex);
13949        const fontNameLength = this.pdfiumModule.FPDFText_GetFontInfo(
13950          textPagePtr,
13951          charIndex,
13952          0,
13953          0,
13954          0
13955        );
13956        const bytesCount2 = fontNameLength + 1;
13957        const textBufferPtr = this.memoryManager.malloc(bytesCount2);
13958        const flagsPtr = this.memoryManager.malloc(4);
13959        this.pdfiumModule.FPDFText_GetFontInfo(
13960          textPagePtr,
13961          charIndex,
13962          textBufferPtr,
13963          bytesCount2,
13964          flagsPtr
13965        );
13966        fontFamily = this.pdfiumModule.pdfium.UTF8ToString(textBufferPtr);
13967        this.memoryManager.free(textBufferPtr);
13968        this.memoryManager.free(flagsPtr);
13969      }
13970      const textRect = {
13971        content,
13972        rect,
13973        font: {
13974          family: fontFamily,
13975          size: fontSize
13976        }
13977      };
13978      textRects.push(textRect);
13979    }
13980    return textRects;
13981  }
13982  /**
13983   * Return geometric + logical text layout for one page
13984   * (glyph-only implementation, no FPDFText_GetRect).
13985   *
13986   * @public
13987   */
13988  getPageGeometry(doc, page) {
13989    const label = "getPageGeometry";
13990    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", doc.id);
13991    const ctx = this.cache.getContext(doc.id);
13992    if (!ctx) {
13993      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);
13994      return PdfTaskHelper.reject({
13995        code: PdfErrorCode.DocNotOpen,
13996        message: "document does not open"
13997      });
13998    }
13999    const pageCtx = ctx.acquirePage(page.index);
14000    const textPagePtr = pageCtx.getTextPage();
14001    const glyphCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
14002    const glyphs = [];
14003    for (let i = 0; i < glyphCount; i++) {
14004      const g = this.readGlyphInfo(page, pageCtx.pagePtr, textPagePtr, i);
14005      glyphs.push(g);
14006    }
14007    const runs = this.buildRunsFromGlyphs(glyphs, textPagePtr);
14008    pageCtx.release();
14009    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);
14010    return PdfTaskHelper.resolve({ runs });
14011  }
14012  /**
14013   * Group consecutive glyphs that belong to the same CPDF_TextObject
14014   * using FPDFText_GetTextObject(), and calculate rotation from glyph positions.
14015   */
14016  buildRunsFromGlyphs(glyphs, textPagePtr) {
14017    const runs = [];
14018    let current = null;
14019    let curObjPtr = null;
14020    let bounds = null;
14021    for (let i = 0; i < glyphs.length; i++) {
14022      const g = glyphs[i];
14023      const objPtr = this.pdfiumModule.FPDFText_GetTextObject(textPagePtr, i);
14024      if (objPtr !== curObjPtr) {
14025        curObjPtr = objPtr;
14026        current = {
14027          rect: {
14028            x: g.origin.x,
14029            y: g.origin.y,
14030            width: g.size.width,
14031            height: g.size.height
14032          },
14033          charStart: i,
14034          glyphs: [],
14035          fontSize: this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, i)
14036        };
14037        bounds = {
14038          minX: g.origin.x,
14039          minY: g.origin.y,
14040          maxX: g.origin.x + g.size.width,
14041          maxY: g.origin.y + g.size.height
14042        };
14043        runs.push(current);
14044      }
14045      current.glyphs.push({
14046        x: g.origin.x,
14047        y: g.origin.y,
14048        width: g.size.width,
14049        height: g.size.height,
14050        flags: g.isEmpty ? 2 : g.isSpace ? 1 : 0,
14051        ...g.tightOrigin && { tightX: g.tightOrigin.x, tightY: g.tightOrigin.y },
14052        ...g.tightSize && { tightWidth: g.tightSize.width, tightHeight: g.tightSize.height }
14053      });
14054      if (g.isEmpty) {
14055        continue;
14056      }
14057      const right = g.origin.x + g.size.width;
14058      const bottom = g.origin.y + g.size.height;
14059      bounds.minX = Math.min(bounds.minX, g.origin.x);
14060      bounds.minY = Math.min(bounds.minY, g.origin.y);
14061      bounds.maxX = Math.max(bounds.maxX, right);
14062      bounds.maxY = Math.max(bounds.maxY, bottom);
14063      current.rect.x = bounds.minX;
14064      current.rect.y = bounds.minY;
14065      current.rect.width = bounds.maxX - bounds.minX;
14066      current.rect.height = bounds.maxY - bounds.minY;
14067    }
14068    return runs;
14069  }
14070  /**
14071   * Rich text runs: groups consecutive characters sharing the same
14072   * text object, font, size, and fill color into structured segments
14073   * with full font metadata and bounding boxes in PDF page coordinates.
14074   *
14075   * @public
14076   */
14077  getPageTextRuns(doc, page) {
14078    const label = "getPageTextRuns";
14079    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", doc.id);
14080    const ctx = this.cache.getContext(doc.id);
14081    if (!ctx) {
14082      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);
14083      return PdfTaskHelper.reject({
14084        code: PdfErrorCode.DocNotOpen,
14085        message: "document does not open"
14086      });
14087    }
14088    const pageCtx = ctx.acquirePage(page.index);
14089    const textPagePtr = pageCtx.getTextPage();
14090    const charCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
14091    const runs = [];
14092    let runStart = 0;
14093    let curObjPtr = null;
14094    let curFont = null;
14095    let curFontSize = 0;
14096    let curColor = null;
14097    let bounds = null;
14098    const flushRun = (end) => {
14099      if (curObjPtr === null || curFont === null || curColor === null || bounds === null) return;
14100      const count = end - runStart;
14101      if (count <= 0) return;
14102      const bufPtr = this.memoryManager.malloc(2 * (count + 1));
14103      this.pdfiumModule.FPDFText_GetText(textPagePtr, runStart, count, bufPtr);
14104      const text = stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(bufPtr));
14105      this.memoryManager.free(bufPtr);
14106      runs.push({
14107        text,
14108        rect: {
14109          origin: { x: bounds.minX, y: bounds.minY },
14110          size: {
14111            width: Math.max(1, bounds.maxX - bounds.minX),
14112            height: Math.max(1, bounds.maxY - bounds.minY)
14113          }
14114        },
14115        font: curFont,
14116        fontSize: curFontSize,
14117        color: curColor,
14118        charIndex: runStart,
14119        charCount: count
14120      });
14121    };
14122    const rPtr = this.memoryManager.malloc(4);
14123    const gPtr = this.memoryManager.malloc(4);
14124    const bPtr = this.memoryManager.malloc(4);
14125    const aPtr = this.memoryManager.malloc(4);
14126    const rectPtr = this.memoryManager.malloc(16);
14127    const dx1Ptr = this.memoryManager.malloc(4);
14128    const dy1Ptr = this.memoryManager.malloc(4);
14129    const dx2Ptr = this.memoryManager.malloc(4);
14130    const dy2Ptr = this.memoryManager.malloc(4);
14131    const italicAnglePtr = this.memoryManager.malloc(4);
14132    for (let i = 0; i < charCount; i++) {
14133      const uc = this.pdfiumModule.FPDFText_GetUnicode(textPagePtr, i);
14134      if (uc === 65534 || uc === 65533) continue;
14135      const objPtr = this.pdfiumModule.FPDFText_GetTextObject(textPagePtr, i);
14136      if (objPtr === 0) continue;
14137      const fontSize = this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, i);
14138      this.pdfiumModule.FPDFText_GetFillColor(textPagePtr, i, rPtr, gPtr, bPtr, aPtr);
14139      const red = this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255;
14140      const green = this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255;
14141      const blue = this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255;
14142      const alpha = this.pdfiumModule.pdfium.getValue(aPtr, "i32") & 255;
14143      const fontInfo = this.readFontInfoFromTextObject(objPtr, italicAnglePtr);
14144      const needNewRun = curObjPtr === null || objPtr !== curObjPtr || fontInfo.name !== curFont.name || Math.abs(fontSize - curFontSize) > 0.01 || red !== curColor.red || green !== curColor.green || blue !== curColor.blue;
14145      if (needNewRun) {
14146        flushRun(i);
14147        curObjPtr = objPtr;
14148        curFont = fontInfo;
14149        curFontSize = fontSize;
14150        curColor = { red, green, blue, alpha };
14151        runStart = i;
14152        bounds = null;
14153      }
14154      if (this.pdfiumModule.FPDFText_GetLooseCharBox(textPagePtr, i, rectPtr)) {
14155        const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");
14156        const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");
14157        const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");
14158        const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");
14159        if (left !== right && top !== bottom) {
14160          this.pdfiumModule.FPDF_PageToDevice(
14161            pageCtx.pagePtr,
14162            0,
14163            0,
14164            page.size.width,
14165            page.size.height,
14166            0,
14167            left,
14168            top,
14169            dx1Ptr,
14170            dy1Ptr
14171          );
14172          this.pdfiumModule.FPDF_PageToDevice(
14173            pageCtx.pagePtr,
14174            0,
14175            0,
14176            page.size.width,
14177            page.size.height,
14178            0,
14179            right,
14180            bottom,
14181            dx2Ptr,
14182            dy2Ptr
14183          );
14184          const x1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");
14185          const y1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");
14186          const x2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");
14187          const y2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");
14188          const cx = Math.min(x1, x2);
14189          const cy = Math.min(y1, y2);
14190          const cw = Math.abs(x2 - x1);
14191          const ch = Math.abs(y2 - y1);
14192          if (bounds === null) {
14193            bounds = { minX: cx, minY: cy, maxX: cx + cw, maxY: cy + ch };
14194          } else {
14195            bounds.minX = Math.min(bounds.minX, cx);
14196            bounds.minY = Math.min(bounds.minY, cy);
14197            bounds.maxX = Math.max(bounds.maxX, cx + cw);
14198            bounds.maxY = Math.max(bounds.maxY, cy + ch);
14199          }
14200        }
14201      }
14202    }
14203    flushRun(charCount);
14204    [rPtr, gPtr, bPtr, aPtr, rectPtr, dx1Ptr, dy1Ptr, dx2Ptr, dy2Ptr, italicAnglePtr].forEach(
14205      (p) => this.memoryManager.free(p)
14206    );
14207    pageCtx.release();
14208    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);
14209    return PdfTaskHelper.resolve({ runs });
14210  }
14211  /**
14212   * Read font metadata from a text object handle via FPDFFont_* APIs.
14213   */
14214  readFontInfoFromTextObject(textObjPtr, italicAnglePtr) {
14215    const fontPtr = this.pdfiumModule.FPDFTextObj_GetFont(textObjPtr);
14216    let name = "";
14217    let familyName = "";
14218    let weight = 400;
14219    let italic = false;
14220    let monospaced = false;
14221    let embedded = false;
14222    if (fontPtr) {
14223      const nameLen = this.pdfiumModule.FPDFFont_GetBaseFontName(fontPtr, 0, 0);
14224      if (nameLen > 0) {
14225        const nameBuf = this.memoryManager.malloc(nameLen + 1);
14226        this.pdfiumModule.FPDFFont_GetBaseFontName(fontPtr, nameBuf, nameLen + 1);
14227        name = this.pdfiumModule.pdfium.UTF8ToString(nameBuf);
14228        this.memoryManager.free(nameBuf);
14229      }
14230      const famLen = this.pdfiumModule.FPDFFont_GetFamilyName(fontPtr, 0, 0);
14231      if (famLen > 0) {
14232        const famBuf = this.memoryManager.malloc(famLen + 1);
14233        this.pdfiumModule.FPDFFont_GetFamilyName(fontPtr, famBuf, famLen + 1);
14234        familyName = this.pdfiumModule.pdfium.UTF8ToString(famBuf);
14235        this.memoryManager.free(famBuf);
14236      }
14237      weight = this.pdfiumModule.FPDFFont_GetWeight(fontPtr);
14238      embedded = this.pdfiumModule.FPDFFont_GetIsEmbedded(fontPtr) !== 0;
14239      if (this.pdfiumModule.FPDFFont_GetItalicAngle(fontPtr, italicAnglePtr)) {
14240        const angle = this.pdfiumModule.pdfium.getValue(italicAnglePtr, "i32");
14241        italic = angle !== 0;
14242      }
14243      const flags = this.pdfiumModule.FPDFFont_GetFlags(fontPtr);
14244      monospaced = (flags & 1) !== 0;
14245    }
14246    return { name, familyName, weight, italic, monospaced, embedded };
14247  }
14248  /**
14249   * Extract glyph geometry + metadata for \`charIndex\`
14250   *
14251   * Returns device–space coordinates:
14252   *   x,y  → **top-left** corner (integer-pixels)
14253   *   w,h  → width / height (integer-pixels, ≥ 1)
14254   *
14255   * And two flags:
14256   *   isSpace → true if the glyph's Unicode code-point is U+0020
14257   */
14258  readGlyphInfo(page, pagePtr, textPagePtr, charIndex) {
14259    const dx1Ptr = this.memoryManager.malloc(4);
14260    const dy1Ptr = this.memoryManager.malloc(4);
14261    const dx2Ptr = this.memoryManager.malloc(4);
14262    const dy2Ptr = this.memoryManager.malloc(4);
14263    const rectPtr = this.memoryManager.malloc(16);
14264    const tLeftPtr = this.memoryManager.malloc(8);
14265    const tRightPtr = this.memoryManager.malloc(8);
14266    const tBottomPtr = this.memoryManager.malloc(8);
14267    const tTopPtr = this.memoryManager.malloc(8);
14268    const allPtrs = [
14269      rectPtr,
14270      dx1Ptr,
14271      dy1Ptr,
14272      dx2Ptr,
14273      dy2Ptr,
14274      tLeftPtr,
14275      tRightPtr,
14276      tBottomPtr,
14277      tTopPtr
14278    ];
14279    let x = 0, y = 0, width = 0, height = 0, isSpace = false;
14280    let tightOrigin;
14281    let tightSize;
14282    if (this.pdfiumModule.FPDFText_GetLooseCharBox(textPagePtr, charIndex, rectPtr)) {
14283      const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");
14284      const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");
14285      const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");
14286      const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");
14287      if (left === right || top === bottom) {
14288        allPtrs.forEach((p) => this.memoryManager.free(p));
14289        return {
14290          origin: { x: 0, y: 0 },
14291          size: { width: 0, height: 0 },
14292          isEmpty: true
14293        };
14294      }
14295      this.pdfiumModule.FPDF_PageToDevice(
14296        pagePtr,
14297        0,
14298        0,
14299        page.size.width,
14300        page.size.height,
14301        0,
14302        left,
14303        top,
14304        dx1Ptr,
14305        dy1Ptr
14306      );
14307      this.pdfiumModule.FPDF_PageToDevice(
14308        pagePtr,
14309        0,
14310        0,
14311        page.size.width,
14312        page.size.height,
14313        0,
14314        right,
14315        bottom,
14316        dx2Ptr,
14317        dy2Ptr
14318      );
14319      const x1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");
14320      const y1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");
14321      const x2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");
14322      const y2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");
14323      x = Math.min(x1, x2);
14324      y = Math.min(y1, y2);
14325      width = Math.max(1, Math.abs(x2 - x1));
14326      height = Math.max(1, Math.abs(y2 - y1));
14327      if (this.pdfiumModule.FPDFText_GetCharBox(
14328        textPagePtr,
14329        charIndex,
14330        tLeftPtr,
14331        tRightPtr,
14332        tBottomPtr,
14333        tTopPtr
14334      )) {
14335        const tLeft = this.pdfiumModule.pdfium.getValue(tLeftPtr, "double");
14336        const tRight = this.pdfiumModule.pdfium.getValue(tRightPtr, "double");
14337        const tBottom = this.pdfiumModule.pdfium.getValue(tBottomPtr, "double");
14338        const tTop = this.pdfiumModule.pdfium.getValue(tTopPtr, "double");
14339        this.pdfiumModule.FPDF_PageToDevice(
14340          pagePtr,
14341          0,
14342          0,
14343          page.size.width,
14344          page.size.height,
14345          0,
14346          tLeft,
14347          tTop,
14348          dx1Ptr,
14349          dy1Ptr
14350        );
14351        this.pdfiumModule.FPDF_PageToDevice(
14352          pagePtr,
14353          0,
14354          0,
14355          page.size.width,
14356          page.size.height,
14357          0,
14358          tRight,
14359          tBottom,
14360          dx2Ptr,
14361          dy2Ptr
14362        );
14363        const tx1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");
14364        const ty1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");
14365        const tx2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");
14366        const ty2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");
14367        tightOrigin = { x: Math.min(tx1, tx2), y: Math.min(ty1, ty2) };
14368        tightSize = {
14369          width: Math.max(1, Math.abs(tx2 - tx1)),
14370          height: Math.max(1, Math.abs(ty2 - ty1))
14371        };
14372      }
14373      const uc = this.pdfiumModule.FPDFText_GetUnicode(textPagePtr, charIndex);
14374      isSpace = uc === 32;
14375    }
14376    allPtrs.forEach((p) => this.memoryManager.free(p));
14377    return {
14378      origin: { x, y },
14379      size: { width, height },
14380      ...tightOrigin && { tightOrigin },
14381      ...tightSize && { tightSize },
14382      ...isSpace && { isSpace }
14383    };
14384  }
14385  /**
14386   * Geometry-only text extraction
14387   * ------------------------------------------
14388   * Returns every glyph on the requested page
14389   * in the logical order delivered by PDFium.
14390   *
14391   * The promise resolves to an array of objects:
14392   *   {
14393   *     idx:     number;            // glyph index on the page (0…n-1)
14394   *     origin:  { x: number; y: number };
14395   *     size:    { width: number;  height: number };
14396   *     angle:   number;            // degrees, counter-clock-wise
14397   *     isSpace: boolean;           // true  → U+0020
14398   *   }
14399   *
14400   * No Unicode is included; front-end decides whether to hydrate it.
14401   */
14402  getPageGlyphs(doc, page) {
14403    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", doc, page);
14404    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "Begin", doc.id);
14405    const ctx = this.cache.getContext(doc.id);
14406    if (!ctx) {
14407      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "End", doc.id);
14408      return PdfTaskHelper.reject({
14409        code: PdfErrorCode.DocNotOpen,
14410        message: "document does not open"
14411      });
14412    }
14413    const pageCtx = ctx.acquirePage(page.index);
14414    const textPagePtr = pageCtx.getTextPage();
14415    const total = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
14416    const glyphs = new Array(total);
14417    for (let i = 0; i < total; i++) {
14418      const g = this.readGlyphInfo(page, pageCtx.pagePtr, textPagePtr, i);
14419      if (g.isEmpty) {
14420        continue;
14421      }
14422      glyphs[i] = { ...g };
14423    }
14424    pageCtx.release();
14425    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "End", doc.id);
14426    return PdfTaskHelper.resolve(glyphs);
14427  }
14428  readCharBox(page, pagePtr, textPagePtr, charIndex) {
14429    const topPtr = this.memoryManager.malloc(8);
14430    const leftPtr = this.memoryManager.malloc(8);
14431    const bottomPtr = this.memoryManager.malloc(8);
14432    const rightPtr = this.memoryManager.malloc(8);
14433    let x = 0;
14434    let y = 0;
14435    let width = 0;
14436    let height = 0;
14437    if (this.pdfiumModule.FPDFText_GetCharBox(
14438      textPagePtr,
14439      charIndex,
14440      leftPtr,
14441      rightPtr,
14442      bottomPtr,
14443      topPtr
14444    )) {
14445      const top = this.pdfiumModule.pdfium.getValue(topPtr, "double");
14446      const left = this.pdfiumModule.pdfium.getValue(leftPtr, "double");
14447      const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "double");
14448      const right = this.pdfiumModule.pdfium.getValue(rightPtr, "double");
14449      const deviceXPtr = this.memoryManager.malloc(4);
14450      const deviceYPtr = this.memoryManager.malloc(4);
14451      this.pdfiumModule.FPDF_PageToDevice(
14452        pagePtr,
14453        0,
14454        0,
14455        page.size.width,
14456        page.size.height,
14457        0,
14458        left,
14459        top,
14460        deviceXPtr,
14461        deviceYPtr
14462      );
14463      x = this.pdfiumModule.pdfium.getValue(deviceXPtr, "i32");
14464      y = this.pdfiumModule.pdfium.getValue(deviceYPtr, "i32");
14465      this.memoryManager.free(deviceXPtr);
14466      this.memoryManager.free(deviceYPtr);
14467      width = Math.ceil(Math.abs(right - left));
14468      height = Math.ceil(Math.abs(top - bottom));
14469    }
14470    this.memoryManager.free(topPtr);
14471    this.memoryManager.free(leftPtr);
14472    this.memoryManager.free(bottomPtr);
14473    this.memoryManager.free(rightPtr);
14474    return {
14475      origin: {
14476        x,
14477        y
14478      },
14479      size: {
14480        width,
14481        height
14482      }
14483    };
14484  }
14485  /**
14486   * Read page annotations
14487   *
14488   * @param doc - pdf document object
14489   * @param ctx - document context
14490   * @param page - page info
14491   * @returns annotations on the pdf page
14492   *
14493   * @private
14494   */
14495  readPageAnnotations(doc, ctx, page) {
14496    return ctx.borrowPage(page.index, (pageCtx) => {
14497      return pageCtx.withFormHandle((formHandle) => {
14498        const annotationCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
14499        const annotations = [];
14500        for (let i = 0; i < annotationCount; i++) {
14501          pageCtx.withAnnotation(i, (annotPtr) => {
14502            const anno = this.readPageAnnotation(doc, ctx.docPtr, page, annotPtr, formHandle);
14503            if (anno) annotations.push(anno);
14504          });
14505        }
14506        return annotations;
14507      });
14508    });
14509  }
14510  /**
14511   *
14512   *
14513   * @param ctx - document context
14514   * @param page - page info
14515   * @returns form fields on the pdf page
14516   *
14517   * @private
14518   */
14519  readPageAnnoWidgets(doc, ctx, page) {
14520    return ctx.borrowPage(page.index, (pageCtx) => {
14521      return pageCtx.withFormHandle((formHandle) => {
14522        const annotationCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
14523        const annotations = [];
14524        for (let i = 0; i < annotationCount; i++) {
14525          pageCtx.withAnnotation(i, (annotPtr) => {
14526            const anno = this.readPageAnnoWidget(doc, page, annotPtr, formHandle);
14527            if (anno) annotations.push(anno);
14528          });
14529        }
14530        return annotations;
14531      });
14532    });
14533  }
14534  /**
14535   * Read page annotations
14536   * Read page annotations without loading the page (raw approach)
14537   *
14538   * @param doc - pdf document object
14539   * @param ctx - document context
14540   * @param page - page info
14541   * @returns annotations on the pdf page
14542   *
14543   * @private
14544   */
14545  readPageAnnotationsRaw(doc, ctx, page, formHandle) {
14546    const count = this.pdfiumModule.EPDFPage_GetAnnotCountRaw(ctx.docPtr, page.index);
14547    if (count <= 0) return [];
14548    const out = [];
14549    for (let i = 0; i < count; ++i) {
14550      const annotPtr = this.pdfiumModule.EPDFPage_GetAnnotRaw(ctx.docPtr, page.index, i);
14551      if (!annotPtr) continue;
14552      try {
14553        const anno = this.readPageAnnotation(doc, ctx.docPtr, page, annotPtr, formHandle);
14554        if (anno) out.push(anno);
14555      } finally {
14556        this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
14557      }
14558    }
14559    return out;
14560  }
14561  /**
14562   * Read page form field
14563   *
14564   * @param ctx - document context
14565   * @param page - page info
14566   * @param annotationPtr - pointer to pdf annotation
14567   * @param pageCtx - page context
14568   * @returns form field
14569   *
14570   * @private
14571   */
14572  readPageAnnoWidget(doc, page, annotationPtr, formHandle) {
14573    let index = this.getAnnotString(annotationPtr, "NM");
14574    if (!index || !isUuidV4(index)) {
14575      index = uuidV4();
14576      this.setAnnotString(annotationPtr, "NM", index);
14577    }
14578    const subType = this.pdfiumModule.FPDFAnnot_GetSubtype(
14579      annotationPtr
14580    );
14581    if (subType !== PdfAnnotationSubtype.WIDGET) return;
14582    return this.readPdfWidgetAnno(doc, page, annotationPtr, formHandle, index);
14583  }
14584  /*
14585   * Get page annotations (public API, returns Task)
14586   *
14587   * @param doc - pdf document
14588   * @param page - page info
14589   * @returns task with annotations on the pdf page
14590   *
14591   * @public
14592   */
14593  getPageAnnotationsRaw(doc, page) {
14594    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnotationsRaw", doc, page);
14595    this.logger.perf(
14596      LOG_SOURCE$1,
14597      LOG_CATEGORY$1,
14598      \`GetPageAnnotationsRaw\`,
14599      "Begin",
14600      \`\${doc.id}-\${page.index}\`
14601    );
14602    const ctx = this.cache.getContext(doc.id);
14603    if (!ctx) {
14604      return PdfTaskHelper.reject({
14605        code: PdfErrorCode.DocNotOpen,
14606        message: "document does not open"
14607      });
14608    }
14609    const formInfoPtr = this.pdfiumModule.PDFiumExt_OpenFormFillInfo();
14610    const formHandle = this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(ctx.docPtr, formInfoPtr);
14611    try {
14612      const out = this.readPageAnnotationsRaw(doc, ctx, page, formHandle);
14613      this.logger.perf(
14614        LOG_SOURCE$1,
14615        LOG_CATEGORY$1,
14616        \`GetPageAnnotationsRaw\`,
14617        "End",
14618        \`\${doc.id}-\${page.index}\`
14619      );
14620      this.logger.debug(
14621        LOG_SOURCE$1,
14622        LOG_CATEGORY$1,
14623        "getPageAnnotationsRaw",
14624        \`\${doc.id}-\${page.index}\`,
14625        out
14626      );
14627      return PdfTaskHelper.resolve(out);
14628    } finally {
14629      this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);
14630      this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formInfoPtr);
14631    }
14632  }
14633  /**
14634   * Read pdf annotation from pdf document
14635   *
14636   * @param doc - pdf document object
14637   * @param docPtr - pointer to pdf document
14638   * @param page - page info
14639   * @param annotationPtr - pointer to pdf annotation
14640   * @param formHandle - optional form fill handle for widget annotations
14641   * @returns pdf annotation
14642   *
14643   * @private
14644   */
14645  readPageAnnotation(doc, docPtr, page, annotationPtr, formHandle) {
14646    let index = this.getAnnotString(annotationPtr, "NM");
14647    if (!index || !isUuidV4(index)) {
14648      index = uuidV4();
14649      this.setAnnotString(annotationPtr, "NM", index);
14650    }
14651    const subType = this.pdfiumModule.FPDFAnnot_GetSubtype(
14652      annotationPtr
14653    );
14654    let annotation;
14655    switch (subType) {
14656      case PdfAnnotationSubtype.TEXT:
14657        {
14658          annotation = this.readPdfTextAnno(doc, page, annotationPtr, index);
14659        }
14660        break;
14661      case PdfAnnotationSubtype.FREETEXT:
14662        {
14663          annotation = this.readPdfFreeTextAnno(doc, page, annotationPtr, index);
14664        }
14665        break;
14666      case PdfAnnotationSubtype.LINK:
14667        {
14668          annotation = this.readPdfLinkAnno(doc, page, docPtr, annotationPtr, index);
14669        }
14670        break;
14671      case PdfAnnotationSubtype.WIDGET:
14672        {
14673          if (formHandle !== void 0) {
14674            return this.readPdfWidgetAnno(doc, page, annotationPtr, formHandle, index);
14675          }
14676        }
14677        break;
14678      case PdfAnnotationSubtype.FILEATTACHMENT:
14679        {
14680          annotation = this.readPdfFileAttachmentAnno(doc, page, annotationPtr, index);
14681        }
14682        break;
14683      case PdfAnnotationSubtype.INK:
14684        {
14685          annotation = this.readPdfInkAnno(doc, page, annotationPtr, index);
14686        }
14687        break;
14688      case PdfAnnotationSubtype.POLYGON:
14689        {
14690          annotation = this.readPdfPolygonAnno(doc, page, annotationPtr, index);
14691        }
14692        break;
14693      case PdfAnnotationSubtype.POLYLINE:
14694        {
14695          annotation = this.readPdfPolylineAnno(doc, page, annotationPtr, index);
14696        }
14697        break;
14698      case PdfAnnotationSubtype.LINE:
14699        {
14700          annotation = this.readPdfLineAnno(doc, page, annotationPtr, index);
14701        }
14702        break;
14703      case PdfAnnotationSubtype.HIGHLIGHT:
14704        annotation = this.readPdfHighlightAnno(doc, page, annotationPtr, index);
14705        break;
14706      case PdfAnnotationSubtype.STAMP:
14707        {
14708          annotation = this.readPdfStampAnno(doc, page, annotationPtr, index);
14709        }
14710        break;
14711      case PdfAnnotationSubtype.SQUARE:
14712        {
14713          annotation = this.readPdfSquareAnno(doc, page, annotationPtr, index);
14714        }
14715        break;
14716      case PdfAnnotationSubtype.CIRCLE:
14717        {
14718          annotation = this.readPdfCircleAnno(doc, page, annotationPtr, index);
14719        }
14720        break;
14721      case PdfAnnotationSubtype.UNDERLINE:
14722        {
14723          annotation = this.readPdfUnderlineAnno(doc, page, annotationPtr, index);
14724        }
14725        break;
14726      case PdfAnnotationSubtype.SQUIGGLY:
14727        {
14728          annotation = this.readPdfSquigglyAnno(doc, page, annotationPtr, index);
14729        }
14730        break;
14731      case PdfAnnotationSubtype.STRIKEOUT:
14732        {
14733          annotation = this.readPdfStrikeOutAnno(doc, page, annotationPtr, index);
14734        }
14735        break;
14736      case PdfAnnotationSubtype.CARET:
14737        {
14738          annotation = this.readPdfCaretAnno(doc, page, annotationPtr, index);
14739        }
14740        break;
14741      case PdfAnnotationSubtype.REDACT:
14742        {
14743          annotation = this.readPdfRedactAnno(doc, page, annotationPtr, index);
14744        }
14745        break;
14746      default:
14747        {
14748          annotation = this.readPdfAnno(doc, page, subType, annotationPtr, index);
14749        }
14750        break;
14751    }
14752    if (annotation) {
14753      annotation = this.reverseRotateAnnotationOnLoad(annotation);
14754      const apModes = this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(annotationPtr);
14755      if (apModes) {
14756        annotation.appearanceModes = apModes;
14757      }
14758    }
14759    return annotation;
14760  }
14761  /**
14762   * On load, if a vertex-type annotation has rotation metadata in EPDFCustom,
14763   * reverse-rotate the PDF's physically rotated vertices by -rotation to recover
14764   * the unrotated vertices for runtime editing.
14765   */
14766  reverseRotateAnnotationOnLoad(annotation) {
14767    const rotation = annotation.rotation;
14768    const unrotatedRect = annotation.unrotatedRect;
14769    if (!rotation || rotation === 0 || !unrotatedRect) {
14770      return annotation;
14771    }
14772    const center = {
14773      x: unrotatedRect.origin.x + unrotatedRect.size.width / 2,
14774      y: unrotatedRect.origin.y + unrotatedRect.size.height / 2
14775    };
14776    switch (annotation.type) {
14777      case PdfAnnotationSubtype.INK: {
14778        const ink = annotation;
14779        const unrotatedInkList = ink.inkList.map((stroke) => ({
14780          points: stroke.points.map((p) => this.rotatePointForSave(p, center, -rotation))
14781        }));
14782        return { ...ink, inkList: unrotatedInkList };
14783      }
14784      case PdfAnnotationSubtype.LINE: {
14785        const line = annotation;
14786        return {
14787          ...line,
14788          linePoints: {
14789            start: this.rotatePointForSave(line.linePoints.start, center, -rotation),
14790            end: this.rotatePointForSave(line.linePoints.end, center, -rotation)
14791          }
14792        };
14793      }
14794      case PdfAnnotationSubtype.POLYGON: {
14795        const poly = annotation;
14796        return {
14797          ...poly,
14798          vertices: poly.vertices.map((v) => this.rotatePointForSave(v, center, -rotation))
14799        };
14800      }
14801      case PdfAnnotationSubtype.POLYLINE: {
14802        const polyline = annotation;
14803        return {
14804          ...polyline,
14805          vertices: polyline.vertices.map((v) => this.rotatePointForSave(v, center, -rotation))
14806        };
14807      }
14808      default:
14809        return annotation;
14810    }
14811  }
14812  /**
14813   * Return the colour stored directly in the annotation dictionary's \`/C\` entry.
14814   *
14815   * Most PDFs created by Acrobat, Microsoft Office, LaTeX, etc. include this entry.
14816   * When the key is absent (common in macOS Preview, Chrome, Drawboard) the call
14817   * fails and the function returns \`undefined\`.
14818   *
14819   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
14820   * @returns An RGBA tuple (0-255 channels) or \`undefined\` if no \`/C\` entry exists
14821   *
14822   * @private
14823   */
14824  readAnnotationColor(annotationPtr, colorType = PdfAnnotationColorType.Color) {
14825    const rPtr = this.memoryManager.malloc(4);
14826    const gPtr = this.memoryManager.malloc(4);
14827    const bPtr = this.memoryManager.malloc(4);
14828    const ok = this.pdfiumModule.EPDFAnnot_GetColor(annotationPtr, colorType, rPtr, gPtr, bPtr);
14829    let colour;
14830    if (ok) {
14831      colour = {
14832        red: this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255,
14833        green: this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255,
14834        blue: this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255
14835      };
14836    }
14837    this.memoryManager.free(rPtr);
14838    this.memoryManager.free(gPtr);
14839    this.memoryManager.free(bPtr);
14840    return colour;
14841  }
14842  /**
14843   * Get the fill/stroke colour annotation.
14844   *
14845   * @param annotationPtr - pointer to the annotation whose colour is being set
14846   * @param colorType - which colour to get (0 = fill, 1 = stroke)
14847   * @returns WebColor with hex color
14848   *
14849   * @private
14850   */
14851  getAnnotationColor(annotationPtr, colorType = PdfAnnotationColorType.Color) {
14852    const annotationColor = this.readAnnotationColor(annotationPtr, colorType);
14853    return annotationColor ? pdfColorToWebColor(annotationColor) : void 0;
14854  }
14855  /**
14856   * Set the fill/stroke colour for a **Highlight / Underline / StrikeOut / Squiggly** markup annotation.
14857   *
14858   * @param annotationPtr - pointer to the annotation whose colour is being set
14859   * @param webAlphaColor - WebAlphaColor with hex color and opacity (0-1)
14860   * @param shouldClearAP - whether to clear the /AP entry
14861   * @param which - which colour to set (0 = fill, 1 = stroke)
14862   * @returns \`true\` if the operation was successful
14863   *
14864   * @private
14865   */
14866  setAnnotationColor(annotationPtr, webColor, colorType = PdfAnnotationColorType.Color) {
14867    const pdfColor = webColorToPdfColor(webColor);
14868    return this.pdfiumModule.EPDFAnnot_SetColor(
14869      annotationPtr,
14870      colorType,
14871      pdfColor.red & 255,
14872      pdfColor.green & 255,
14873      pdfColor.blue & 255
14874    );
14875  }
14876  /**
14877   * Get the opacity of the annotation.
14878   *
14879   * @param annotationPtr - pointer to the annotation whose opacity is being set
14880   * @returns opacity (0-1)
14881   *
14882   * @private
14883   */
14884  getAnnotationOpacity(annotationPtr) {
14885    const opacityPtr = this.memoryManager.malloc(4);
14886    const ok = this.pdfiumModule.EPDFAnnot_GetOpacity(annotationPtr, opacityPtr);
14887    const opacity = ok ? this.pdfiumModule.pdfium.getValue(opacityPtr, "i32") : 255;
14888    this.memoryManager.free(opacityPtr);
14889    return pdfAlphaToWebOpacity(opacity);
14890  }
14891  /**
14892   * Set the opacity of the annotation.
14893   *
14894   * @param annotationPtr - pointer to the annotation whose opacity is being set
14895   * @param opacity - opacity (0-1)
14896   * @returns true on success
14897   *
14898   * @private
14899   */
14900  setAnnotationOpacity(annotationPtr, opacity) {
14901    const pdfOpacity = webOpacityToPdfAlpha(opacity);
14902    return this.pdfiumModule.EPDFAnnot_SetOpacity(annotationPtr, pdfOpacity & 255);
14903  }
14904  /**
14905   * Get the rotation angle (in degrees) from the annotation's /Rotate entry.
14906   * Returns 0 if no rotation is set or on error.
14907   *
14908   * @param annotationPtr - pointer to the annotation
14909   * @returns rotation in degrees (0 if not set)
14910   */
14911  getAnnotationRotation(annotationPtr) {
14912    const rotationPtr = this.memoryManager.malloc(4);
14913    const ok = this.pdfiumModule.EPDFAnnot_GetRotate(annotationPtr, rotationPtr);
14914    if (!ok) {
14915      this.memoryManager.free(rotationPtr);
14916      return 0;
14917    }
14918    const rotation = this.pdfiumModule.pdfium.getValue(rotationPtr, "float");
14919    this.memoryManager.free(rotationPtr);
14920    return rotation;
14921  }
14922  /**
14923   * Set the rotation angle (in degrees) on the annotation's /Rotate entry.
14924   * A value of 0 removes the /Rotate key.
14925   *
14926   * @param annotationPtr - pointer to the annotation
14927   * @param rotation - rotation in degrees (clockwise)
14928   * @returns true on success
14929   */
14930  setAnnotationRotation(annotationPtr, rotation) {
14931    return !!this.pdfiumModule.EPDFAnnot_SetRotate(annotationPtr, rotation);
14932  }
14933  /**
14934   * Get the EmbedPDF extended rotation (in degrees) from the annotation's
14935   * /EPDFRotate entry. Returns 0 if not set or on error.
14936   *
14937   * @param annotationPtr - pointer to the annotation
14938   * @returns rotation in degrees (0 if not set)
14939   */
14940  getAnnotExtendedRotation(annotationPtr) {
14941    const rotationPtr = this.memoryManager.malloc(4);
14942    const ok = this.pdfiumModule.EPDFAnnot_GetExtendedRotation(annotationPtr, rotationPtr);
14943    if (!ok) {
14944      this.memoryManager.free(rotationPtr);
14945      return 0;
14946    }
14947    const rotation = this.pdfiumModule.pdfium.getValue(rotationPtr, "float");
14948    this.memoryManager.free(rotationPtr);
14949    return rotation;
14950  }
14951  /**
14952   * Set the EmbedPDF extended rotation (in degrees) on the annotation's
14953   * /EPDFRotate entry. A value of 0 removes the key.
14954   *
14955   * @param annotationPtr - pointer to the annotation
14956   * @param rotation - rotation in degrees
14957   * @returns true on success
14958   */
14959  setAnnotExtendedRotation(annotationPtr, rotation) {
14960    return !!this.pdfiumModule.EPDFAnnot_SetExtendedRotation(annotationPtr, rotation);
14961  }
14962  /**
14963   * Read the EmbedPDF unrotated rect from the annotation's /EPDFUnrotatedRect
14964   * entry. Returns the raw page-space rect (same format as \`readPageAnnoRect\`)
14965   * or null if not set.
14966   *
14967   * @param annotationPtr - pointer to the annotation
14968   * @returns raw \`{ left, top, right, bottom }\` in page coords, or null
14969   */
14970  readAnnotUnrotatedRect(annotationPtr) {
14971    const rectPtr = this.memoryManager.malloc(4 * 4);
14972    const ok = this.pdfiumModule.EPDFAnnot_GetUnrotatedRect(annotationPtr, rectPtr);
14973    if (!ok) {
14974      this.memoryManager.free(rectPtr);
14975      return null;
14976    }
14977    const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");
14978    const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");
14979    const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");
14980    const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");
14981    this.memoryManager.free(rectPtr);
14982    if (left === 0 && top === 0 && right === 0 && bottom === 0) {
14983      return null;
14984    }
14985    return { left, top, right, bottom };
14986  }
14987  /**
14988   * Write the EmbedPDF unrotated rect (/EPDFUnrotatedRect) for an annotation.
14989   * Accepts a device-space \`Rect\` and converts to page coordinates internally,
14990   * following the same pattern as \`setPageAnnoRect\`.
14991   *
14992   * @param doc  - pdf document object
14993   * @param page - pdf page object
14994   * @param annotPtr - pointer to the annotation
14995   * @param rect - device-space rect to store as the unrotated rect
14996   * @returns true on success
14997   */
14998  setAnnotUnrotatedRect(doc, page, annotPtr, rect) {
14999    const x0d = rect.origin.x;
15000    const y0d = rect.origin.y;
15001    const x1d = rect.origin.x + rect.size.width;
15002    const y1d = rect.origin.y + rect.size.height;
15003    const TL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y0d });
15004    const TR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y0d });
15005    const BR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y1d });
15006    const BL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y1d });
15007    let left = Math.min(TL.x, TR.x, BR.x, BL.x);
15008    let right = Math.max(TL.x, TR.x, BR.x, BL.x);
15009    let bottom = Math.min(TL.y, TR.y, BR.y, BL.y);
15010    let top = Math.max(TL.y, TR.y, BR.y, BL.y);
15011    if (left > right) [left, right] = [right, left];
15012    if (bottom > top) [bottom, top] = [top, bottom];
15013    const ptr = this.memoryManager.malloc(16);
15014    const pdf = this.pdfiumModule.pdfium;
15015    pdf.setValue(ptr + 0, left, "float");
15016    pdf.setValue(ptr + 4, top, "float");
15017    pdf.setValue(ptr + 8, right, "float");
15018    pdf.setValue(ptr + 12, bottom, "float");
15019    const ok = this.pdfiumModule.EPDFAnnot_SetUnrotatedRect(annotPtr, ptr);
15020    this.memoryManager.free(ptr);
15021    return !!ok;
15022  }
15023  /**
15024   * Fetch the \`/Q\` text-alignment value from a **FreeText** annotation.
15025   *
15026   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15027   * @returns \`PdfTextAlignment\`
15028   */
15029  getAnnotationTextAlignment(annotationPtr) {
15030    return this.pdfiumModule.EPDFAnnot_GetTextAlignment(annotationPtr);
15031  }
15032  /**
15033   * Write the \`/Q\` text-alignment value into a **FreeText** annotation
15034   * and clear the existing appearance stream so it can be regenerated.
15035   *
15036   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15037   * @param alignment     \`PdfTextAlignment\`
15038   * @returns \`true\` on success
15039   */
15040  setAnnotationTextAlignment(annotationPtr, alignment) {
15041    return !!this.pdfiumModule.EPDFAnnot_SetTextAlignment(annotationPtr, alignment);
15042  }
15043  /**
15044   * Fetch the \`/EPDF:VerticalAlignment\` vertical-alignment value from a **FreeText** annotation.
15045   *
15046   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15047   * @returns \`PdfVerticalAlignment\`
15048   */
15049  getAnnotationVerticalAlignment(annotationPtr) {
15050    return this.pdfiumModule.EPDFAnnot_GetVerticalAlignment(annotationPtr);
15051  }
15052  /**
15053   * Write the \`/EPDF:VerticalAlignment\` vertical-alignment value into a **FreeText** annotation
15054   * and clear the existing appearance stream so it can be regenerated.
15055   *
15056   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15057   * @param alignment     \`PdfVerticalAlignment\`
15058   * @returns \`true\` on success
15059   */
15060  setAnnotationVerticalAlignment(annotationPtr, alignment) {
15061    return !!this.pdfiumModule.EPDFAnnot_SetVerticalAlignment(annotationPtr, alignment);
15062  }
15063  /**
15064   * Get the overlay text from a Redact annotation.
15065   *
15066   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15067   * @returns overlay text string or \`undefined\` if not set
15068   *
15069   * @private
15070   */
15071  getOverlayText(annotationPtr) {
15072    const len = this.pdfiumModule.EPDFAnnot_GetOverlayText(annotationPtr, 0, 0);
15073    if (len === 0) return void 0;
15074    const bytes = (len + 1) * 2;
15075    const ptr = this.memoryManager.malloc(bytes);
15076    this.pdfiumModule.EPDFAnnot_GetOverlayText(annotationPtr, ptr, bytes);
15077    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
15078    this.memoryManager.free(ptr);
15079    return value || void 0;
15080  }
15081  /**
15082   * Set the overlay text on a Redact annotation.
15083   *
15084   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15085   * @param text overlay text to set, or undefined/empty to clear
15086   * @returns \`true\` on success
15087   *
15088   * @private
15089   */
15090  setOverlayText(annotationPtr, text) {
15091    if (!text) {
15092      return this.pdfiumModule.EPDFAnnot_SetOverlayText(annotationPtr, 0);
15093    }
15094    return this.withWString(text, (wPtr) => {
15095      return this.pdfiumModule.EPDFAnnot_SetOverlayText(annotationPtr, wPtr);
15096    });
15097  }
15098  /**
15099   * Get whether overlay text repeats in a Redact annotation.
15100   *
15101   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15102   * @returns \`true\` if overlay text repeats
15103   *
15104   * @private
15105   */
15106  getOverlayTextRepeat(annotationPtr) {
15107    return this.pdfiumModule.EPDFAnnot_GetOverlayTextRepeat(annotationPtr);
15108  }
15109  /**
15110   * Set whether overlay text repeats in a Redact annotation.
15111   *
15112   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15113   * @param repeat whether overlay text should repeat
15114   * @returns \`true\` on success
15115   *
15116   * @private
15117   */
15118  setOverlayTextRepeat(annotationPtr, repeat) {
15119    return this.pdfiumModule.EPDFAnnot_SetOverlayTextRepeat(annotationPtr, repeat);
15120  }
15121  /**
15122   * Return the **default appearance** (font, size, colour) declared in the
15123   * \`/DA\` string of a **FreeText** annotation.
15124   *
15125   * @param annotationPtr  pointer to \`FPDF_ANNOTATION\`
15126   * @returns \`{ font, fontSize, color }\` or \`undefined\` when PDFium returns false
15127   *
15128   * NOTE – \`font\` is the raw \`FPDF_STANDARD_FONT\` enum value that PDFium uses
15129   *        (same range as the C API: 0 = Courier, 12 = ZapfDingbats, …).
15130   */
15131  getAnnotationDefaultAppearance(annotationPtr) {
15132    const fontPtr = this.memoryManager.malloc(4);
15133    const sizePtr = this.memoryManager.malloc(4);
15134    const rPtr = this.memoryManager.malloc(4);
15135    const gPtr = this.memoryManager.malloc(4);
15136    const bPtr = this.memoryManager.malloc(4);
15137    const ok = !!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(
15138      annotationPtr,
15139      fontPtr,
15140      sizePtr,
15141      rPtr,
15142      gPtr,
15143      bPtr
15144    );
15145    if (!ok) {
15146      [fontPtr, sizePtr, rPtr, gPtr, bPtr].forEach((p) => this.memoryManager.free(p));
15147      return;
15148    }
15149    const pdf = this.pdfiumModule.pdfium;
15150    const font = pdf.getValue(fontPtr, "i32");
15151    const fontSize = pdf.getValue(sizePtr, "float");
15152    const red = pdf.getValue(rPtr, "i32") & 255;
15153    const green = pdf.getValue(gPtr, "i32") & 255;
15154    const blue = pdf.getValue(bPtr, "i32") & 255;
15155    [fontPtr, sizePtr, rPtr, gPtr, bPtr].forEach((p) => this.memoryManager.free(p));
15156    return {
15157      fontFamily: font,
15158      fontSize,
15159      fontColor: pdfColorToWebColor({ red, green, blue })
15160    };
15161  }
15162  /**
15163   * Write a **default appearance** (\`/DA\`) into a FreeText annotation.
15164   *
15165   * @param annotationPtr pointer to \`FPDF_ANNOTATION\`
15166   * @param font          \`FPDF_STANDARD_FONT\` enum value
15167   * @param fontSize      size in points (≥ 0)
15168   * @param color         CSS-style \`#rrggbb\` string (alpha ignored)
15169   * @returns \`true\` on success
15170   */
15171  setAnnotationDefaultAppearance(annotationPtr, font, fontSize, color) {
15172    const { red, green, blue } = webColorToPdfColor(color);
15173    return !!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(
15174      annotationPtr,
15175      font,
15176      fontSize,
15177      red & 255,
15178      green & 255,
15179      blue & 255
15180    );
15181  }
15182  /**
15183   * Border‐style + width helper
15184   *
15185   * Tries the new PDFium helper \`EPDFAnnot_GetBorderStyle()\` (patch series
15186   * 9 July 2025).
15187   *
15188   * @param  annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15189   * @returns \`{ ok, style, width }\`
15190   *          • \`ok\`     – \`true\` when the call succeeded
15191   *          • \`style\`  – \`PdfAnnotationBorderStyle\` enum
15192   *          • \`width\`  – stroke-width in points (defaults to 0 pt)
15193   */
15194  getBorderStyle(annotationPtr) {
15195    const widthPtr = this.memoryManager.malloc(4);
15196    let width = 0;
15197    let style = PdfAnnotationBorderStyle.UNKNOWN;
15198    let ok = false;
15199    style = this.pdfiumModule.EPDFAnnot_GetBorderStyle(annotationPtr, widthPtr);
15200    width = this.pdfiumModule.pdfium.getValue(widthPtr, "float");
15201    ok = style !== PdfAnnotationBorderStyle.UNKNOWN;
15202    this.memoryManager.free(widthPtr);
15203    return { ok, style, width };
15204  }
15205  setBorderStyle(annotationPtr, style, width) {
15206    return this.pdfiumModule.EPDFAnnot_SetBorderStyle(annotationPtr, style, width);
15207  }
15208  /**
15209   * Get the /Name entry of the annotation
15210   *
15211   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15212   * @returns \`PdfAnnotationName\`
15213   */
15214  getAnnotationName(annotationPtr) {
15215    return this.pdfiumModule.EPDFAnnot_GetName(annotationPtr);
15216  }
15217  /**
15218   * Set the /Name entry of the annotation
15219   *
15220   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15221   * @param name - \`PdfAnnotationName\`
15222   * @returns \`true\` on success
15223   */
15224  setAnnotationName(annotationPtr, name) {
15225    return this.pdfiumModule.EPDFAnnot_SetName(annotationPtr, name);
15226  }
15227  /**
15228   * Get the reply type of the annotation (RT property per ISO 32000-2)
15229   *
15230   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15231   * @returns \`PdfAnnotationReplyType\`
15232   */
15233  getReplyType(annotationPtr) {
15234    return this.pdfiumModule.EPDFAnnot_GetReplyType(annotationPtr);
15235  }
15236  /**
15237   * Set the reply type of the annotation (RT property per ISO 32000-2)
15238   *
15239   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15240   * @param replyType - \`PdfAnnotationReplyType\`
15241   * @returns \`true\` on success
15242   */
15243  setReplyType(annotationPtr, replyType) {
15244    return this.pdfiumModule.EPDFAnnot_SetReplyType(
15245      annotationPtr,
15246      replyType ?? PdfAnnotationReplyType.Unknown
15247    );
15248  }
15249  /**
15250   * Border-effect (“cloudy”) helper
15251   *
15252   * Calls the new PDFium function \`EPDFAnnot_GetBorderEffect()\` (July 2025).
15253   *
15254   * @param  annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15255   * @returns \`{ ok, intensity }\`
15256   *          • \`ok\`        – \`true\` when the annotation *does* have a
15257   *                          valid cloudy-border effect
15258   *          • \`intensity\` – radius/intensity value (0 when \`ok\` is false)
15259   */
15260  getBorderEffect(annotationPtr) {
15261    const intensityPtr = this.memoryManager.malloc(4);
15262    const ok = !!this.pdfiumModule.EPDFAnnot_GetBorderEffect(annotationPtr, intensityPtr);
15263    const intensity = ok ? this.pdfiumModule.pdfium.getValue(intensityPtr, "float") : 0;
15264    this.memoryManager.free(intensityPtr);
15265    return { ok, intensity };
15266  }
15267  /**
15268   * Rectangle-differences helper ( /RD array on Square / Circle annots )
15269   *
15270   * Calls \`EPDFAnnot_GetRectangleDifferences()\` introduced in July 2025.
15271   *
15272   * @param  annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15273   * @returns \`{ ok, left, top, right, bottom }\`
15274   *          • \`ok\`     – \`true\` when the annotation *has* an /RD entry
15275   *          • the four floats are 0 when \`ok\` is false
15276   *
15277   * Native PDFium exposes /RD as [left, bottom, right, top]. We remap it here
15278   * to the model's stable { left, top, right, bottom } shape.
15279   */
15280  getRectangleDifferences(annotationPtr) {
15281    const lPtr = this.memoryManager.malloc(4);
15282    const bPtr = this.memoryManager.malloc(4);
15283    const rPtr = this.memoryManager.malloc(4);
15284    const tPtr = this.memoryManager.malloc(4);
15285    const ok = !!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(
15286      annotationPtr,
15287      lPtr,
15288      bPtr,
15289      rPtr,
15290      tPtr
15291    );
15292    const pdf = this.pdfiumModule.pdfium;
15293    const left = pdf.getValue(lPtr, "float");
15294    const bottom = pdf.getValue(bPtr, "float");
15295    const right = pdf.getValue(rPtr, "float");
15296    const top = pdf.getValue(tPtr, "float");
15297    this.memoryManager.free(lPtr);
15298    this.memoryManager.free(bPtr);
15299    this.memoryManager.free(rPtr);
15300    this.memoryManager.free(tPtr);
15301    return { ok, left, top, right, bottom };
15302  }
15303  /**
15304   * Sets the /RD array on an annotation.
15305   *
15306   * @param annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15307   * @param rd  the four inset values, or \`undefined\` to clear
15308   * @returns \`true\` on success
15309   */
15310  setRectangleDifferences(annotationPtr, rd) {
15311    if (!rd) {
15312      return this.pdfiumModule.EPDFAnnot_ClearRectangleDifferences(annotationPtr);
15313    }
15314    return this.pdfiumModule.EPDFAnnot_SetRectangleDifferences(
15315      annotationPtr,
15316      rd.left,
15317      rd.bottom,
15318      rd.right,
15319      rd.top
15320    );
15321  }
15322  /**
15323   * Sets or clears the /BE (border effect) dictionary on an annotation.
15324   *
15325   * @param annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15326   * @param intensity  cloudy border intensity, or \`undefined\` to clear
15327   * @returns \`true\` on success
15328   */
15329  setBorderEffect(annotationPtr, intensity) {
15330    if (intensity === void 0 || intensity <= 0) {
15331      return this.pdfiumModule.EPDFAnnot_ClearBorderEffect(annotationPtr);
15332    }
15333    return this.pdfiumModule.EPDFAnnot_SetBorderEffect(annotationPtr, intensity);
15334  }
15335  /**
15336   * Get the date of the annotation
15337   *
15338   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15339   * @param key - 'M' for modified date, 'CreationDate' for creation date
15340   * @returns \`Date\` or \`undefined\` when PDFium can't read the date
15341   */
15342  getAnnotationDate(annotationPtr, key) {
15343    const raw = this.getAnnotString(annotationPtr, key);
15344    return raw ? pdfDateToDate(raw) : void 0;
15345  }
15346  /**
15347   * Set the date of the annotation
15348   *
15349   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15350   * @param key - 'M' for modified date, 'CreationDate' for creation date
15351   * @param date - \`Date\` to set
15352   * @returns \`true\` on success
15353   */
15354  setAnnotationDate(annotationPtr, key, date) {
15355    const raw = dateToPdfDate(date);
15356    return this.setAnnotString(annotationPtr, key, raw);
15357  }
15358  /**
15359   * Get the date of the attachment
15360   *
15361   * @param attachmentPtr - pointer to an \`FPDF_ATTACHMENT\`
15362   * @param key - 'ModDate' for modified date, 'CreationDate' for creation date
15363   * @returns \`Date\` or \`undefined\` when PDFium can't read the date
15364   */
15365  getAttachmentDate(attachmentPtr, key) {
15366    const raw = this.getAttachmentString(attachmentPtr, key);
15367    return raw ? pdfDateToDate(raw) : void 0;
15368  }
15369  /**
15370   * Set the date of the attachment
15371   *
15372   * @param attachmentPtr - pointer to an \`FPDF_ATTACHMENT\`
15373   * @param key - 'ModDate' for modified date, 'CreationDate' for creation date
15374   * @param date - \`Date\` to set
15375   * @returns \`true\` on success
15376   */
15377  setAttachmentDate(attachmentPtr, key, date) {
15378    const raw = dateToPdfDate(date);
15379    return this.setAttachmentString(attachmentPtr, key, raw);
15380  }
15381  /**
15382   * Dash-pattern helper ( /BS → /D array, dashed borders only )
15383   *
15384   * Uses the two new PDFium helpers:
15385   *   • \`EPDFAnnot_GetBorderDashPatternCount\`
15386   *   • \`EPDFAnnot_GetBorderDashPattern\`
15387   *
15388   * @param  annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15389   * @returns \`{ ok, pattern }\`
15390   *          • \`ok\`       – \`true\` when the annot is dashed *and* the array
15391   *                          was retrieved successfully
15392   *          • \`pattern\`  – numeric array of dash/space lengths (empty when \`ok\` is false)
15393   */
15394  getBorderDashPattern(annotationPtr) {
15395    const count = this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(annotationPtr);
15396    if (count === 0) {
15397      return { ok: false, pattern: [] };
15398    }
15399    const arrPtr = this.memoryManager.malloc(4 * count);
15400    const okNative = !!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(
15401      annotationPtr,
15402      arrPtr,
15403      count
15404    );
15405    const pattern = [];
15406    if (okNative) {
15407      const pdf = this.pdfiumModule.pdfium;
15408      for (let i = 0; i < count; i++) {
15409        pattern.push(pdf.getValue(arrPtr + 4 * i, "float"));
15410      }
15411    }
15412    this.memoryManager.free(arrPtr);
15413    return { ok: okNative, pattern };
15414  }
15415  /**
15416   * Write the /BS /D dash pattern array for an annotation border.
15417   *
15418   * @param annotationPtr Pointer to FPDF_ANNOTATION
15419   * @param pattern       Array of dash/space lengths in *points* (e.g. [3, 2])
15420   *                      Empty array clears the pattern (solid line).
15421   * @returns true on success
15422   *
15423   * @private
15424   */
15425  setBorderDashPattern(annotationPtr, pattern) {
15426    if (!pattern || pattern.length === 0) {
15427      return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(annotationPtr, 0, 0);
15428    }
15429    const clean = pattern.map((n) => Number.isFinite(n) && n > 0 ? n : 0).filter((n) => n > 0);
15430    if (clean.length === 0) {
15431      return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(annotationPtr, 0, 0);
15432    }
15433    const bytes = 4 * clean.length;
15434    const bufPtr = this.memoryManager.malloc(bytes);
15435    for (let i = 0; i < clean.length; i++) {
15436      this.pdfiumModule.pdfium.setValue(bufPtr + 4 * i, clean[i], "float");
15437    }
15438    const ok = !!this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(
15439      annotationPtr,
15440      bufPtr,
15441      clean.length
15442    );
15443    this.memoryManager.free(bufPtr);
15444    return ok;
15445  }
15446  /**
15447   * Return the \`/LE\` array (start/end line-ending styles) for a LINE / POLYLINE annot.
15448   *
15449   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15450   * @returns \`{ start, end }\` or \`undefined\` when PDFium can't read them
15451   *
15452   * @private
15453   */
15454  getLineEndings(annotationPtr) {
15455    const startPtr = this.memoryManager.malloc(4);
15456    const endPtr = this.memoryManager.malloc(4);
15457    const ok = !!this.pdfiumModule.EPDFAnnot_GetLineEndings(annotationPtr, startPtr, endPtr);
15458    if (!ok) {
15459      this.memoryManager.free(startPtr);
15460      this.memoryManager.free(endPtr);
15461      return void 0;
15462    }
15463    const start = this.pdfiumModule.pdfium.getValue(startPtr, "i32");
15464    const end = this.pdfiumModule.pdfium.getValue(endPtr, "i32");
15465    this.memoryManager.free(startPtr);
15466    this.memoryManager.free(endPtr);
15467    return { start, end };
15468  }
15469  /**
15470   * Write the \`/LE\` array (start/end line-ending styles) for a LINE / POLYLINE annot.
15471   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15472   * @param start - start line ending style
15473   * @param end - end line ending style
15474   * @returns \`true\` on success
15475   */
15476  setLineEndings(annotationPtr, start, end) {
15477    return !!this.pdfiumModule.EPDFAnnot_SetLineEndings(annotationPtr, start, end);
15478  }
15479  /**
15480   * Get the start and end points of a LINE / POLYLINE annot.
15481   * @param doc - pdf document object
15482   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15483   * @param page - logical page info object (\`PdfPageObject\`)
15484   * @returns \`{ start, end }\` or \`undefined\` when PDFium can't read them
15485   */
15486  getLinePoints(doc, page, annotationPtr) {
15487    const startPtr = this.memoryManager.malloc(8);
15488    const endPtr = this.memoryManager.malloc(8);
15489    const ok = this.pdfiumModule.FPDFAnnot_GetLine(annotationPtr, startPtr, endPtr);
15490    if (!ok) {
15491      this.memoryManager.free(startPtr);
15492      this.memoryManager.free(endPtr);
15493      return void 0;
15494    }
15495    const pdf = this.pdfiumModule.pdfium;
15496    const sx = pdf.getValue(startPtr + 0, "float");
15497    const sy = pdf.getValue(startPtr + 4, "float");
15498    const ex = pdf.getValue(endPtr + 0, "float");
15499    const ey = pdf.getValue(endPtr + 4, "float");
15500    this.memoryManager.free(startPtr);
15501    this.memoryManager.free(endPtr);
15502    const start = this.convertPagePointToDevicePoint(doc, page, { x: sx, y: sy });
15503    const end = this.convertPagePointToDevicePoint(doc, page, { x: ex, y: ey });
15504    return { start, end };
15505  }
15506  /**
15507   * Set the two end‑points of a **Line** annotation
15508   * by writing a new /L array \`[ x1 y1 x2 y2 ]\`.
15509   * @param doc - pdf document object
15510   * @param page - logical page info object (\`PdfPageObject\`)
15511   * @param annotPtr - pointer to the annotation whose line points are needed
15512   * @param start - start point
15513   * @param end - end point
15514   * @returns true on success
15515   */
15516  setLinePoints(doc, page, annotPtr, start, end) {
15517    const p1 = this.convertDevicePointToPagePoint(doc, page, start);
15518    const p2 = this.convertDevicePointToPagePoint(doc, page, end);
15519    if (!p1 || !p2) return false;
15520    const buf = this.memoryManager.malloc(16);
15521    const pdf = this.pdfiumModule.pdfium;
15522    pdf.setValue(buf + 0, p1.x, "float");
15523    pdf.setValue(buf + 4, p1.y, "float");
15524    pdf.setValue(buf + 8, p2.x, "float");
15525    pdf.setValue(buf + 12, p2.y, "float");
15526    const ok = this.pdfiumModule.EPDFAnnot_SetLine(annotPtr, buf, buf + 8);
15527    this.memoryManager.free(buf);
15528    return !!ok;
15529  }
15530  /**
15531   * Read \`/QuadPoints\` from any annotation and convert each quadrilateral to
15532   * device-space coordinates.
15533   *
15534   * The four points are returned in natural reading order:
15535   *   \`p1 → p2\` (top edge) and \`p4 → p3\` (bottom edge).
15536   * This preserves the true shape for rotated / skewed text, whereas callers
15537   * that only need axis-aligned boxes can collapse each quad themselves.
15538   *
15539   * @param doc           - pdf document object
15540   * @param page          - logical page info object (\`PdfPageObject\`)
15541   * @param annotationPtr - pointer to the annotation whose quads are needed
15542   * @returns Array of \`Rect\` objects (\`[]\` if the annotation has no quads)
15543   *
15544   * @private
15545   */
15546  getQuadPointsAnno(doc, page, annotationPtr) {
15547    const quadCount = this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(annotationPtr);
15548    if (quadCount === 0) return [];
15549    const FS_QUADPOINTSF_SIZE = 8 * 4;
15550    const quads = [];
15551    for (let qi = 0; qi < quadCount; qi++) {
15552      const quadPtr = this.memoryManager.malloc(FS_QUADPOINTSF_SIZE);
15553      const ok = this.pdfiumModule.FPDFAnnot_GetAttachmentPoints(annotationPtr, qi, quadPtr);
15554      if (ok) {
15555        const xs = [];
15556        const ys = [];
15557        for (let i = 0; i < 4; i++) {
15558          const base = quadPtr + i * 8;
15559          xs.push(this.pdfiumModule.pdfium.getValue(base, "float"));
15560          ys.push(this.pdfiumModule.pdfium.getValue(base + 4, "float"));
15561        }
15562        const p1 = this.convertPagePointToDevicePoint(doc, page, { x: xs[0], y: ys[0] });
15563        const p2 = this.convertPagePointToDevicePoint(doc, page, { x: xs[1], y: ys[1] });
15564        const p3 = this.convertPagePointToDevicePoint(doc, page, { x: xs[2], y: ys[2] });
15565        const p4 = this.convertPagePointToDevicePoint(doc, page, { x: xs[3], y: ys[3] });
15566        quads.push({ p1, p2, p3, p4 });
15567      }
15568      this.memoryManager.free(quadPtr);
15569    }
15570    return quads.map(quadToRect);
15571  }
15572  /**
15573   * Set the quadrilaterals for a **Highlight / Underline / StrikeOut / Squiggly** markup annotation.
15574   *
15575   * @param doc           - pdf document object
15576   * @param page          - logical page info object (\`PdfPageObject\`)
15577   * @param annotationPtr - pointer to the annotation whose quads are needed
15578   * @param rects         - array of \`Rect\` objects (\`[]\` if the annotation has no quads)
15579   * @returns \`true\` if the operation was successful
15580   *
15581   * @private
15582   */
15583  syncQuadPointsAnno(doc, page, annotPtr, rects) {
15584    const FS_QUADPOINTSF_SIZE = 8 * 4;
15585    const pdf = this.pdfiumModule.pdfium;
15586    const count = this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(annotPtr);
15587    const buf = this.memoryManager.malloc(FS_QUADPOINTSF_SIZE);
15588    const writeQuad = (r) => {
15589      const q = rectToQuad(r);
15590      const p1 = this.convertDevicePointToPagePoint(doc, page, q.p1);
15591      const p2 = this.convertDevicePointToPagePoint(doc, page, q.p2);
15592      const p3 = this.convertDevicePointToPagePoint(doc, page, q.p3);
15593      const p4 = this.convertDevicePointToPagePoint(doc, page, q.p4);
15594      pdf.setValue(buf + 0, p1.x, "float");
15595      pdf.setValue(buf + 4, p1.y, "float");
15596      pdf.setValue(buf + 8, p2.x, "float");
15597      pdf.setValue(buf + 12, p2.y, "float");
15598      pdf.setValue(buf + 16, p4.x, "float");
15599      pdf.setValue(buf + 20, p4.y, "float");
15600      pdf.setValue(buf + 24, p3.x, "float");
15601      pdf.setValue(buf + 28, p3.y, "float");
15602    };
15603    const min = Math.min(count, rects.length);
15604    for (let i = 0; i < min; i++) {
15605      writeQuad(rects[i]);
15606      if (!this.pdfiumModule.FPDFAnnot_SetAttachmentPoints(annotPtr, i, buf)) {
15607        this.memoryManager.free(buf);
15608        return false;
15609      }
15610    }
15611    for (let i = count; i < rects.length; i++) {
15612      writeQuad(rects[i]);
15613      if (!this.pdfiumModule.FPDFAnnot_AppendAttachmentPoints(annotPtr, buf)) {
15614        this.memoryManager.free(buf);
15615        return false;
15616      }
15617    }
15618    this.memoryManager.free(buf);
15619    return true;
15620  }
15621  /**
15622   * Redact text that intersects ANY of the provided **quads** (device-space).
15623   * Returns \`true\` if the page changed. Always regenerates the page stream.
15624   */
15625  redactTextInRects(doc, page, rects, options) {
15626    const { recurseForms = true, drawBlackBoxes = false } = options ?? {};
15627    this.logger.debug(
15628      "PDFiumEngine",
15629      "Engine",
15630      "redactTextInQuads",
15631      doc.id,
15632      page.index,
15633      rects.length
15634    );
15635    const label = "RedactTextInQuads";
15636    this.logger.perf("PDFiumEngine", "Engine", label, "Begin", \`\${doc.id}-\${page.index}\`);
15637    const ctx = this.cache.getContext(doc.id);
15638    if (!ctx) {
15639      this.logger.perf("PDFiumEngine", "Engine", label, "End", \`\${doc.id}-\${page.index}\`);
15640      return PdfTaskHelper.reject({
15641        code: PdfErrorCode.DocNotOpen,
15642        message: "document does not open"
15643      });
15644    }
15645    const clean = (rects ?? []).filter(
15646      (r) => {
15647        var _a, _b, _c, _d;
15648        return r && Number.isFinite((_a = r.origin) == null ? void 0 : _a.x) && Number.isFinite((_b = r.origin) == null ? void 0 : _b.y) && Number.isFinite((_c = r.size) == null ? void 0 : _c.width) && Number.isFinite((_d = r.size) == null ? void 0 : _d.height) && r.size.width > 0 && r.size.height > 0;
15649      }
15650    );
15651    if (clean.length === 0) {
15652      this.logger.perf("PDFiumEngine", "Engine", label, "End", \`\${doc.id}-\${page.index}\`);
15653      return PdfTaskHelper.resolve(false);
15654    }
15655    const pageCtx = ctx.acquirePage(page.index);
15656    const { ptr, count } = this.allocFSQuadsBufferFromRects(doc, page, clean);
15657    let ok = false;
15658    try {
15659      ok = !!this.pdfiumModule.EPDFText_RedactInQuads(
15660        pageCtx.pagePtr,
15661        ptr,
15662        count,
15663        recurseForms ? true : false,
15664        false
15665      );
15666    } finally {
15667      this.memoryManager.free(ptr);
15668    }
15669    if (ok) {
15670      ok = !!this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
15671    }
15672    pageCtx.disposeImmediate();
15673    this.logger.perf("PDFiumEngine", "Engine", label, "End", \`\${doc.id}-\${page.index}\`);
15674    return PdfTaskHelper.resolve(!!ok);
15675  }
15676  /**
15677   * Apply a single redaction annotation, permanently removing content underneath
15678   * and flattening the RO (Redact Overlay) appearance stream if present.
15679   * The annotation is removed after successful application.
15680   *
15681   * @param doc - document object
15682   * @param page - page object
15683   * @param annotation - the redact annotation to apply
15684   * @returns true if successful
15685   */
15686  applyRedaction(doc, page, annotation) {
15687    this.logger.debug(
15688      LOG_SOURCE$1,
15689      LOG_CATEGORY$1,
15690      "applyRedaction",
15691      doc.id,
15692      page.index,
15693      annotation.id
15694    );
15695    const label = "ApplyRedaction";
15696    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15697    const ctx = this.cache.getContext(doc.id);
15698    if (!ctx) {
15699      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15700      return PdfTaskHelper.reject({
15701        code: PdfErrorCode.DocNotOpen,
15702        message: "document does not open"
15703      });
15704    }
15705    const pageCtx = ctx.acquirePage(page.index);
15706    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
15707    if (!annotPtr) {
15708      pageCtx.release();
15709      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15710      return PdfTaskHelper.reject({
15711        code: PdfErrorCode.NotFound,
15712        message: "annotation not found"
15713      });
15714    }
15715    const ok = this.pdfiumModule.EPDFAnnot_ApplyRedaction(pageCtx.pagePtr, annotPtr);
15716    this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
15717    if (ok) {
15718      this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
15719    }
15720    pageCtx.disposeImmediate();
15721    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15722    return PdfTaskHelper.resolve(!!ok);
15723  }
15724  /**
15725   * Apply all redaction annotations on a page, permanently removing content
15726   * underneath each one and flattening RO streams if present.
15727   * All redact annotations are removed after successful application.
15728   *
15729   * @param doc - document object
15730   * @param page - page object
15731   * @returns true if any redactions were applied
15732   */
15733  applyAllRedactions(doc, page) {
15734    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "applyAllRedactions", doc.id, page.index);
15735    const label = "ApplyAllRedactions";
15736    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15737    const ctx = this.cache.getContext(doc.id);
15738    if (!ctx) {
15739      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15740      return PdfTaskHelper.reject({
15741        code: PdfErrorCode.DocNotOpen,
15742        message: "document does not open"
15743      });
15744    }
15745    const pageCtx = ctx.acquirePage(page.index);
15746    const ok = this.pdfiumModule.EPDFPage_ApplyRedactions(pageCtx.pagePtr);
15747    if (ok) {
15748      this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
15749    }
15750    pageCtx.disposeImmediate();
15751    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15752    return PdfTaskHelper.resolve(!!ok);
15753  }
15754  /**
15755   * Flatten an annotation's appearance (AP/N) to page content.
15756   * The annotation's visual appearance becomes part of the page itself.
15757   * The annotation is automatically removed after flattening.
15758   *
15759   * @param doc - document object
15760   * @param page - page object
15761   * @param annotation - the annotation to flatten
15762   * @returns true if successful
15763   */
15764  flattenAnnotation(doc, page, annotation) {
15765    this.logger.debug(
15766      LOG_SOURCE$1,
15767      LOG_CATEGORY$1,
15768      "flattenAnnotation",
15769      doc.id,
15770      page.index,
15771      annotation.id
15772    );
15773    const label = "FlattenAnnotation";
15774    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15775    const ctx = this.cache.getContext(doc.id);
15776    if (!ctx) {
15777      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15778      return PdfTaskHelper.reject({
15779        code: PdfErrorCode.DocNotOpen,
15780        message: "document does not open"
15781      });
15782    }
15783    const pageCtx = ctx.acquirePage(page.index);
15784    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
15785    if (!annotPtr) {
15786      pageCtx.release();
15787      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15788      return PdfTaskHelper.reject({
15789        code: PdfErrorCode.NotFound,
15790        message: "annotation not found"
15791      });
15792    }
15793    const ok = this.pdfiumModule.EPDFAnnot_Flatten(pageCtx.pagePtr, annotPtr);
15794    this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
15795    if (ok) {
15796      this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
15797    }
15798    pageCtx.disposeImmediate();
15799    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15800    return PdfTaskHelper.resolve(!!ok);
15801  }
15802  /**
15803   * Export an annotation's appearance as a standalone single-page PDF.
15804   *
15805   * @param doc - document object
15806   * @param page - page object
15807   * @param annotation - the annotation to export
15808   * @returns a PDF buffer containing the annotation appearance
15809   */
15810  exportAnnotationAppearanceAsPdf(doc, page, annotation) {
15811    this.logger.debug(
15812      LOG_SOURCE$1,
15813      LOG_CATEGORY$1,
15814      "exportAnnotationAppearanceAsPdf",
15815      doc.id,
15816      page.index,
15817      annotation.id
15818    );
15819    const label = "ExportAnnotationAppearanceAsPdf";
15820    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15821    const ctx = this.cache.getContext(doc.id);
15822    if (!ctx) {
15823      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15824      return PdfTaskHelper.reject({
15825        code: PdfErrorCode.DocNotOpen,
15826        message: "document does not open"
15827      });
15828    }
15829    const pageCtx = ctx.acquirePage(page.index);
15830    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
15831    if (!annotPtr) {
15832      pageCtx.release();
15833      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15834      return PdfTaskHelper.reject({
15835        code: PdfErrorCode.NotFound,
15836        message: "annotation not found"
15837      });
15838    }
15839    const exportedDocPtr = this.pdfiumModule.EPDFAnnot_ExportAppearanceAsDocument(annotPtr);
15840    this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
15841    if (!exportedDocPtr) {
15842      pageCtx.release();
15843      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15844      return PdfTaskHelper.reject({
15845        code: PdfErrorCode.CantCreateNewDoc,
15846        message: "can not export annotation as pdf"
15847      });
15848    }
15849    try {
15850      return PdfTaskHelper.resolve(this.saveDocument(exportedDocPtr));
15851    } finally {
15852      this.pdfiumModule.FPDF_CloseDocument(exportedDocPtr);
15853      pageCtx.release();
15854      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15855    }
15856  }
15857  /**
15858   * Export multiple annotations' appearances as a standalone single-page PDF.
15859   * All annotations must be on the same page. The resulting page is sized to
15860   * the union of all annotation rects, with each appearance positioned correctly.
15861   *
15862   * @param doc - document object
15863   * @param page - page object
15864   * @param annotations - the annotations to export
15865   * @returns a PDF buffer containing the combined appearances
15866   */
15867  exportAnnotationsAppearanceAsPdf(doc, page, annotations) {
15868    this.logger.debug(
15869      LOG_SOURCE$1,
15870      LOG_CATEGORY$1,
15871      "exportAnnotationsAppearanceAsPdf",
15872      doc.id,
15873      page.index,
15874      annotations.map((a) => a.id)
15875    );
15876    const label = "ExportAnnotationsAppearanceAsPdf";
15877    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15878    const ctx = this.cache.getContext(doc.id);
15879    if (!ctx) {
15880      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15881      return PdfTaskHelper.reject({
15882        code: PdfErrorCode.DocNotOpen,
15883        message: "document does not open"
15884      });
15885    }
15886    if (annotations.length === 0) {
15887      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15888      return PdfTaskHelper.reject({
15889        code: PdfErrorCode.NotFound,
15890        message: "no annotations provided"
15891      });
15892    }
15893    const pageCtx = ctx.acquirePage(page.index);
15894    const annotPtrs = [];
15895    for (const annotation of annotations) {
15896      const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
15897      if (!annotPtr) {
15898        for (const ptr of annotPtrs) {
15899          this.pdfiumModule.FPDFPage_CloseAnnot(ptr);
15900        }
15901        pageCtx.release();
15902        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15903        return PdfTaskHelper.reject({
15904          code: PdfErrorCode.NotFound,
15905          message: \`annotation not found: \${annotation.id}\`
15906        });
15907      }
15908      annotPtrs.push(annotPtr);
15909    }
15910    const ptrArraySize = annotPtrs.length * 4;
15911    const ptrArrayPtr = this.memoryManager.malloc(ptrArraySize);
15912    for (let i = 0; i < annotPtrs.length; i++) {
15913      this.pdfiumModule.pdfium.setValue(ptrArrayPtr + i * 4, annotPtrs[i], "i32");
15914    }
15915    const exportedDocPtr = this.pdfiumModule.EPDFAnnot_ExportMultipleAppearancesAsDocument(
15916      ptrArrayPtr,
15917      annotPtrs.length
15918    );
15919    this.memoryManager.free(ptrArrayPtr);
15920    for (const ptr of annotPtrs) {
15921      this.pdfiumModule.FPDFPage_CloseAnnot(ptr);
15922    }
15923    if (!exportedDocPtr) {
15924      pageCtx.release();
15925      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15926      return PdfTaskHelper.reject({
15927        code: PdfErrorCode.CantCreateNewDoc,
15928        message: "can not export annotations as pdf"
15929      });
15930    }
15931    try {
15932      return PdfTaskHelper.resolve(this.saveDocument(exportedDocPtr));
15933    } finally {
15934      this.pdfiumModule.FPDF_CloseDocument(exportedDocPtr);
15935      pageCtx.release();
15936      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15937    }
15938  }
15939  /** Pack device-space Rects into an FS_QUADPOINTSF[] buffer (page space). */
15940  allocFSQuadsBufferFromRects(doc, page, rects) {
15941    const STRIDE = 32;
15942    const count = rects.length;
15943    const ptr = this.memoryManager.malloc(STRIDE * count);
15944    const pdf = this.pdfiumModule.pdfium;
15945    for (let i = 0; i < count; i++) {
15946      const r = rects[i];
15947      const q = rectToQuad(r);
15948      const p1 = this.convertDevicePointToPagePoint(doc, page, q.p1);
15949      const p2 = this.convertDevicePointToPagePoint(doc, page, q.p2);
15950      const p3 = this.convertDevicePointToPagePoint(doc, page, q.p3);
15951      const p4 = this.convertDevicePointToPagePoint(doc, page, q.p4);
15952      const base = ptr + i * STRIDE;
15953      pdf.setValue(base + 0, p1.x, "float");
15954      pdf.setValue(base + 4, p1.y, "float");
15955      pdf.setValue(base + 8, p2.x, "float");
15956      pdf.setValue(base + 12, p2.y, "float");
15957      pdf.setValue(base + 16, p4.x, "float");
15958      pdf.setValue(base + 20, p4.y, "float");
15959      pdf.setValue(base + 24, p3.x, "float");
15960      pdf.setValue(base + 28, p3.y, "float");
15961    }
15962    return { ptr, count };
15963  }
15964  /**
15965   * Read ink list from annotation
15966   * @param doc - pdf document object
15967   * @param page  - logical page info object (\`PdfPageObject\`)
15968   * @param pagePtr - pointer to the page
15969   * @param annotationPtr - pointer to the annotation whose ink list is needed
15970   * @returns ink list
15971   */
15972  getInkList(doc, page, annotationPtr) {
15973    const inkList = [];
15974    const pathCount = this.pdfiumModule.FPDFAnnot_GetInkListCount(annotationPtr);
15975    if (pathCount <= 0) return inkList;
15976    const pdf = this.pdfiumModule.pdfium;
15977    const POINT_STRIDE = 8;
15978    for (let i = 0; i < pathCount; i++) {
15979      const points = [];
15980      const n = this.pdfiumModule.FPDFAnnot_GetInkListPath(annotationPtr, i, 0, 0);
15981      if (n > 0) {
15982        const buf = this.memoryManager.malloc(n * POINT_STRIDE);
15983        this.pdfiumModule.FPDFAnnot_GetInkListPath(annotationPtr, i, buf, n);
15984        for (let j = 0; j < n; j++) {
15985          const base = buf + j * POINT_STRIDE;
15986          const px = pdf.getValue(base + 0, "float");
15987          const py = pdf.getValue(base + 4, "float");
15988          const d = this.convertPagePointToDevicePoint(doc, page, { x: px, y: py });
15989          points.push({ x: d.x, y: d.y });
15990        }
15991        this.memoryManager.free(buf);
15992      }
15993      inkList.push({ points });
15994    }
15995    return inkList;
15996  }
15997  /**
15998   * Add ink list to annotation
15999   * @param doc - pdf document object
16000   * @param page  - logical page info object (\`PdfPageObject\`)
16001   * @param pagePtr - pointer to the page
16002   * @param annotationPtr - pointer to the annotation whose ink list is needed
16003   * @param inkList - ink list array of \`PdfInkListObject\`
16004   * @returns \`true\` if the operation was successful
16005   */
16006  setInkList(doc, page, annotationPtr, inkList) {
16007    const pdf = this.pdfiumModule.pdfium;
16008    const POINT_STRIDE = 8;
16009    for (const stroke of inkList) {
16010      const n = stroke.points.length;
16011      if (n === 0) continue;
16012      const buf = this.memoryManager.malloc(n * POINT_STRIDE);
16013      for (let i = 0; i < n; i++) {
16014        const pDev = stroke.points[i];
16015        const pPage = this.convertDevicePointToPagePoint(doc, page, pDev);
16016        pdf.setValue(buf + i * POINT_STRIDE + 0, pPage.x, "float");
16017        pdf.setValue(buf + i * POINT_STRIDE + 4, pPage.y, "float");
16018      }
16019      const idx = this.pdfiumModule.FPDFAnnot_AddInkStroke(annotationPtr, buf, n);
16020      this.memoryManager.free(buf);
16021      if (idx === -1) {
16022        return false;
16023      }
16024    }
16025    return true;
16026  }
16027  /**
16028   * Read pdf text annotation
16029   * @param page  - pdf page infor
16030   * @param annotationPtr - pointer to pdf annotation
16031   * @param index  - index of annotation in the pdf page
16032   * @returns pdf text annotation
16033   *
16034   * @private
16035   */
16036  readPdfTextAnno(doc, page, annotationPtr, index) {
16037    const annoRect = this.readPageAnnoRect(annotationPtr);
16038    const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);
16039    const state = this.getAnnotString(annotationPtr, "State");
16040    const stateModel = this.getAnnotString(annotationPtr, "StateModel");
16041    const color = this.getAnnotationColor(annotationPtr);
16042    const opacity = this.getAnnotationOpacity(annotationPtr);
16043    const name = this.getAnnotationName(annotationPtr);
16044    return {
16045      pageIndex: page.index,
16046      id: index,
16047      type: PdfAnnotationSubtype.TEXT,
16048      rect,
16049      strokeColor: color ?? "#FFFF00",
16050      color: color ?? "#FFFF00",
16051      opacity,
16052      state,
16053      stateModel,
16054      name,
16055      icon: name,
16056      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16057    };
16058  }
16059  /**
16060   * Read pdf freetext annotation
16061   * @param page  - pdf page infor
16062   * @param annotationPtr - pointer to pdf annotation
16063   * @param index  - index of annotation in the pdf page
16064   * @returns pdf freetext annotation
16065   *
16066   * @private
16067   */
16068  readPdfFreeTextAnno(doc, page, annotationPtr, index) {
16069    const annoRect = this.readPageAnnoRect(annotationPtr);
16070    const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);
16071    const defaultStyle = this.getAnnotString(annotationPtr, "DS");
16072    const da = this.getAnnotationDefaultAppearance(annotationPtr);
16073    const bgColor = this.getAnnotationColor(annotationPtr);
16074    const textColor = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.TextColor);
16075    const borderStyle = this.getBorderStyle(annotationPtr);
16076    const textAlign = this.getAnnotationTextAlignment(annotationPtr);
16077    const verticalAlign = this.getAnnotationVerticalAlignment(annotationPtr);
16078    const opacity = this.getAnnotationOpacity(annotationPtr);
16079    const richContent = this.getAnnotRichContent(annotationPtr);
16080    const rd = this.getRectangleDifferences(annotationPtr);
16081    const intent = this.getAnnotIntent(annotationPtr);
16082    const calloutLine = this.getCalloutLine(doc, page, annotationPtr);
16083    const lineEndings = this.getLineEndings(annotationPtr);
16084    return {
16085      pageIndex: page.index,
16086      id: index,
16087      type: PdfAnnotationSubtype.FREETEXT,
16088      rect,
16089      fontFamily: (da == null ? void 0 : da.fontFamily) ?? PdfStandardFont.Unknown,
16090      fontSize: (da == null ? void 0 : da.fontSize) ?? 12,
16091      fontColor: textColor ?? (da == null ? void 0 : da.fontColor) ?? "#000000",
16092      verticalAlign,
16093      color: bgColor,
16094      backgroundColor: bgColor,
16095      opacity,
16096      textAlign,
16097      defaultStyle,
16098      richContent,
16099      ...rd.ok && {
16100        rectangleDifferences: {
16101          left: rd.left,
16102          top: rd.top,
16103          right: rd.right,
16104          bottom: rd.bottom
16105        }
16106      },
16107      ...intent && { intent },
16108      ...calloutLine && { calloutLine },
16109      ...lineEndings && { lineEnding: lineEndings.end },
16110      ...borderStyle.width > 0 ? { strokeWidth: borderStyle.width, strokeColor: (da == null ? void 0 : da.fontColor) ?? "#000000" } : intent === "FreeTextCallout" ? { strokeWidth: 1, strokeColor: (da == null ? void 0 : da.fontColor) ?? "#000000" } : {},
16111      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16112    };
16113  }
16114  /**
16115   * Read pdf link annotation from pdf document
16116   * @param page  - pdf page infor
16117   * @param docPtr - pointer to pdf document object
16118   * @param annotationPtr - pointer to pdf annotation
16119   * @param index  - index of annotation in the pdf page
16120   * @returns pdf link annotation
16121   *
16122   * @private
16123   */
16124  readPdfLinkAnno(doc, page, docPtr, annotationPtr, index) {
16125    const linkPtr = this.pdfiumModule.FPDFAnnot_GetLink(annotationPtr);
16126    if (!linkPtr) {
16127      return;
16128    }
16129    const annoRect = this.readPageAnnoRect(annotationPtr);
16130    const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);
16131    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16132    const strokeColor = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.Color);
16133    let strokeDashArray;
16134    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16135      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16136      if (ok) {
16137        strokeDashArray = pattern;
16138      }
16139    }
16140    const target = this.readPdfLinkAnnoTarget(
16141      docPtr,
16142      () => {
16143        return this.pdfiumModule.FPDFLink_GetAction(linkPtr);
16144      },
16145      () => {
16146        return this.pdfiumModule.FPDFLink_GetDest(docPtr, linkPtr);
16147      }
16148    );
16149    return {
16150      pageIndex: page.index,
16151      id: index,
16152      type: PdfAnnotationSubtype.LINK,
16153      rect,
16154      target,
16155      strokeColor,
16156      strokeWidth,
16157      strokeStyle,
16158      strokeDashArray,
16159      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16160    };
16161  }
16162  /**
16163   * Read pdf widget annotation
16164   * @param page  - pdf page infor
16165   * @param annotationPtr - pointer to pdf annotation
16166   * @param formHandle - form handle
16167   * @param index  - index of annotation in the pdf page
16168   * @returns pdf widget annotation
16169   *
16170   * @private
16171   */
16172  readPdfWidgetAnno(doc, page, annotationPtr, formHandle, index) {
16173    const pageRect = this.readPageAnnoRect(annotationPtr);
16174    this.getAnnotationFlags(annotationPtr);
16175    const da = this.getAnnotationDefaultAppearance(annotationPtr);
16176    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16177    const field = this.readPdfWidgetAnnoField(formHandle, annotationPtr);
16178    const exportValue = this.readButtonExportValue(annotationPtr);
16179    const strokeColor = this.getMKColor(annotationPtr, 0);
16180    const color = this.getMKColor(annotationPtr, 1);
16181    const { width: strokeWidth } = this.getBorderStyle(annotationPtr);
16182    return {
16183      pageIndex: page.index,
16184      id: index,
16185      type: PdfAnnotationSubtype.WIDGET,
16186      fontFamily: (da == null ? void 0 : da.fontFamily) ?? PdfStandardFont.Unknown,
16187      fontSize: (da == null ? void 0 : da.fontSize) ?? 12,
16188      fontColor: (da == null ? void 0 : da.fontColor) ?? "#000000",
16189      rect,
16190      field,
16191      ...exportValue !== void 0 && { exportValue },
16192      strokeWidth,
16193      strokeColor: strokeColor ?? "transparent",
16194      color: color ?? "transparent",
16195      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16196    };
16197  }
16198  /**
16199   * Read pdf file attachment annotation
16200   * @param page  - pdf page infor
16201   * @param annotationPtr - pointer to pdf annotation
16202   * @param index  - index of annotation in the pdf page
16203   * @returns pdf file attachment annotation
16204   *
16205   * @private
16206   */
16207  readPdfFileAttachmentAnno(doc, page, annotationPtr, index) {
16208    const pageRect = this.readPageAnnoRect(annotationPtr);
16209    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16210    return {
16211      pageIndex: page.index,
16212      id: index,
16213      type: PdfAnnotationSubtype.FILEATTACHMENT,
16214      rect,
16215      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16216    };
16217  }
16218  /**
16219   * Read pdf ink annotation
16220   * @param page  - pdf page infor
16221   * @param annotationPtr - pointer to pdf annotation
16222   * @param index  - index of annotation in the pdf page
16223   * @returns pdf ink annotation
16224   *
16225   * @private
16226   */
16227  readPdfInkAnno(doc, page, annotationPtr, index) {
16228    const pageRect = this.readPageAnnoRect(annotationPtr);
16229    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16230    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";
16231    const opacity = this.getAnnotationOpacity(annotationPtr);
16232    const { width: strokeWidth } = this.getBorderStyle(annotationPtr);
16233    const inkList = this.getInkList(doc, page, annotationPtr);
16234    const intent = this.getAnnotIntent(annotationPtr);
16235    return {
16236      pageIndex: page.index,
16237      id: index,
16238      type: PdfAnnotationSubtype.INK,
16239      rect,
16240      ...intent && { intent },
16241      strokeColor,
16242      color: strokeColor,
16243      // deprecated alias
16244      opacity,
16245      strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,
16246      inkList,
16247      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16248    };
16249  }
16250  /**
16251   * Read pdf polygon annotation
16252   * @param page  - pdf page infor
16253   * @param annotationPtr - pointer to pdf annotation
16254   * @param index  - index of annotation in the pdf page
16255   * @returns pdf polygon annotation
16256   *
16257   * @private
16258   */
16259  readPdfPolygonAnno(doc, page, annotationPtr, index) {
16260    const pageRect = this.readPageAnnoRect(annotationPtr);
16261    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16262    const vertices = this.readPdfAnnoVertices(doc, page, annotationPtr);
16263    const strokeColor = this.getAnnotationColor(annotationPtr);
16264    const interiorColor = this.getAnnotationColor(
16265      annotationPtr,
16266      PdfAnnotationColorType.InteriorColor
16267    );
16268    const opacity = this.getAnnotationOpacity(annotationPtr);
16269    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16270    let strokeDashArray;
16271    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16272      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16273      if (ok) {
16274        strokeDashArray = pattern;
16275      }
16276    }
16277    if (vertices.length > 1) {
16278      const first = vertices[0];
16279      const last = vertices[vertices.length - 1];
16280      if (first.x === last.x && first.y === last.y) {
16281        vertices.pop();
16282      }
16283    }
16284    const rd = this.getRectangleDifferences(annotationPtr);
16285    const be = this.getBorderEffect(annotationPtr);
16286    return {
16287      pageIndex: page.index,
16288      id: index,
16289      type: PdfAnnotationSubtype.POLYGON,
16290      rect,
16291      strokeColor: strokeColor ?? "#FF0000",
16292      color: interiorColor ?? "transparent",
16293      opacity,
16294      strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,
16295      strokeStyle,
16296      strokeDashArray,
16297      vertices,
16298      ...be.ok && { cloudyBorderIntensity: be.intensity },
16299      ...rd.ok && {
16300        rectangleDifferences: {
16301          left: rd.left,
16302          top: rd.top,
16303          right: rd.right,
16304          bottom: rd.bottom
16305        }
16306      },
16307      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16308    };
16309  }
16310  /**
16311   * Read pdf polyline annotation
16312   * @param page  - pdf page infor
16313   * @param annotationPtr - pointer to pdf annotation
16314   * @param index  - index of annotation in the pdf page
16315   * @returns pdf polyline annotation
16316   *
16317   * @private
16318   */
16319  readPdfPolylineAnno(doc, page, annotationPtr, index) {
16320    const pageRect = this.readPageAnnoRect(annotationPtr);
16321    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16322    const vertices = this.readPdfAnnoVertices(doc, page, annotationPtr);
16323    const strokeColor = this.getAnnotationColor(annotationPtr);
16324    const interiorColor = this.getAnnotationColor(
16325      annotationPtr,
16326      PdfAnnotationColorType.InteriorColor
16327    );
16328    const opacity = this.getAnnotationOpacity(annotationPtr);
16329    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16330    let strokeDashArray;
16331    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16332      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16333      if (ok) {
16334        strokeDashArray = pattern;
16335      }
16336    }
16337    const lineEndings = this.getLineEndings(annotationPtr);
16338    return {
16339      pageIndex: page.index,
16340      id: index,
16341      type: PdfAnnotationSubtype.POLYLINE,
16342      rect,
16343      strokeColor: strokeColor ?? "#FF0000",
16344      color: interiorColor ?? "transparent",
16345      opacity,
16346      strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,
16347      strokeStyle,
16348      strokeDashArray,
16349      lineEndings,
16350      vertices,
16351      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16352    };
16353  }
16354  /**
16355   * Read pdf line annotation
16356   * @param page  - pdf page infor
16357   * @param annotationPtr - pointer to pdf annotation
16358   * @param index  - index of annotation in the pdf page
16359   * @returns pdf line annotation
16360   *
16361   * @private
16362   */
16363  readPdfLineAnno(doc, page, annotationPtr, index) {
16364    const pageRect = this.readPageAnnoRect(annotationPtr);
16365    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16366    const linePoints = this.getLinePoints(doc, page, annotationPtr);
16367    const lineEndings = this.getLineEndings(annotationPtr);
16368    const strokeColor = this.getAnnotationColor(annotationPtr);
16369    const interiorColor = this.getAnnotationColor(
16370      annotationPtr,
16371      PdfAnnotationColorType.InteriorColor
16372    );
16373    const opacity = this.getAnnotationOpacity(annotationPtr);
16374    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16375    let strokeDashArray;
16376    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16377      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16378      if (ok) {
16379        strokeDashArray = pattern;
16380      }
16381    }
16382    return {
16383      pageIndex: page.index,
16384      id: index,
16385      type: PdfAnnotationSubtype.LINE,
16386      rect,
16387      strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,
16388      strokeStyle,
16389      strokeDashArray,
16390      strokeColor: strokeColor ?? "#FF0000",
16391      color: interiorColor ?? "transparent",
16392      opacity,
16393      linePoints: linePoints || { start: { x: 0, y: 0 }, end: { x: 0, y: 0 } },
16394      lineEndings: lineEndings || {
16395        start: PdfAnnotationLineEnding.None,
16396        end: PdfAnnotationLineEnding.None
16397      },
16398      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16399    };
16400  }
16401  /**
16402   * Read pdf highlight annotation
16403   * @param page  - pdf page infor
16404   * @param annotationPtr - pointer to pdf annotation
16405   * @param index  - index of annotation in the pdf page
16406   * @returns pdf highlight annotation
16407   *
16408   * @private
16409   */
16410  readPdfHighlightAnno(doc, page, annotationPtr, index) {
16411    const pageRect = this.readPageAnnoRect(annotationPtr);
16412    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16413    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16414    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FFFF00";
16415    const opacity = this.getAnnotationOpacity(annotationPtr);
16416    return {
16417      pageIndex: page.index,
16418      id: index,
16419      type: PdfAnnotationSubtype.HIGHLIGHT,
16420      rect,
16421      segmentRects,
16422      strokeColor,
16423      color: strokeColor,
16424      // deprecated alias
16425      opacity,
16426      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16427    };
16428  }
16429  /**
16430   * Read pdf underline annotation
16431   * @param page  - pdf page infor
16432   * @param annotationPtr - pointer to pdf annotation
16433   * @param index  - index of annotation in the pdf page
16434   * @returns pdf underline annotation
16435   *
16436   * @private
16437   */
16438  readPdfUnderlineAnno(doc, page, annotationPtr, index) {
16439    const pageRect = this.readPageAnnoRect(annotationPtr);
16440    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16441    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16442    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";
16443    const opacity = this.getAnnotationOpacity(annotationPtr);
16444    return {
16445      pageIndex: page.index,
16446      id: index,
16447      type: PdfAnnotationSubtype.UNDERLINE,
16448      rect,
16449      segmentRects,
16450      strokeColor,
16451      color: strokeColor,
16452      // deprecated alias
16453      opacity,
16454      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16455    };
16456  }
16457  /**
16458   * Read strikeout annotation
16459   * @param page  - pdf page infor
16460   * @param annotationPtr - pointer to pdf annotation
16461   * @param index  - index of annotation in the pdf page
16462   * @returns pdf strikeout annotation
16463   *
16464   * @private
16465   */
16466  readPdfStrikeOutAnno(doc, page, annotationPtr, index) {
16467    const pageRect = this.readPageAnnoRect(annotationPtr);
16468    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16469    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16470    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";
16471    const opacity = this.getAnnotationOpacity(annotationPtr);
16472    return {
16473      pageIndex: page.index,
16474      id: index,
16475      type: PdfAnnotationSubtype.STRIKEOUT,
16476      rect,
16477      segmentRects,
16478      strokeColor,
16479      color: strokeColor,
16480      // deprecated alias
16481      opacity,
16482      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16483    };
16484  }
16485  /**
16486   * Read pdf squiggly annotation
16487   * @param page  - pdf page infor
16488   * @param annotationPtr - pointer to pdf annotation
16489   * @param index  - index of annotation in the pdf page
16490   * @returns pdf squiggly annotation
16491   *
16492   * @private
16493   */
16494  readPdfSquigglyAnno(doc, page, annotationPtr, index) {
16495    const pageRect = this.readPageAnnoRect(annotationPtr);
16496    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16497    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16498    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";
16499    const opacity = this.getAnnotationOpacity(annotationPtr);
16500    return {
16501      pageIndex: page.index,
16502      id: index,
16503      type: PdfAnnotationSubtype.SQUIGGLY,
16504      rect,
16505      segmentRects,
16506      strokeColor,
16507      color: strokeColor,
16508      // deprecated alias
16509      opacity,
16510      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16511    };
16512  }
16513  /**
16514   * Read pdf caret annotation
16515   * @param page  - pdf page infor
16516   * @param annotationPtr - pointer to pdf annotation
16517   * @param index  - index of annotation in the pdf page
16518   * @returns pdf caret annotation
16519   *
16520   * @private
16521   */
16522  readPdfCaretAnno(doc, page, annotationPtr, index) {
16523    const pageRect = this.readPageAnnoRect(annotationPtr);
16524    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16525    const strokeColor = this.getAnnotationColor(annotationPtr);
16526    const opacity = this.getAnnotationOpacity(annotationPtr);
16527    const intent = this.getAnnotIntent(annotationPtr);
16528    const rd = this.getRectangleDifferences(annotationPtr);
16529    return {
16530      pageIndex: page.index,
16531      id: index,
16532      type: PdfAnnotationSubtype.CARET,
16533      rect,
16534      strokeColor,
16535      opacity,
16536      intent,
16537      ...rd.ok && {
16538        rectangleDifferences: {
16539          left: rd.left,
16540          top: rd.top,
16541          right: rd.right,
16542          bottom: rd.bottom
16543        }
16544      },
16545      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16546    };
16547  }
16548  /**
16549   * Read pdf redact annotation
16550   * @param page  - pdf page info
16551   * @param annotationPtr - pointer to pdf annotation
16552   * @param index  - index of annotation in the pdf page
16553   * @returns pdf redact annotation
16554   *
16555   * @private
16556   */
16557  readPdfRedactAnno(doc, page, annotationPtr, index) {
16558    const pageRect = this.readPageAnnoRect(annotationPtr);
16559    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16560    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16561    const color = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.InteriorColor);
16562    const overlayColor = this.getAnnotationColor(
16563      annotationPtr,
16564      PdfAnnotationColorType.OverlayColor
16565    );
16566    const strokeColor = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.Color);
16567    const opacity = this.getAnnotationOpacity(annotationPtr);
16568    const overlayText = this.getOverlayText(annotationPtr);
16569    const overlayTextRepeat = this.getOverlayTextRepeat(annotationPtr);
16570    const da = this.getAnnotationDefaultAppearance(annotationPtr);
16571    const textAlign = this.getAnnotationTextAlignment(annotationPtr);
16572    return {
16573      pageIndex: page.index,
16574      id: index,
16575      type: PdfAnnotationSubtype.REDACT,
16576      rect,
16577      segmentRects,
16578      color,
16579      overlayColor,
16580      strokeColor,
16581      opacity,
16582      overlayText,
16583      overlayTextRepeat,
16584      fontFamily: da == null ? void 0 : da.fontFamily,
16585      fontSize: da == null ? void 0 : da.fontSize,
16586      fontColor: da == null ? void 0 : da.fontColor,
16587      textAlign,
16588      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16589    };
16590  }
16591  /**
16592   * Read pdf stamp annotation
16593   * @param page  - pdf page infor
16594   * @param annotationPtr - pointer to pdf annotation
16595   * @param index  - index of annotation in the pdf page
16596   * @returns pdf stamp annotation
16597   *
16598   * @private
16599   */
16600  readPdfStampAnno(doc, page, annotationPtr, index) {
16601    const pageRect = this.readPageAnnoRect(annotationPtr);
16602    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16603    const name = this.getAnnotationName(annotationPtr);
16604    return {
16605      pageIndex: page.index,
16606      id: index,
16607      type: PdfAnnotationSubtype.STAMP,
16608      rect,
16609      name,
16610      icon: name,
16611      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16612    };
16613  }
16614  /**
16615   * Read pdf object in pdf page
16616   * @param pageObjectPtr  - pointer to pdf object in page
16617   * @returns pdf object in page
16618   *
16619   * @private
16620   */
16621  readPdfPageObject(pageObjectPtr) {
16622    const type = this.pdfiumModule.FPDFPageObj_GetType(pageObjectPtr);
16623    switch (type) {
16624      case PdfPageObjectType.PATH:
16625        return this.readPathObject(pageObjectPtr);
16626      case PdfPageObjectType.IMAGE:
16627        return this.readImageObject(pageObjectPtr);
16628      case PdfPageObjectType.FORM:
16629        return this.readFormObject(pageObjectPtr);
16630    }
16631  }
16632  /**
16633   * Read pdf path object
16634   * @param pathObjectPtr  - pointer to pdf path object in page
16635   * @returns pdf path object
16636   *
16637   * @private
16638   */
16639  readPathObject(pathObjectPtr) {
16640    const segmentCount = this.pdfiumModule.FPDFPath_CountSegments(pathObjectPtr);
16641    const leftPtr = this.memoryManager.malloc(4);
16642    const bottomPtr = this.memoryManager.malloc(4);
16643    const rightPtr = this.memoryManager.malloc(4);
16644    const topPtr = this.memoryManager.malloc(4);
16645    this.pdfiumModule.FPDFPageObj_GetBounds(pathObjectPtr, leftPtr, bottomPtr, rightPtr, topPtr);
16646    const left = this.pdfiumModule.pdfium.getValue(leftPtr, "float");
16647    const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "float");
16648    const right = this.pdfiumModule.pdfium.getValue(rightPtr, "float");
16649    const top = this.pdfiumModule.pdfium.getValue(topPtr, "float");
16650    const bounds = { left, bottom, right, top };
16651    this.memoryManager.free(leftPtr);
16652    this.memoryManager.free(bottomPtr);
16653    this.memoryManager.free(rightPtr);
16654    this.memoryManager.free(topPtr);
16655    const segments = [];
16656    for (let i = 0; i < segmentCount; i++) {
16657      const segment = this.readPdfSegment(pathObjectPtr, i);
16658      segments.push(segment);
16659    }
16660    const matrix = this.readPdfPageObjectTransformMatrix(pathObjectPtr);
16661    return {
16662      type: PdfPageObjectType.PATH,
16663      bounds,
16664      segments,
16665      matrix
16666    };
16667  }
16668  /**
16669   * Read segment of pdf path object
16670   * @param annotationObjectPtr - pointer to pdf path object
16671   * @param segmentIndex - index of segment
16672   * @returns pdf segment in pdf path
16673   *
16674   * @private
16675   */
16676  readPdfSegment(annotationObjectPtr, segmentIndex) {
16677    const segmentPtr = this.pdfiumModule.FPDFPath_GetPathSegment(annotationObjectPtr, segmentIndex);
16678    const segmentType = this.pdfiumModule.FPDFPathSegment_GetType(segmentPtr);
16679    const isClosed = this.pdfiumModule.FPDFPathSegment_GetClose(segmentPtr);
16680    const pointXPtr = this.memoryManager.malloc(4);
16681    const pointYPtr = this.memoryManager.malloc(4);
16682    this.pdfiumModule.FPDFPathSegment_GetPoint(segmentPtr, pointXPtr, pointYPtr);
16683    const pointX = this.pdfiumModule.pdfium.getValue(pointXPtr, "float");
16684    const pointY = this.pdfiumModule.pdfium.getValue(pointYPtr, "float");
16685    this.memoryManager.free(pointXPtr);
16686    this.memoryManager.free(pointYPtr);
16687    return {
16688      type: segmentType,
16689      point: { x: pointX, y: pointY },
16690      isClosed
16691    };
16692  }
16693  /**
16694   * Read pdf image object from pdf document
16695   * @param pageObjectPtr  - pointer to pdf image object in page
16696   * @returns pdf image object
16697   *
16698   * @private
16699   */
16700  readImageObject(imageObjectPtr) {
16701    const bitmapPtr = this.pdfiumModule.FPDFImageObj_GetBitmap(imageObjectPtr);
16702    const bitmapBufferPtr = this.pdfiumModule.FPDFBitmap_GetBuffer(bitmapPtr);
16703    const bitmapWidth = this.pdfiumModule.FPDFBitmap_GetWidth(bitmapPtr);
16704    const bitmapHeight = this.pdfiumModule.FPDFBitmap_GetHeight(bitmapPtr);
16705    const format = this.pdfiumModule.FPDFBitmap_GetFormat(bitmapPtr);
16706    const pixelCount = bitmapWidth * bitmapHeight;
16707    const bytesPerPixel = 4;
16708    const array = new Uint8ClampedArray(pixelCount * bytesPerPixel);
16709    for (let i = 0; i < pixelCount; i++) {
16710      switch (format) {
16711        case 2:
16712          {
16713            const blue = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3, "i8");
16714            const green = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3 + 1, "i8");
16715            const red = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3 + 2, "i8");
16716            array[i * bytesPerPixel] = red;
16717            array[i * bytesPerPixel + 1] = green;
16718            array[i * bytesPerPixel + 2] = blue;
16719            array[i * bytesPerPixel + 3] = 100;
16720          }
16721          break;
16722      }
16723    }
16724    const imageDataLike = {
16725      data: array,
16726      width: bitmapWidth,
16727      height: bitmapHeight
16728    };
16729    const matrix = this.readPdfPageObjectTransformMatrix(imageObjectPtr);
16730    return {
16731      type: PdfPageObjectType.IMAGE,
16732      imageData: imageDataLike,
16733      matrix
16734    };
16735  }
16736  /**
16737   * Read form object from pdf document
16738   * @param formObjectPtr  - pointer to pdf form object in page
16739   * @returns pdf form object
16740   *
16741   * @private
16742   */
16743  readFormObject(formObjectPtr) {
16744    const objectCount = this.pdfiumModule.FPDFFormObj_CountObjects(formObjectPtr);
16745    const objects = [];
16746    for (let i = 0; i < objectCount; i++) {
16747      const pageObjectPtr = this.pdfiumModule.FPDFFormObj_GetObject(formObjectPtr, i);
16748      const pageObj = this.readPdfPageObject(pageObjectPtr);
16749      if (pageObj) {
16750        objects.push(pageObj);
16751      }
16752    }
16753    const matrix = this.readPdfPageObjectTransformMatrix(formObjectPtr);
16754    return {
16755      type: PdfPageObjectType.FORM,
16756      objects,
16757      matrix
16758    };
16759  }
16760  /**
16761   * Read pdf object in pdf page
16762   * @param pageObjectPtr  - pointer to pdf object in page
16763   * @returns pdf object in page
16764   *
16765   * @private
16766   */
16767  readPdfPageObjectTransformMatrix(pageObjectPtr) {
16768    const matrixPtr = this.memoryManager.malloc(4 * 6);
16769    if (this.pdfiumModule.FPDFPageObj_GetMatrix(pageObjectPtr, matrixPtr)) {
16770      const a = this.pdfiumModule.pdfium.getValue(matrixPtr, "float");
16771      const b = this.pdfiumModule.pdfium.getValue(matrixPtr + 4, "float");
16772      const c = this.pdfiumModule.pdfium.getValue(matrixPtr + 8, "float");
16773      const d = this.pdfiumModule.pdfium.getValue(matrixPtr + 12, "float");
16774      const e = this.pdfiumModule.pdfium.getValue(matrixPtr + 16, "float");
16775      const f = this.pdfiumModule.pdfium.getValue(matrixPtr + 20, "float");
16776      this.memoryManager.free(matrixPtr);
16777      return { a, b, c, d, e, f };
16778    }
16779    this.memoryManager.free(matrixPtr);
16780    return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
16781  }
16782  /**
16783   * Read contents of a stamp annotation
16784   * @param annotationPtr - pointer to pdf annotation
16785   * @returns contents of the stamp annotation
16786   *
16787   * @private
16788   */
16789  readStampAnnotationContents(annotationPtr) {
16790    const contents = [];
16791    const objectCount = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr);
16792    for (let i = 0; i < objectCount; i++) {
16793      const annotationObjectPtr = this.pdfiumModule.FPDFAnnot_GetObject(annotationPtr, i);
16794      const pageObj = this.readPdfPageObject(annotationObjectPtr);
16795      if (pageObj) {
16796        contents.push(pageObj);
16797      }
16798    }
16799    return contents;
16800  }
16801  /**
16802   * Return the stroke-width declared in the annotation’s /Border or /BS entry.
16803   * Falls back to 1 pt when nothing is defined.
16804   *
16805   * @param annotationPtr - pointer to pdf annotation
16806   * @returns stroke-width
16807   *
16808   * @private
16809   */
16810  getStrokeWidth(annotationPtr) {
16811    const hPtr = this.memoryManager.malloc(4);
16812    const vPtr = this.memoryManager.malloc(4);
16813    const wPtr = this.memoryManager.malloc(4);
16814    const ok = this.pdfiumModule.FPDFAnnot_GetBorder(annotationPtr, hPtr, vPtr, wPtr);
16815    const width = ok ? this.pdfiumModule.pdfium.getValue(wPtr, "float") : 1;
16816    this.memoryManager.free(hPtr);
16817    this.memoryManager.free(vPtr);
16818    this.memoryManager.free(wPtr);
16819    return width;
16820  }
16821  /**
16822   * Fetches the \`/F\` flag bit-field from an annotation.
16823   *
16824   * @param annotationPtr pointer to an \`FPDF_ANNOTATION\`
16825   * @returns \`{ raw, flags }\`
16826   *          • \`raw\`   – the 32-bit integer returned by PDFium
16827   *          • \`flags\` – object with individual booleans
16828   */
16829  getAnnotationFlags(annotationPtr) {
16830    const rawFlags = this.pdfiumModule.FPDFAnnot_GetFlags(annotationPtr);
16831    return flagsToNames(rawFlags);
16832  }
16833  setAnnotationFlags(annotationPtr, flags) {
16834    const rawFlags = namesToFlags(flags);
16835    return this.pdfiumModule.FPDFAnnot_SetFlags(annotationPtr, rawFlags);
16836  }
16837  /**
16838   * Read circle annotation
16839   * @param page  - pdf page infor
16840   * @param annotationPtr - pointer to pdf annotation
16841   * @param index  - index of annotation in the pdf page
16842   * @returns pdf circle annotation
16843   *
16844   * @private
16845   */
16846  readPdfCircleAnno(doc, page, annotationPtr, index) {
16847    const pageRect = this.readPageAnnoRect(annotationPtr);
16848    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16849    const interiorColor = this.getAnnotationColor(
16850      annotationPtr,
16851      PdfAnnotationColorType.InteriorColor
16852    );
16853    const strokeColor = this.getAnnotationColor(annotationPtr);
16854    const opacity = this.getAnnotationOpacity(annotationPtr);
16855    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16856    let strokeDashArray;
16857    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16858      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16859      if (ok) {
16860        strokeDashArray = pattern;
16861      }
16862    }
16863    const rd = this.getRectangleDifferences(annotationPtr);
16864    const be = this.getBorderEffect(annotationPtr);
16865    return {
16866      pageIndex: page.index,
16867      id: index,
16868      type: PdfAnnotationSubtype.CIRCLE,
16869      rect,
16870      color: interiorColor ?? "transparent",
16871      opacity,
16872      strokeWidth,
16873      strokeColor: strokeColor ?? "#FF0000",
16874      strokeStyle,
16875      ...strokeDashArray !== void 0 && { strokeDashArray },
16876      ...be.ok && { cloudyBorderIntensity: be.intensity },
16877      ...rd.ok && {
16878        rectangleDifferences: {
16879          left: rd.left,
16880          top: rd.top,
16881          right: rd.right,
16882          bottom: rd.bottom
16883        }
16884      },
16885      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16886    };
16887  }
16888  /**
16889   * Read square annotation
16890   * @param page  - pdf page infor
16891   * @param annotationPtr - pointer to pdf annotation
16892   * @param index  - index of annotation in the pdf page
16893   * @returns pdf square annotation
16894   *
16895   * @private
16896   */
16897  readPdfSquareAnno(doc, page, annotationPtr, index) {
16898    const pageRect = this.readPageAnnoRect(annotationPtr);
16899    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16900    const interiorColor = this.getAnnotationColor(
16901      annotationPtr,
16902      PdfAnnotationColorType.InteriorColor
16903    );
16904    const strokeColor = this.getAnnotationColor(annotationPtr);
16905    const opacity = this.getAnnotationOpacity(annotationPtr);
16906    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16907    let strokeDashArray;
16908    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16909      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16910      if (ok) {
16911        strokeDashArray = pattern;
16912      }
16913    }
16914    const rd = this.getRectangleDifferences(annotationPtr);
16915    const be = this.getBorderEffect(annotationPtr);
16916    return {
16917      pageIndex: page.index,
16918      id: index,
16919      type: PdfAnnotationSubtype.SQUARE,
16920      rect,
16921      color: interiorColor ?? "transparent",
16922      opacity,
16923      strokeColor: strokeColor ?? "#FF0000",
16924      strokeWidth,
16925      strokeStyle,
16926      ...strokeDashArray !== void 0 && { strokeDashArray },
16927      ...be.ok && { cloudyBorderIntensity: be.intensity },
16928      ...rd.ok && {
16929        rectangleDifferences: {
16930          left: rd.left,
16931          top: rd.top,
16932          right: rd.right,
16933          bottom: rd.bottom
16934        }
16935      },
16936      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16937    };
16938  }
16939  /**
16940   * Read basic info of unsupported pdf annotation
16941   * @param page  - pdf page infor
16942   * @param type - type of annotation
16943   * @param annotationPtr - pointer to pdf annotation
16944   * @param index  - index of annotation in the pdf page
16945   * @returns pdf annotation
16946   *
16947   * @private
16948   */
16949  readPdfAnno(doc, page, type, annotationPtr, index) {
16950    const pageRect = this.readPageAnnoRect(annotationPtr);
16951    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16952    return {
16953      pageIndex: page.index,
16954      id: index,
16955      type,
16956      rect,
16957      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16958    };
16959  }
16960  /**
16961   * Resolve \`/IRT\` → parent-annotation index on the same page.
16962   *
16963   * @param pagePtr        - pointer to FPDF_PAGE
16964   * @param annotationPtr  - pointer to FPDF_ANNOTATION
16965   * @returns index (\`0…count-1\`) or \`undefined\` when the annotation is *not* a reply
16966   *
16967   * @private
16968   */
16969  getInReplyToId(annotationPtr) {
16970    const parentPtr = this.pdfiumModule.FPDFAnnot_GetLinkedAnnot(annotationPtr, "IRT");
16971    if (!parentPtr) return;
16972    let nm = this.getAnnotString(parentPtr, "NM");
16973    if (!nm || !isUuidV4(nm)) {
16974      nm = uuidV4();
16975      this.setAnnotString(parentPtr, "NM", nm);
16976    }
16977    this.pdfiumModule.FPDFPage_CloseAnnot(parentPtr);
16978    return nm;
16979  }
16980  /**
16981   * Set the in reply to id of the annotation
16982   *
16983   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
16984   * @param id - the id of the parent annotation
16985   * @returns \`true\` on success
16986   */
16987  setInReplyToId(pagePtr, annotationPtr, id) {
16988    if (!id) {
16989      return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(annotationPtr, "IRT", 0);
16990    }
16991    const parentPtr = this.getAnnotationByName(pagePtr, id);
16992    if (!parentPtr) return false;
16993    return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(annotationPtr, "IRT", parentPtr);
16994  }
16995  /**
16996   * Rotate a point around a center by the given angle in degrees.
16997   * Used to rotate vertices for PDF storage.
16998   */
16999  rotatePointForSave(point, center, angleDegrees) {
17000    const rad = angleDegrees * Math.PI / 180;
17001    const cos = Math.cos(rad);
17002    const sin = Math.sin(rad);
17003    const dx = point.x - center.x;
17004    const dy = point.y - center.y;
17005    return {
17006      x: center.x + dx * cos - dy * sin,
17007      y: center.y + dx * sin + dy * cos
17008    };
17009  }
17010  /**
17011   * Prepare an annotation for saving to PDF.
17012   * For vertex types (ink, line, polygon, polyline) with rotation,
17013   * physically rotates the vertices by +rotation so that other PDF viewers
17014   * see the correct visual result. Our viewer reverse-rotates on load.
17015   */
17016  prepareAnnotationForSave(annotation) {
17017    const rotation = annotation.rotation;
17018    const unrotatedRect = annotation.unrotatedRect;
17019    if (!rotation || rotation === 0 || !unrotatedRect) {
17020      return annotation;
17021    }
17022    const center = {
17023      x: unrotatedRect.origin.x + unrotatedRect.size.width / 2,
17024      y: unrotatedRect.origin.y + unrotatedRect.size.height / 2
17025    };
17026    switch (annotation.type) {
17027      case PdfAnnotationSubtype.INK: {
17028        const ink = annotation;
17029        const rotatedInkList = ink.inkList.map((stroke) => ({
17030          points: stroke.points.map((p) => this.rotatePointForSave(p, center, rotation))
17031        }));
17032        return { ...ink, inkList: rotatedInkList };
17033      }
17034      case PdfAnnotationSubtype.LINE: {
17035        const line = annotation;
17036        return {
17037          ...line,
17038          linePoints: {
17039            start: this.rotatePointForSave(line.linePoints.start, center, rotation),
17040            end: this.rotatePointForSave(line.linePoints.end, center, rotation)
17041          }
17042        };
17043      }
17044      case PdfAnnotationSubtype.POLYGON: {
17045        const poly = annotation;
17046        return {
17047          ...poly,
17048          vertices: poly.vertices.map((v) => this.rotatePointForSave(v, center, rotation))
17049        };
17050      }
17051      case PdfAnnotationSubtype.POLYLINE: {
17052        const polyline = annotation;
17053        return {
17054          ...polyline,
17055          vertices: polyline.vertices.map((v) => this.rotatePointForSave(v, center, rotation))
17056        };
17057      }
17058      default:
17059        return annotation;
17060    }
17061  }
17062  /**
17063   * Apply all base annotation properties from PdfAnnotationObjectBase.
17064   * The setInReplyToId and setReplyType functions handle clearing when undefined.
17065   *
17066   * @param pagePtr - pointer to page object
17067   * @param annotationPtr - pointer to annotation object
17068   * @param annotation - the annotation object containing properties to apply
17069   * @returns \`true\` on success
17070   */
17071  applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation) {
17072    if (!this.setAnnotString(annotationPtr, "T", annotation.author || "")) {
17073      return false;
17074    }
17075    if (!this.setAnnotString(annotationPtr, "Contents", annotation.contents ?? "")) {
17076      return false;
17077    }
17078    if (annotation.subject && !this.setAnnotString(annotationPtr, "Subj", annotation.subject)) {
17079      return false;
17080    }
17081    if (annotation.modified) {
17082      if (!this.setAnnotationDate(annotationPtr, "M", annotation.modified)) {
17083        return false;
17084      }
17085    }
17086    if (annotation.created) {
17087      if (!this.setAnnotationDate(annotationPtr, "CreationDate", annotation.created)) {
17088        return false;
17089      }
17090    }
17091    if (annotation.flags) {
17092      if (!this.setAnnotationFlags(annotationPtr, annotation.flags)) {
17093        return false;
17094      }
17095    }
17096    const existingCustom = this.getAnnotCustom(annotationPtr) ?? {};
17097    const customData = {
17098      ...existingCustom,
17099      ...annotation.custom ?? {}
17100    };
17101    delete customData.unrotatedRect;
17102    delete customData.rotation;
17103    const hasCustomData = Object.keys(customData).length > 0;
17104    if (hasCustomData) {
17105      if (!this.setAnnotCustom(annotationPtr, customData)) {
17106        return false;
17107      }
17108    } else if (Object.keys(existingCustom).length > 0) {
17109      if (!this.setAnnotCustom(annotationPtr, null)) {
17110        return false;
17111      }
17112    }
17113    if (annotation.rotation !== void 0) {
17114      const pdfRotation = annotation.rotation ? (360 - annotation.rotation) % 360 : 0;
17115      this.setAnnotExtendedRotation(annotationPtr, pdfRotation);
17116    }
17117    if (annotation.unrotatedRect) {
17118      this.setAnnotUnrotatedRect(doc, page, annotationPtr, annotation.unrotatedRect);
17119    } else if (annotation.rotation && annotation.rotation !== 0) {
17120      this.setAnnotUnrotatedRect(doc, page, annotationPtr, annotation.rect);
17121    }
17122    if (!this.setInReplyToId(pagePtr, annotationPtr, annotation.inReplyToId)) {
17123      return false;
17124    }
17125    if (!this.setReplyType(annotationPtr, annotation.replyType)) {
17126      return false;
17127    }
17128    return true;
17129  }
17130  /**
17131   * Read all base annotation properties from PdfAnnotationObjectBase.
17132   * Returns an object that can be spread into the annotation return value.
17133   *
17134   * @param doc - pdf document object
17135   * @param page - pdf page object
17136   * @param annotationPtr - pointer to annotation object
17137   * @returns object with base annotation properties
17138   */
17139  readBaseAnnotationProperties(doc, page, annotationPtr) {
17140    const author = this.getAnnotString(annotationPtr, "T");
17141    const contents = this.getAnnotString(annotationPtr, "Contents") || "";
17142    const modified = this.getAnnotationDate(annotationPtr, "M");
17143    const created = this.getAnnotationDate(annotationPtr, "CreationDate");
17144    const subject = this.getAnnotString(annotationPtr, "Subj");
17145    const flags = this.getAnnotationFlags(annotationPtr);
17146    const custom = this.getAnnotCustom(annotationPtr);
17147    const inReplyToId = this.getInReplyToId(annotationPtr);
17148    const replyType = this.getReplyType(annotationPtr);
17149    const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);
17150    const pdfRotation = this.getAnnotExtendedRotation(annotationPtr);
17151    const rotation = pdfRotation !== 0 ? (360 - pdfRotation) % 360 : 0;
17152    const rawUnrotatedRect = this.readAnnotUnrotatedRect(annotationPtr);
17153    const unrotatedRect = rawUnrotatedRect ? this.convertPageRectToDeviceRect(doc, page, rawUnrotatedRect) : void 0;
17154    return {
17155      author,
17156      contents,
17157      modified,
17158      created,
17159      flags,
17160      custom,
17161      blendMode,
17162      ...subject && { subject },
17163      // Only include IRT if present
17164      ...inReplyToId && { inReplyToId },
17165      // Only include RT if present and not the default (Reply)
17166      ...replyType && replyType !== PdfAnnotationReplyType.Reply && { replyType },
17167      ...rotation !== 0 && { rotation },
17168      ...unrotatedRect !== void 0 && { unrotatedRect }
17169    };
17170  }
17171  /**
17172   * Fetch a string value (\`/T\`, \`/M\`, \`/State\`, …) from an annotation.
17173   *
17174   * @returns decoded UTF-8 string or \`undefined\` when the key is absent
17175   *
17176   * @private
17177   */
17178  getAnnotString(annotationPtr, key) {
17179    const len = this.pdfiumModule.FPDFAnnot_GetStringValue(annotationPtr, key, 0, 0);
17180    if (len === 0) return;
17181    const bytes = (len + 1) * 2;
17182    const ptr = this.memoryManager.malloc(bytes);
17183    this.pdfiumModule.FPDFAnnot_GetStringValue(annotationPtr, key, ptr, bytes);
17184    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17185    this.memoryManager.free(ptr);
17186    return value || void 0;
17187  }
17188  readButtonExportValue(annotationPtr) {
17189    const len = this.pdfiumModule.EPDFAnnot_GetButtonExportValue(annotationPtr, 0, 0);
17190    if (len === 0) return;
17191    const bytes = (len + 1) * 2;
17192    const ptr = this.memoryManager.malloc(bytes);
17193    this.pdfiumModule.EPDFAnnot_GetButtonExportValue(annotationPtr, ptr, bytes);
17194    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17195    this.memoryManager.free(ptr);
17196    return value || void 0;
17197  }
17198  /**
17199   * Get a string value (\`/T\`, \`/M\`, \`/State\`, …) from an attachment.
17200   *
17201   * @returns decoded UTF-8 string or \`undefined\` when the key is absent
17202   *
17203   * @private
17204   */
17205  getAttachmentString(attachmentPtr, key) {
17206    const len = this.pdfiumModule.FPDFAttachment_GetStringValue(attachmentPtr, key, 0, 0);
17207    if (len === 0) return;
17208    const bytes = (len + 1) * 2;
17209    const ptr = this.memoryManager.malloc(bytes);
17210    this.pdfiumModule.FPDFAttachment_GetStringValue(attachmentPtr, key, ptr, bytes);
17211    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17212    this.memoryManager.free(ptr);
17213    return value || void 0;
17214  }
17215  /**
17216   * Get a number value (\`/Size\`) from an attachment.
17217   *
17218   * @returns number or \`null\` when the key is absent
17219   *
17220   * @private
17221   */
17222  getAttachmentNumber(attachmentPtr, key) {
17223    const outPtr = this.memoryManager.malloc(4);
17224    try {
17225      const ok = this.pdfiumModule.EPDFAttachment_GetIntegerValue(
17226        attachmentPtr,
17227        key,
17228        // FPDF_BYTESTRING → ASCII JS string is fine in your glue
17229        outPtr
17230      );
17231      if (!ok) return void 0;
17232      return this.pdfiumModule.pdfium.getValue(outPtr, "i32") >>> 0;
17233    } finally {
17234      this.memoryManager.free(outPtr);
17235    }
17236  }
17237  /**
17238   * Get custom data of the annotation
17239   * @param annotationPtr - pointer to pdf annotation
17240   * @returns custom data of the annotation
17241   *
17242   * @private
17243   */
17244  getAnnotCustom(annotationPtr) {
17245    const custom = this.getAnnotString(annotationPtr, "EPDFCustom");
17246    if (!custom) return;
17247    try {
17248      return JSON.parse(custom);
17249    } catch (error) {
17250      console.warn("Failed to parse annotation custom data as JSON:", error);
17251      console.warn("Invalid JSON string:", custom);
17252      return void 0;
17253    }
17254  }
17255  /**
17256   * Sets custom data for an annotation by safely stringifying and storing JSON
17257   * @private
17258   */
17259  setAnnotCustom(annotationPtr, data) {
17260    if (data === void 0 || data === null) {
17261      return this.setAnnotString(annotationPtr, "EPDFCustom", "");
17262    }
17263    try {
17264      const jsonString = JSON.stringify(data);
17265      return this.setAnnotString(annotationPtr, "EPDFCustom", jsonString);
17266    } catch (error) {
17267      console.warn("Failed to stringify annotation custom data as JSON:", error);
17268      console.warn("Invalid data object:", data);
17269      return false;
17270    }
17271  }
17272  /**
17273   * Fetches the /IT (Intent) name from an annotation as a UTF-8 JS string.
17274   *
17275   * Mirrors getAnnotString(): calls EPDFAnnot_GetIntent twice (length probe + copy).
17276   * Returns \`undefined\` if no intent present.
17277   */
17278  getAnnotIntent(annotationPtr) {
17279    const len = this.pdfiumModule.EPDFAnnot_GetIntent(annotationPtr, 0, 0);
17280    if (len === 0) return;
17281    const codeUnits = len + 1;
17282    const bytes = codeUnits * 2;
17283    const ptr = this.memoryManager.malloc(bytes);
17284    this.pdfiumModule.EPDFAnnot_GetIntent(annotationPtr, ptr, bytes);
17285    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17286    this.memoryManager.free(ptr);
17287    return value && value !== "undefined" ? value : void 0;
17288  }
17289  /**
17290   * Write the \`/IT\` (Intent) name into an annotation dictionary.
17291   *
17292   * Mirrors EPDFAnnot_SetIntent in PDFium (expects a UTF‑8 FPDF_BYTESTRING).
17293   *
17294   * @param annotationPtr Pointer returned by FPDFPage_GetAnnot
17295   * @param intent        Name without leading slash, e.g. \`"PolygonCloud"\`
17296   *                      A leading “/” will be stripped for convenience.
17297   * @returns             true on success, false otherwise
17298   */
17299  setAnnotIntent(annotationPtr, intent) {
17300    return this.pdfiumModule.EPDFAnnot_SetIntent(annotationPtr, intent);
17301  }
17302  /**
17303   * Returns the rich‑content string stored in the annotation’s \`/RC\` entry.
17304   *
17305   * Works like \`getAnnotIntent()\`: first probe for length, then copy.
17306   * \`undefined\` when the annotation has no rich content.
17307   */
17308  getAnnotRichContent(annotationPtr) {
17309    const len = this.pdfiumModule.EPDFAnnot_GetRichContent(annotationPtr, 0, 0);
17310    if (len === 0) return;
17311    const codeUnits = len + 1;
17312    const bytes = codeUnits * 2;
17313    const ptr = this.memoryManager.malloc(bytes);
17314    this.pdfiumModule.EPDFAnnot_GetRichContent(annotationPtr, ptr, bytes);
17315    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17316    this.memoryManager.free(ptr);
17317    return value || void 0;
17318  }
17319  /**
17320   * Get annotation by name
17321   * @param pagePtr - pointer to pdf page object
17322   * @param name - name of annotation
17323   * @returns pointer to pdf annotation
17324   *
17325   * @private
17326   */
17327  getAnnotationByName(pagePtr, name) {
17328    return this.withWString(name, (wNamePtr) => {
17329      return this.pdfiumModule.EPDFPage_GetAnnotByName(pagePtr, wNamePtr);
17330    });
17331  }
17332  /**
17333   * Remove annotation by name
17334   * @param pagePtr - pointer to pdf page object
17335   * @param name - name of annotation
17336   * @returns true on success
17337   *
17338   * @private
17339   */
17340  removeAnnotationByName(pagePtr, name) {
17341    return this.withWString(name, (wNamePtr) => {
17342      return this.pdfiumModule.EPDFPage_RemoveAnnotByName(pagePtr, wNamePtr);
17343    });
17344  }
17345  /**
17346   * Set a string value (\`/T\`, \`/M\`, \`/State\`, …) to an annotation.
17347   *
17348   * @returns \`true\` if the operation was successful
17349   *
17350   * @private
17351   */
17352  setAnnotString(annotationPtr, key, value) {
17353    return this.withWString(value, (wValPtr) => {
17354      return this.pdfiumModule.FPDFAnnot_SetStringValue(annotationPtr, key, wValPtr);
17355    });
17356  }
17357  /**
17358   * Set a string value (\`/T\`, \`/M\`, \`/State\`, …) to an attachment.
17359   *
17360   * @returns \`true\` if the operation was successful
17361   *
17362   * @private
17363   */
17364  setAttachmentString(attachmentPtr, key, value) {
17365    return this.withWString(value, (wValPtr) => {
17366      return this.pdfiumModule.FPDFAttachment_SetStringValue(attachmentPtr, key, wValPtr);
17367    });
17368  }
17369  /**
17370   * Read vertices of pdf annotation
17371   * @param doc - pdf document object
17372   * @param page  - pdf page infor
17373   * @param annotationPtr - pointer to pdf annotation
17374   * @returns vertices of pdf annotation
17375   *
17376   * @private
17377   */
17378  readPdfAnnoVertices(doc, page, annotationPtr) {
17379    const vertices = [];
17380    const count = this.pdfiumModule.FPDFAnnot_GetVertices(annotationPtr, 0, 0);
17381    const pointMemorySize = 8;
17382    const pointsPtr = this.memoryManager.malloc(count * pointMemorySize);
17383    this.pdfiumModule.FPDFAnnot_GetVertices(annotationPtr, pointsPtr, count);
17384    for (let i = 0; i < count; i++) {
17385      const pointX = this.pdfiumModule.pdfium.getValue(pointsPtr + i * pointMemorySize, "float");
17386      const pointY = this.pdfiumModule.pdfium.getValue(
17387        pointsPtr + i * pointMemorySize + 4,
17388        "float"
17389      );
17390      const { x, y } = this.convertPagePointToDevicePoint(doc, page, {
17391        x: pointX,
17392        y: pointY
17393      });
17394      const last = vertices[vertices.length - 1];
17395      if (!last || last.x !== x || last.y !== y) {
17396        vertices.push({ x, y });
17397      }
17398    }
17399    this.memoryManager.free(pointsPtr);
17400    return vertices;
17401  }
17402  /**
17403   * Sync the vertices of a polygon or polyline annotation.
17404   *
17405   * @param doc - pdf document object
17406   * @param page  - pdf page infor
17407   * @param annotPtr - pointer to pdf annotation
17408   * @param vertices - the vertices to be set
17409   * @returns true on success
17410   *
17411   * @private
17412   */
17413  setPdfAnnoVertices(doc, page, annotPtr, vertices) {
17414    const pdf = this.pdfiumModule.pdfium;
17415    const FS_POINTF_SIZE = 8;
17416    const buf = this.memoryManager.malloc(FS_POINTF_SIZE * vertices.length);
17417    vertices.forEach((v, i) => {
17418      const pagePt = this.convertDevicePointToPagePoint(doc, page, v);
17419      pdf.setValue(buf + i * FS_POINTF_SIZE + 0, pagePt.x, "float");
17420      pdf.setValue(buf + i * FS_POINTF_SIZE + 4, pagePt.y, "float");
17421    });
17422    const ok = this.pdfiumModule.EPDFAnnot_SetVertices(annotPtr, buf, vertices.length);
17423    this.memoryManager.free(buf);
17424    return ok;
17425  }
17426  /**
17427   * Read the callout line points (/CL) from a FreeText annotation.
17428   * Returns an array of 2 or 3 Position points in device coords, or undefined.
17429   *
17430   * @private
17431   */
17432  getCalloutLine(doc, page, annotationPtr) {
17433    const count = this.pdfiumModule.EPDFAnnot_GetCalloutLineCount(annotationPtr);
17434    if (count === 0) {
17435      return void 0;
17436    }
17437    const FS_POINTF_SIZE = 8;
17438    const pointsPtr = this.memoryManager.malloc(count * FS_POINTF_SIZE);
17439    const result = this.pdfiumModule.EPDFAnnot_GetCalloutLine(annotationPtr, pointsPtr, count);
17440    if (result === 0) {
17441      this.memoryManager.free(pointsPtr);
17442      return void 0;
17443    }
17444    const points = [];
17445    for (let i = 0; i < count; i++) {
17446      const px = this.pdfiumModule.pdfium.getValue(pointsPtr + i * FS_POINTF_SIZE, "float");
17447      const py = this.pdfiumModule.pdfium.getValue(pointsPtr + i * FS_POINTF_SIZE + 4, "float");
17448      points.push(this.convertPagePointToDevicePoint(doc, page, { x: px, y: py }));
17449    }
17450    this.memoryManager.free(pointsPtr);
17451    return points;
17452  }
17453  /**
17454   * Set the callout line points (/CL) on a FreeText annotation.
17455   * Converts from device coords to page coords before writing.
17456   *
17457   * @private
17458   */
17459  setCalloutLine(doc, page, annotPtr, points) {
17460    const pdf = this.pdfiumModule.pdfium;
17461    const FS_POINTF_SIZE = 8;
17462    const buf = this.memoryManager.malloc(FS_POINTF_SIZE * points.length);
17463    points.forEach((v, i) => {
17464      const pagePt = this.convertDevicePointToPagePoint(doc, page, v);
17465      pdf.setValue(buf + i * FS_POINTF_SIZE + 0, pagePt.x, "float");
17466      pdf.setValue(buf + i * FS_POINTF_SIZE + 4, pagePt.y, "float");
17467    });
17468    const ok = this.pdfiumModule.EPDFAnnot_SetCalloutLine(annotPtr, buf, points.length);
17469    this.memoryManager.free(buf);
17470    return ok;
17471  }
17472  /**
17473   * Read the target of pdf bookmark
17474   * @param docPtr - pointer to pdf document object
17475   * @param getActionPtr - callback function to retrive the pointer of action
17476   * @param getDestinationPtr - callback function to retrive the pointer of destination
17477   * @returns target of pdf bookmark
17478   *
17479   * @private
17480   */
17481  readPdfBookmarkTarget(docPtr, getActionPtr, getDestinationPtr) {
17482    const actionPtr = getActionPtr();
17483    if (actionPtr) {
17484      const action = this.readPdfAction(docPtr, actionPtr);
17485      return {
17486        type: "action",
17487        action
17488      };
17489    } else {
17490      const destinationPtr = getDestinationPtr();
17491      if (destinationPtr) {
17492        const destination = this.readPdfDestination(docPtr, destinationPtr);
17493        return {
17494          type: "destination",
17495          destination
17496        };
17497      }
17498    }
17499  }
17500  /**
17501   * Read field of pdf widget annotation
17502   * @param formHandle - form handle
17503   * @param annotationPtr - pointer to pdf annotation
17504   * @returns field of pdf widget annotation
17505   *
17506   * @private
17507   */
17508  readPdfWidgetAnnoField(formHandle, annotationPtr) {
17509    const flag = this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(
17510      formHandle,
17511      annotationPtr
17512    );
17513    const type = this.pdfiumModule.FPDFAnnot_GetFormFieldType(
17514      formHandle,
17515      annotationPtr
17516    );
17517    const name = readString(
17518      this.pdfiumModule.pdfium,
17519      (buffer, bufferLength) => {
17520        return this.pdfiumModule.FPDFAnnot_GetFormFieldName(
17521          formHandle,
17522          annotationPtr,
17523          buffer,
17524          bufferLength
17525        );
17526      },
17527      this.pdfiumModule.pdfium.UTF16ToString
17528    );
17529    const alternateName = readString(
17530      this.pdfiumModule.pdfium,
17531      (buffer, bufferLength) => {
17532        return this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(
17533          formHandle,
17534          annotationPtr,
17535          buffer,
17536          bufferLength
17537        );
17538      },
17539      this.pdfiumModule.pdfium.UTF16ToString
17540    );
17541    const value = readString(
17542      this.pdfiumModule.pdfium,
17543      (buffer, bufferLength) => {
17544        return this.pdfiumModule.EPDFAnnot_GetFormFieldRawValue(
17545          formHandle,
17546          annotationPtr,
17547          buffer,
17548          bufferLength
17549        );
17550      },
17551      this.pdfiumModule.pdfium.UTF16ToString
17552    );
17553    const fieldObjectId = this.pdfiumModule.EPDFAnnot_GetFormFieldObjectNumber(
17554      formHandle,
17555      annotationPtr
17556    );
17557    const base = {
17558      flag,
17559      name,
17560      alternateName,
17561      value,
17562      fieldObjectId: fieldObjectId > 0 ? fieldObjectId : void 0
17563    };
17564    switch (type) {
17565      case PDF_FORM_FIELD_TYPE.TEXTFIELD: {
17566        let maxLen;
17567        const floatPtr = this.memoryManager.malloc(4);
17568        const ok = this.pdfiumModule.FPDFAnnot_GetNumberValue(annotationPtr, "MaxLen", floatPtr);
17569        if (ok) {
17570          maxLen = this.pdfiumModule.pdfium.getValue(floatPtr, "float");
17571        }
17572        this.memoryManager.free(floatPtr);
17573        return { ...base, type, maxLen };
17574      }
17575      case PDF_FORM_FIELD_TYPE.CHECKBOX:
17576        return { ...base, type };
17577      case PDF_FORM_FIELD_TYPE.RADIOBUTTON:
17578        return {
17579          ...base,
17580          type,
17581          options: this.readWidgetOptions(formHandle, annotationPtr)
17582        };
17583      case PDF_FORM_FIELD_TYPE.COMBOBOX:
17584        return { ...base, type, options: this.readWidgetOptions(formHandle, annotationPtr) };
17585      case PDF_FORM_FIELD_TYPE.LISTBOX:
17586        return { ...base, type, options: this.readWidgetOptions(formHandle, annotationPtr) };
17587      case PDF_FORM_FIELD_TYPE.PUSHBUTTON:
17588        return { ...base, type };
17589      case PDF_FORM_FIELD_TYPE.SIGNATURE:
17590        return { ...base, type };
17591      default:
17592        return { ...base, type };
17593    }
17594  }
17595  readWidgetOptions(formHandle, annotationPtr) {
17596    const options = [];
17597    const count = this.pdfiumModule.FPDFAnnot_GetOptionCount(formHandle, annotationPtr);
17598    for (let i = 0; i < count; i++) {
17599      const label = readString(
17600        this.pdfiumModule.pdfium,
17601        (buffer, bufferLength) => {
17602          return this.pdfiumModule.FPDFAnnot_GetOptionLabel(
17603            formHandle,
17604            annotationPtr,
17605            i,
17606            buffer,
17607            bufferLength
17608          );
17609        },
17610        this.pdfiumModule.pdfium.UTF16ToString
17611      );
17612      const isSelected = this.pdfiumModule.FPDFAnnot_IsOptionSelected(formHandle, annotationPtr, i);
17613      options.push({ label, isSelected });
17614    }
17615    return options;
17616  }
17617  /**
17618   * {@inheritDoc @embedpdf/models!PdfEngine.renderAnnotation}
17619   *
17620   * @public
17621   */
17622  renderPageAnnotationRaw(doc, page, annotation, options) {
17623    const {
17624      scaleFactor = 1,
17625      rotation = Rotation.Degree0,
17626      dpr = 1,
17627      mode = AppearanceMode.Normal
17628    } = options ?? {};
17629    this.logger.debug(
17630      LOG_SOURCE$1,
17631      LOG_CATEGORY$1,
17632      "renderPageAnnotation",
17633      doc,
17634      page,
17635      annotation,
17636      options
17637    );
17638    this.logger.perf(
17639      LOG_SOURCE$1,
17640      LOG_CATEGORY$1,
17641      \`RenderPageAnnotation\`,
17642      "Begin",
17643      \`\${doc.id}-\${page.index}-\${annotation.id}\`
17644    );
17645    const task = new Task();
17646    const ctx = this.cache.getContext(doc.id);
17647    if (!ctx) {
17648      this.logger.perf(
17649        LOG_SOURCE$1,
17650        LOG_CATEGORY$1,
17651        \`RenderPageAnnotation\`,
17652        "End",
17653        \`\${doc.id}-\${page.index}-\${annotation.id}\`
17654      );
17655      return PdfTaskHelper.reject({
17656        code: PdfErrorCode.DocNotOpen,
17657        message: "document does not open"
17658      });
17659    }
17660    const pageCtx = ctx.acquirePage(page.index);
17661    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
17662    if (!annotPtr) {
17663      this.logger.perf(
17664        LOG_SOURCE$1,
17665        LOG_CATEGORY$1,
17666        \`RenderPageAnnotation\`,
17667        "End",
17668        \`\${doc.id}-\${page.index}-\${annotation.id}\`
17669      );
17670      pageCtx.release();
17671      return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });
17672    }
17673    let hasAP = !!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(annotPtr, mode);
17674    if (!hasAP && annotation.type === PdfAnnotationSubtype.WIDGET) {
17675      if (!this.pdfiumModule.FPDFAnnot_HasKey(annotPtr, "AP")) {
17676        this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotPtr);
17677        hasAP = !!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(annotPtr, mode);
17678      }
17679    }
17680    if (!hasAP) {
17681      this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
17682      pageCtx.release();
17683      this.logger.perf(
17684        LOG_SOURCE$1,
17685        LOG_CATEGORY$1,
17686        \`RenderPageAnnotation\`,
17687        "End",
17688        \`\${doc.id}-\${page.index}-\${annotation.id}\`
17689      );
17690      task.resolve({ data: new Uint8ClampedArray(4), width: 1, height: 1 });
17691      return task;
17692    }
17693    const finalScale = Math.max(0.01, scaleFactor * dpr);
17694    const unrotated = !!(options == null ? void 0 : options.unrotated) && !!annotation.unrotatedRect;
17695    const renderRect = unrotated ? annotation.unrotatedRect : annotation.rect;
17696    const devRect = toIntRect(transformRect(page.size, renderRect, rotation, finalScale));
17697    const wDev = Math.max(1, devRect.size.width);
17698    const hDev = Math.max(1, devRect.size.height);
17699    const stride = wDev * 4;
17700    const bytes = stride * hDev;
17701    const heapPtr = this.memoryManager.malloc(bytes);
17702    const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(
17703      wDev,
17704      hDev,
17705      4,
17706      heapPtr,
17707      stride
17708    );
17709    this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, 0);
17710    const M = buildUserToDeviceMatrix(renderRect, rotation, wDev, hDev);
17711    const mPtr = this.memoryManager.malloc(6 * 4);
17712    const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);
17713    mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);
17714    const FLAGS = 16;
17715    let ok = false;
17716    try {
17717      if (unrotated) {
17718        ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmapUnrotated(
17719          bitmapPtr,
17720          pageCtx.pagePtr,
17721          annotPtr,
17722          mode,
17723          mPtr,
17724          FLAGS
17725        );
17726      } else {
17727        ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmap(
17728          bitmapPtr,
17729          pageCtx.pagePtr,
17730          annotPtr,
17731          mode,
17732          mPtr,
17733          FLAGS
17734        );
17735      }
17736    } finally {
17737      this.memoryManager.free(mPtr);
17738      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
17739      this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
17740      pageCtx.release();
17741    }
17742    if (!ok) {
17743      this.memoryManager.free(heapPtr);
17744      this.logger.perf(
17745        LOG_SOURCE$1,
17746        LOG_CATEGORY$1,
17747        \`RenderPageAnnotation\`,
17748        "End",
17749        \`\${doc.id}-\${page.index}-\${annotation.id}\`
17750      );
17751      return PdfTaskHelper.reject({
17752        code: PdfErrorCode.Unknown,
17753        message: "EPDF_RenderAnnotBitmap failed"
17754      });
17755    }
17756    const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);
17757    const imageDataLike = {
17758      data: new Uint8ClampedArray(data),
17759      width: wDev,
17760      height: hDev
17761    };
17762    task.resolve(imageDataLike);
17763    this.memoryManager.free(heapPtr);
17764    return task;
17765  }
17766  /**
17767   * Batch-render all annotation appearance streams for a page in one call.
17768   * Returns a map of annotation ID -> rendered appearances (Normal/Rollover/Down).
17769   * Skips annotations that have rotation + unrotatedRect (EmbedPDF-rotated)
17770   * and annotations without any appearance stream.
17771   *
17772   * @public
17773   */
17774  renderPageAnnotationsRaw(doc, page, options) {
17775    const { scaleFactor = 1, rotation = Rotation.Degree0, dpr = 1 } = options ?? {};
17776    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPageAnnotationsRaw", doc, page, options);
17777    this.logger.perf(
17778      LOG_SOURCE$1,
17779      LOG_CATEGORY$1,
17780      "RenderPageAnnotationsRaw",
17781      "Begin",
17782      \`\${doc.id}-\${page.index}\`
17783    );
17784    const ctx = this.cache.getContext(doc.id);
17785    if (!ctx) {
17786      this.logger.perf(
17787        LOG_SOURCE$1,
17788        LOG_CATEGORY$1,
17789        "RenderPageAnnotationsRaw",
17790        "End",
17791        \`\${doc.id}-\${page.index}\`
17792      );
17793      return PdfTaskHelper.reject({
17794        code: PdfErrorCode.DocNotOpen,
17795        message: "document does not open"
17796      });
17797    }
17798    const pageCtx = ctx.acquirePage(page.index);
17799    const result = {};
17800    const finalScale = Math.max(0.01, scaleFactor * dpr);
17801    const annotCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
17802    for (let i = 0; i < annotCount; i++) {
17803      const annotPtr = this.pdfiumModule.FPDFPage_GetAnnot(pageCtx.pagePtr, i);
17804      if (!annotPtr) continue;
17805      try {
17806        const nm = this.getAnnotString(annotPtr, "NM");
17807        if (!nm) continue;
17808        const extRotation = this.getAnnotExtendedRotation(annotPtr);
17809        if (extRotation !== 0) {
17810          const unrotatedRaw = this.readAnnotUnrotatedRect(annotPtr);
17811          if (unrotatedRaw) continue;
17812        }
17813        const apModes = this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(annotPtr);
17814        if (!apModes) continue;
17815        const appearances = {};
17816        const modesToRender = [
17817          { bit: AP_MODE_NORMAL, mode: AppearanceMode.Normal, key: "normal" },
17818          { bit: AP_MODE_ROLLOVER, mode: AppearanceMode.Rollover, key: "rollover" },
17819          { bit: AP_MODE_DOWN, mode: AppearanceMode.Down, key: "down" }
17820        ];
17821        for (const { bit, mode, key } of modesToRender) {
17822          if (!(apModes & bit)) continue;
17823          const rendered = this.renderSingleAnnotAppearance(
17824            doc,
17825            page,
17826            pageCtx,
17827            annotPtr,
17828            mode,
17829            rotation,
17830            finalScale
17831          );
17832          if (rendered) {
17833            appearances[key] = rendered;
17834          }
17835        }
17836        if (appearances.normal || appearances.rollover || appearances.down) {
17837          result[nm] = appearances;
17838        }
17839      } finally {
17840        this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
17841      }
17842    }
17843    pageCtx.release();
17844    this.logger.perf(
17845      LOG_SOURCE$1,
17846      LOG_CATEGORY$1,
17847      "RenderPageAnnotationsRaw",
17848      "End",
17849      \`\${doc.id}-\${page.index}\`
17850    );
17851    const task = new Task();
17852    task.resolve(result);
17853    return task;
17854  }
17855  /**
17856   * Render a single annotation's appearance for a given mode.
17857   * Returns the image data and rect, or null on failure.
17858   * @private
17859   */
17860  renderSingleAnnotAppearance(doc, page, pageCtx, annotPtr, mode, rotation, finalScale) {
17861    if (!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(annotPtr, mode)) {
17862      const subtype = this.pdfiumModule.FPDFAnnot_GetSubtype(annotPtr);
17863      if (subtype === PdfAnnotationSubtype.WIDGET && !this.pdfiumModule.FPDFAnnot_HasKey(annotPtr, "AP")) {
17864        this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotPtr);
17865        if (!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(annotPtr, mode)) {
17866          return null;
17867        }
17868      } else {
17869        return null;
17870      }
17871    }
17872    const pageRect = this.readPageAnnoRect(annotPtr);
17873    const annotRect = this.convertPageRectToDeviceRect(doc, page, pageRect);
17874    const devRect = toIntRect(transformRect(page.size, annotRect, rotation, finalScale));
17875    const wDev = Math.max(1, devRect.size.width);
17876    const hDev = Math.max(1, devRect.size.height);
17877    const stride = wDev * 4;
17878    const bytes = stride * hDev;
17879    const heapPtr = this.memoryManager.malloc(bytes);
17880    const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(
17881      wDev,
17882      hDev,
17883      4,
17884      heapPtr,
17885      stride
17886    );
17887    this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, 0);
17888    const M = buildUserToDeviceMatrix(annotRect, rotation, wDev, hDev);
17889    const mPtr = this.memoryManager.malloc(6 * 4);
17890    const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);
17891    mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);
17892    const FLAGS = 16;
17893    let ok = false;
17894    try {
17895      ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmap(
17896        bitmapPtr,
17897        pageCtx.pagePtr,
17898        annotPtr,
17899        mode,
17900        mPtr,
17901        FLAGS
17902      );
17903    } finally {
17904      this.memoryManager.free(mPtr);
17905      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
17906    }
17907    if (!ok) {
17908      this.memoryManager.free(heapPtr);
17909      return null;
17910    }
17911    const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);
17912    const imageData = {
17913      data: new Uint8ClampedArray(data),
17914      width: wDev,
17915      height: hDev
17916    };
17917    this.memoryManager.free(heapPtr);
17918    return { data: imageData, rect: annotRect };
17919  }
17920  renderRectEncoded(doc, page, rect, options) {
17921    const task = new Task();
17922    const rotation = (options == null ? void 0 : options.rotation) ?? Rotation.Degree0;
17923    const ctx = this.cache.getContext(doc.id);
17924    if (!ctx) {
17925      return PdfTaskHelper.reject({
17926        code: PdfErrorCode.DocNotOpen,
17927        message: "document does not open"
17928      });
17929    }
17930    const scale = Math.max(0.01, (options == null ? void 0 : options.scaleFactor) ?? 1);
17931    const dpr = Math.max(1, (options == null ? void 0 : options.dpr) ?? 1);
17932    const finalScale = scale * dpr;
17933    const baseW = rect.size.width;
17934    const baseH = rect.size.height;
17935    const swap2 = (rotation & 1) === 1;
17936    const wDev = Math.max(1, Math.round((swap2 ? baseH : baseW) * finalScale));
17937    const hDev = Math.max(1, Math.round((swap2 ? baseW : baseH) * finalScale));
17938    const stride = wDev * 4;
17939    const bytes = stride * hDev;
17940    const pageCtx = ctx.acquirePage(page.index);
17941    const shouldRenderForms = (options == null ? void 0 : options.withForms) ?? false;
17942    const heapPtr = this.memoryManager.malloc(bytes);
17943    const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(
17944      wDev,
17945      hDev,
17946      4,
17947      heapPtr,
17948      stride
17949    );
17950    const bgColor = (options == null ? void 0 : options.transparentBackground) ? 0 : 4294967295;
17951    this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, bgColor);
17952    const M = buildUserToDeviceMatrix(rect, rotation, wDev, hDev);
17953    const mPtr = this.memoryManager.malloc(6 * 4);
17954    const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);
17955    mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);
17956    const clipPtr = this.memoryManager.malloc(4 * 4);
17957    const clipView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, clipPtr, 4);
17958    clipView.set([0, 0, wDev, hDev]);
17959    let flags = 16;
17960    if ((options == null ? void 0 : options.withAnnotations) ?? false) flags |= 1;
17961    try {
17962      this.pdfiumModule.FPDF_RenderPageBitmapWithMatrix(
17963        bitmapPtr,
17964        pageCtx.pagePtr,
17965        mPtr,
17966        clipPtr,
17967        flags
17968      );
17969      if (shouldRenderForms) {
17970        pageCtx.withFormHandle((formHandle) => {
17971          const formParams = computeFormDrawParams(M, rect, page.size, rotation);
17972          const { startX, startY, formsWidth, formsHeight } = formParams;
17973          this.pdfiumModule.FPDF_FFLDraw(
17974            formHandle,
17975            bitmapPtr,
17976            pageCtx.pagePtr,
17977            startX,
17978            startY,
17979            formsWidth,
17980            formsHeight,
17981            rotation,
17982            flags
17983          );
17984        });
17985      }
17986    } finally {
17987      pageCtx.release();
17988      this.memoryManager.free(mPtr);
17989      this.memoryManager.free(clipPtr);
17990    }
17991    this.logger.perf(
17992      LOG_SOURCE$1,
17993      LOG_CATEGORY$1,
17994      \`RenderRectEncodedData\`,
17995      "Begin",
17996      \`\${doc.id}-\${page.index}\`
17997    );
17998    const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);
17999    this.logger.perf(
18000      LOG_SOURCE$1,
18001      LOG_CATEGORY$1,
18002      \`RenderRectEncodedData\`,
18003      "End",
18004      \`\${doc.id}-\${page.index}\`
18005    );
18006    this.logger.perf(
18007      LOG_SOURCE$1,
18008      LOG_CATEGORY$1,
18009      \`RenderRectEncodedImageData\`,
18010      "Begin",
18011      \`\${doc.id}-\${page.index}\`
18012    );
18013    const imageDataLike = {
18014      data: new Uint8ClampedArray(data),
18015      width: wDev,
18016      height: hDev
18017    };
18018    this.logger.perf(
18019      LOG_SOURCE$1,
18020      LOG_CATEGORY$1,
18021      \`RenderRectEncodedImageData\`,
18022      "End",
18023      \`\${doc.id}-\${page.index}\`
18024    );
18025    task.resolve(imageDataLike);
18026    this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
18027    this.memoryManager.free(heapPtr);
18028    return task;
18029  }
18030  /**
18031   * Read the target of pdf link annotation
18032   * @param docPtr - pointer to pdf document object
18033   * @param getActionPtr - callback function to retrive the pointer of action
18034   * @param getDestinationPtr - callback function to retrive the pointer of destination
18035   * @returns target of link
18036   *
18037   * @private
18038   */
18039  readPdfLinkAnnoTarget(docPtr, getActionPtr, getDestinationPtr) {
18040    const destinationPtr = getDestinationPtr();
18041    if (destinationPtr) {
18042      const destination = this.readPdfDestination(docPtr, destinationPtr);
18043      return {
18044        type: "destination",
18045        destination
18046      };
18047    } else {
18048      const actionPtr = getActionPtr();
18049      if (actionPtr) {
18050        const action = this.readPdfAction(docPtr, actionPtr);
18051        return {
18052          type: "action",
18053          action
18054        };
18055      }
18056    }
18057  }
18058  createLocalDestPtr(docPtr, dest) {
18059    var _a, _b;
18060    const pagePtr = this.pdfiumModule.FPDF_LoadPage(docPtr, dest.pageIndex);
18061    if (!pagePtr) return 0;
18062    try {
18063      if (dest.zoom.mode === PdfZoomMode.XYZ) {
18064        const { x, y, zoom } = dest.zoom.params;
18065        return this.pdfiumModule.EPDFDest_CreateXYZ(
18066          pagePtr,
18067          /*has_left*/
18068          true,
18069          x,
18070          /*has_top*/
18071          true,
18072          y,
18073          /*has_zoom*/
18074          true,
18075          zoom
18076        );
18077      }
18078      let viewEnum;
18079      let params = [];
18080      switch (dest.zoom.mode) {
18081        case PdfZoomMode.FitPage:
18082          viewEnum = PdfZoomMode.FitPage;
18083          break;
18084        case PdfZoomMode.FitHorizontal:
18085          viewEnum = PdfZoomMode.FitHorizontal;
18086          params = [((_a = dest.view) == null ? void 0 : _a[0]) ?? 0];
18087          break;
18088        case PdfZoomMode.FitVertical:
18089          viewEnum = PdfZoomMode.FitVertical;
18090          params = [((_b = dest.view) == null ? void 0 : _b[0]) ?? 0];
18091          break;
18092        case PdfZoomMode.FitRectangle:
18093          {
18094            const v = dest.view ?? [];
18095            params = [v[0] ?? 0, v[1] ?? 0, v[2] ?? 0, v[3] ?? 0];
18096            viewEnum = PdfZoomMode.FitRectangle;
18097          }
18098          break;
18099        case PdfZoomMode.Unknown:
18100        default:
18101          return 0;
18102      }
18103      return this.withFloatArray(
18104        params,
18105        (ptr, count) => this.pdfiumModule.EPDFDest_CreateView(pagePtr, viewEnum, ptr, count)
18106      );
18107    } finally {
18108      this.pdfiumModule.FPDF_ClosePage(pagePtr);
18109    }
18110  }
18111  applyBookmarkTarget(docPtr, bmPtr, target) {
18112    if (target.type === "destination") {
18113      const destPtr = this.createLocalDestPtr(docPtr, target.destination);
18114      if (!destPtr) return false;
18115      const ok = this.pdfiumModule.EPDFBookmark_SetDest(docPtr, bmPtr, destPtr);
18116      return !!ok;
18117    }
18118    const action = target.action;
18119    switch (action.type) {
18120      case PdfActionType.Goto: {
18121        const destPtr = this.createLocalDestPtr(docPtr, action.destination);
18122        if (!destPtr) return false;
18123        const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);
18124        if (!actPtr) return false;
18125        return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);
18126      }
18127      case PdfActionType.URI: {
18128        const actPtr = this.pdfiumModule.EPDFAction_CreateURI(docPtr, action.uri);
18129        if (!actPtr) return false;
18130        return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);
18131      }
18132      case PdfActionType.LaunchAppOrOpenFile: {
18133        const actPtr = this.withWString(
18134          action.path,
18135          (wptr) => this.pdfiumModule.EPDFAction_CreateLaunch(docPtr, wptr)
18136        );
18137        if (!actPtr) return false;
18138        return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);
18139      }
18140      case PdfActionType.RemoteGoto:
18141        return false;
18142      case PdfActionType.Unsupported:
18143      default:
18144        return false;
18145    }
18146  }
18147  /**
18148   * Apply a link target (action or destination) to a link annotation
18149   * @param docPtr - pointer to pdf document
18150   * @param annotationPtr - pointer to the link annotation
18151   * @param target - the link target to apply
18152   * @returns true if successful
18153   *
18154   * @private
18155   */
18156  applyLinkTarget(docPtr, annotationPtr, target) {
18157    if (target.type === "destination") {
18158      const destPtr = this.createLocalDestPtr(docPtr, target.destination);
18159      if (!destPtr) return false;
18160      const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);
18161      if (!actPtr) return false;
18162      return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);
18163    }
18164    const action = target.action;
18165    switch (action.type) {
18166      case PdfActionType.Goto: {
18167        const destPtr = this.createLocalDestPtr(docPtr, action.destination);
18168        if (!destPtr) return false;
18169        const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);
18170        if (!actPtr) return false;
18171        return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);
18172      }
18173      case PdfActionType.URI: {
18174        const actPtr = this.pdfiumModule.EPDFAction_CreateURI(docPtr, action.uri);
18175        if (!actPtr) return false;
18176        return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);
18177      }
18178      case PdfActionType.LaunchAppOrOpenFile: {
18179        const actPtr = this.withWString(
18180          action.path,
18181          (wptr) => this.pdfiumModule.EPDFAction_CreateLaunch(docPtr, wptr)
18182        );
18183        if (!actPtr) return false;
18184        return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);
18185      }
18186      case PdfActionType.RemoteGoto:
18187      case PdfActionType.Unsupported:
18188      default:
18189        return false;
18190    }
18191  }
18192  /**
18193   * Read pdf action from pdf document
18194   * @param docPtr - pointer to pdf document object
18195   * @param actionPtr - pointer to pdf action object
18196   * @returns pdf action object
18197   *
18198   * @private
18199   */
18200  readPdfAction(docPtr, actionPtr) {
18201    const actionType = this.pdfiumModule.FPDFAction_GetType(actionPtr);
18202    let action;
18203    switch (actionType) {
18204      case PdfActionType.Unsupported:
18205        action = {
18206          type: PdfActionType.Unsupported
18207        };
18208        break;
18209      case PdfActionType.Goto:
18210        {
18211          const destinationPtr = this.pdfiumModule.FPDFAction_GetDest(docPtr, actionPtr);
18212          if (destinationPtr) {
18213            const destination = this.readPdfDestination(docPtr, destinationPtr);
18214            action = {
18215              type: PdfActionType.Goto,
18216              destination
18217            };
18218          } else {
18219            action = {
18220              type: PdfActionType.Unsupported
18221            };
18222          }
18223        }
18224        break;
18225      case PdfActionType.RemoteGoto:
18226        {
18227          action = {
18228            type: PdfActionType.Unsupported
18229          };
18230        }
18231        break;
18232      case PdfActionType.URI:
18233        {
18234          const uri = readString(
18235            this.pdfiumModule.pdfium,
18236            (buffer, bufferLength) => {
18237              return this.pdfiumModule.FPDFAction_GetURIPath(
18238                docPtr,
18239                actionPtr,
18240                buffer,
18241                bufferLength
18242              );
18243            },
18244            this.pdfiumModule.pdfium.UTF8ToString
18245          );
18246          action = {
18247            type: PdfActionType.URI,
18248            uri
18249          };
18250        }
18251        break;
18252      case PdfActionType.LaunchAppOrOpenFile:
18253        {
18254          const path = readString(
18255            this.pdfiumModule.pdfium,
18256            (buffer, bufferLength) => {
18257              return this.pdfiumModule.FPDFAction_GetFilePath(actionPtr, buffer, bufferLength);
18258            },
18259            this.pdfiumModule.pdfium.UTF8ToString
18260          );
18261          action = {
18262            type: PdfActionType.LaunchAppOrOpenFile,
18263            path
18264          };
18265        }
18266        break;
18267    }
18268    return action;
18269  }
18270  /**
18271   * Read pdf destination object
18272   * @param docPtr - pointer to pdf document object
18273   * @param destinationPtr - pointer to pdf destination
18274   * @returns pdf destination object
18275   *
18276   * @private
18277   */
18278  readPdfDestination(docPtr, destinationPtr) {
18279    const pageIndex = this.pdfiumModule.FPDFDest_GetDestPageIndex(docPtr, destinationPtr);
18280    const maxParmamsCount = 4;
18281    const paramsCountPtr = this.memoryManager.malloc(maxParmamsCount);
18282    const paramsPtr = this.memoryManager.malloc(maxParmamsCount * 4);
18283    const zoomMode = this.pdfiumModule.FPDFDest_GetView(
18284      destinationPtr,
18285      paramsCountPtr,
18286      paramsPtr
18287    );
18288    const paramsCount = this.pdfiumModule.pdfium.getValue(paramsCountPtr, "i32");
18289    const view = [];
18290    for (let i = 0; i < paramsCount; i++) {
18291      const paramPtr = paramsPtr + i * 4;
18292      view.push(this.pdfiumModule.pdfium.getValue(paramPtr, "float"));
18293    }
18294    this.memoryManager.free(paramsCountPtr);
18295    this.memoryManager.free(paramsPtr);
18296    if (zoomMode === PdfZoomMode.XYZ) {
18297      const hasXPtr = this.memoryManager.malloc(1);
18298      const hasYPtr = this.memoryManager.malloc(1);
18299      const hasZPtr = this.memoryManager.malloc(1);
18300      const xPtr = this.memoryManager.malloc(4);
18301      const yPtr = this.memoryManager.malloc(4);
18302      const zPtr = this.memoryManager.malloc(4);
18303      const isSucceed = this.pdfiumModule.FPDFDest_GetLocationInPage(
18304        destinationPtr,
18305        hasXPtr,
18306        hasYPtr,
18307        hasZPtr,
18308        xPtr,
18309        yPtr,
18310        zPtr
18311      );
18312      if (isSucceed) {
18313        const hasX = this.pdfiumModule.pdfium.getValue(hasXPtr, "i8");
18314        const hasY = this.pdfiumModule.pdfium.getValue(hasYPtr, "i8");
18315        const hasZ = this.pdfiumModule.pdfium.getValue(hasZPtr, "i8");
18316        const x = hasX ? this.pdfiumModule.pdfium.getValue(xPtr, "float") : 0;
18317        const y = hasY ? this.pdfiumModule.pdfium.getValue(yPtr, "float") : 0;
18318        const zoom = hasZ ? this.pdfiumModule.pdfium.getValue(zPtr, "float") : 0;
18319        this.memoryManager.free(hasXPtr);
18320        this.memoryManager.free(hasYPtr);
18321        this.memoryManager.free(hasZPtr);
18322        this.memoryManager.free(xPtr);
18323        this.memoryManager.free(yPtr);
18324        this.memoryManager.free(zPtr);
18325        return {
18326          pageIndex,
18327          zoom: {
18328            mode: zoomMode,
18329            params: {
18330              x,
18331              y,
18332              zoom
18333            }
18334          },
18335          view
18336        };
18337      }
18338      this.memoryManager.free(hasXPtr);
18339      this.memoryManager.free(hasYPtr);
18340      this.memoryManager.free(hasZPtr);
18341      this.memoryManager.free(xPtr);
18342      this.memoryManager.free(yPtr);
18343      this.memoryManager.free(zPtr);
18344      return {
18345        pageIndex,
18346        zoom: {
18347          mode: zoomMode,
18348          params: {
18349            x: 0,
18350            y: 0,
18351            zoom: 0
18352          }
18353        },
18354        view
18355      };
18356    }
18357    return {
18358      pageIndex,
18359      zoom: {
18360        mode: zoomMode
18361      },
18362      view
18363    };
18364  }
18365  /**
18366   * Read attachmet from pdf document
18367   * @param docPtr - pointer to pdf document object
18368   * @param index - index of attachment
18369   * @returns attachment content
18370   *
18371   * @private
18372   */
18373  readPdfAttachment(docPtr, index) {
18374    const attachmentPtr = this.pdfiumModule.FPDFDoc_GetAttachment(docPtr, index);
18375    const name = readString(
18376      this.pdfiumModule.pdfium,
18377      (buffer, bufferLength) => {
18378        return this.pdfiumModule.FPDFAttachment_GetName(attachmentPtr, buffer, bufferLength);
18379      },
18380      this.pdfiumModule.pdfium.UTF16ToString
18381    );
18382    const description = readString(
18383      this.pdfiumModule.pdfium,
18384      (buffer, bufferLength) => {
18385        return this.pdfiumModule.EPDFAttachment_GetDescription(attachmentPtr, buffer, bufferLength);
18386      },
18387      this.pdfiumModule.pdfium.UTF16ToString
18388    );
18389    const mimeType = readString(
18390      this.pdfiumModule.pdfium,
18391      (buffer, bufferLength) => {
18392        return this.pdfiumModule.FPDFAttachment_GetSubtype(attachmentPtr, buffer, bufferLength);
18393      },
18394      this.pdfiumModule.pdfium.UTF16ToString
18395    );
18396    const creationDate = this.getAttachmentDate(attachmentPtr, "CreationDate");
18397    const checksum = readString(
18398      this.pdfiumModule.pdfium,
18399      (buffer, bufferLength) => {
18400        return this.pdfiumModule.FPDFAttachment_GetStringValue(
18401          attachmentPtr,
18402          "Checksum",
18403          buffer,
18404          bufferLength
18405        );
18406      },
18407      this.pdfiumModule.pdfium.UTF16ToString
18408    );
18409    const size = this.getAttachmentNumber(attachmentPtr, "Size");
18410    return {
18411      index,
18412      name,
18413      description,
18414      mimeType,
18415      size,
18416      creationDate,
18417      checksum
18418    };
18419  }
18420  /**
18421   * Convert coordinate of point from device coordinate to page coordinate
18422   * @param doc - pdf document object
18423   * @param page  - pdf page infor
18424   * @param position - position of point
18425   * @returns converted position
18426   *
18427   * @private
18428   */
18429  convertDevicePointToPagePoint(doc, page, position) {
18430    const DW = page.size.width;
18431    const DH = page.size.height;
18432    const r = doc.normalizedRotation ? 0 : page.rotation & 3;
18433    if (r === 0) {
18434      return { x: position.x, y: DH - position.y };
18435    }
18436    if (r === 1) {
18437      return { x: position.y, y: position.x };
18438    }
18439    if (r === 2) {
18440      return { x: DW - position.x, y: position.y };
18441    }
18442    {
18443      return { x: DH - position.y, y: DW - position.x };
18444    }
18445  }
18446  /**
18447   * Convert coordinate of point from page coordinate to device coordinate
18448   * @param doc - pdf document object
18449   * @param page  - pdf page infor
18450   * @param position - position of point
18451   * @returns converted position
18452   *
18453   * @private
18454   */
18455  convertPagePointToDevicePoint(doc, page, position) {
18456    const DW = page.size.width;
18457    const DH = page.size.height;
18458    const r = doc.normalizedRotation ? 0 : page.rotation & 3;
18459    if (r === 0) {
18460      return { x: position.x, y: DH - position.y };
18461    }
18462    if (r === 1) {
18463      return { x: position.y, y: position.x };
18464    }
18465    if (r === 2) {
18466      return { x: DW - position.x, y: position.y };
18467    }
18468    {
18469      return { x: DW - position.y, y: DH - position.x };
18470    }
18471  }
18472  /**
18473   * Convert coordinate of rectangle from page coordinate to device coordinate
18474   * @param doc - pdf document object
18475   * @param page  - pdf page infor
18476   * @param pagePtr - pointer to pdf page object
18477   * @param pageRect - rectangle that needs to be converted
18478   * @returns converted rectangle
18479   *
18480   * @private
18481   */
18482  convertPageRectToDeviceRect(doc, page, pageRect) {
18483    const { x, y } = this.convertPagePointToDevicePoint(doc, page, {
18484      x: pageRect.left,
18485      y: pageRect.top
18486    });
18487    const rect = {
18488      origin: {
18489        x,
18490        y
18491      },
18492      size: {
18493        width: Math.abs(pageRect.right - pageRect.left),
18494        height: Math.abs(pageRect.top - pageRect.bottom)
18495      }
18496    };
18497    return rect;
18498  }
18499  /**
18500   * Read the appearance stream of annotation
18501   * @param annotationPtr - pointer to pdf annotation
18502   * @param mode - appearance mode
18503   * @returns appearance stream
18504   *
18505   * @private
18506   */
18507  readPageAnnoAppearanceStreams(annotationPtr) {
18508    return {
18509      normal: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Normal),
18510      rollover: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Rollover),
18511      down: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Down)
18512    };
18513  }
18514  /**
18515   * Read the appearance stream of annotation
18516   * @param annotationPtr - pointer to pdf annotation
18517   * @param mode - appearance mode
18518   * @returns appearance stream
18519   *
18520   * @private
18521   */
18522  readPageAnnoAppearanceStream(annotationPtr, mode = AppearanceMode.Normal) {
18523    const utf16Length = this.pdfiumModule.FPDFAnnot_GetAP(annotationPtr, mode, 0, 0);
18524    const bytesCount = (utf16Length + 1) * 2;
18525    const bufferPtr = this.memoryManager.malloc(bytesCount);
18526    this.pdfiumModule.FPDFAnnot_GetAP(annotationPtr, mode, bufferPtr, bytesCount);
18527    const ap = this.pdfiumModule.pdfium.UTF16ToString(bufferPtr);
18528    this.memoryManager.free(bufferPtr);
18529    return ap;
18530  }
18531  /**
18532   * Set the appearance stream of annotation
18533   * @param annotationPtr - pointer to pdf annotation
18534   * @param mode - appearance mode
18535   * @param apContent - appearance stream content (null to remove)
18536   * @returns whether the appearance stream was set successfully
18537   *
18538   * @private
18539   */
18540  setPageAnnoAppearanceStream(annotationPtr, mode = AppearanceMode.Normal, apContent) {
18541    const bytes = 2 * (apContent.length + 1);
18542    const ptr = this.memoryManager.malloc(bytes);
18543    try {
18544      this.pdfiumModule.pdfium.stringToUTF16(apContent, ptr, bytes);
18545      const ok = this.pdfiumModule.FPDFAnnot_SetAP(annotationPtr, mode, ptr);
18546      return !!ok;
18547    } finally {
18548      this.memoryManager.free(ptr);
18549    }
18550  }
18551  /**
18552   * Set the rect of specified annotation
18553   * @param doc - pdf document object
18554   * @param page - page info that the annotation is belonged to
18555   * @param annotationPtr - pointer to annotation object
18556   * @param rect - target rectangle
18557   * @returns whether the rect is setted
18558   *
18559   * @private
18560   */
18561  setPageAnnoRect(doc, page, annotPtr, rect) {
18562    const x0d = rect.origin.x;
18563    const y0d = rect.origin.y;
18564    const x1d = rect.origin.x + rect.size.width;
18565    const y1d = rect.origin.y + rect.size.height;
18566    const TL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y0d });
18567    const TR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y0d });
18568    const BR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y1d });
18569    const BL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y1d });
18570    let left = Math.min(TL.x, TR.x, BR.x, BL.x);
18571    let right = Math.max(TL.x, TR.x, BR.x, BL.x);
18572    let bottom = Math.min(TL.y, TR.y, BR.y, BL.y);
18573    let top = Math.max(TL.y, TR.y, BR.y, BL.y);
18574    if (left > right) [left, right] = [right, left];
18575    if (bottom > top) [bottom, top] = [top, bottom];
18576    const ptr = this.memoryManager.malloc(16);
18577    const pdf = this.pdfiumModule.pdfium;
18578    pdf.setValue(ptr + 0, left, "float");
18579    pdf.setValue(ptr + 4, top, "float");
18580    pdf.setValue(ptr + 8, right, "float");
18581    pdf.setValue(ptr + 12, bottom, "float");
18582    const ok = this.pdfiumModule.FPDFAnnot_SetRect(annotPtr, ptr);
18583    this.memoryManager.free(ptr);
18584    return !!ok;
18585  }
18586  /**
18587   * Read the rectangle of annotation
18588   * @param annotationPtr - pointer to pdf annotation
18589   * @returns rectangle of annotation
18590   *
18591   * @private
18592   */
18593  readPageAnnoRect(annotationPtr) {
18594    const pageRectPtr = this.memoryManager.malloc(4 * 4);
18595    const pageRect = {
18596      left: 0,
18597      top: 0,
18598      right: 0,
18599      bottom: 0
18600    };
18601    if (this.pdfiumModule.EPDFAnnot_GetRect(annotationPtr, pageRectPtr)) {
18602      pageRect.left = this.pdfiumModule.pdfium.getValue(pageRectPtr, "float");
18603      pageRect.top = this.pdfiumModule.pdfium.getValue(pageRectPtr + 4, "float");
18604      pageRect.right = this.pdfiumModule.pdfium.getValue(pageRectPtr + 8, "float");
18605      pageRect.bottom = this.pdfiumModule.pdfium.getValue(pageRectPtr + 12, "float");
18606    }
18607    this.memoryManager.free(pageRectPtr);
18608    return pageRect;
18609  }
18610  /**
18611   * Get highlight rects for a specific character range (for search highlighting)
18612   * @param doc - pdf document object
18613   * @param page - pdf page info
18614   * @param pagePtr - pointer to pdf page
18615   * @param textPagePtr - pointer to pdf text page
18616   * @param startIndex - starting character index
18617   * @param charCount - number of characters in the range
18618   * @returns array of rectangles for highlighting the specified character range
18619   *
18620   * @private
18621   */
18622  getHighlightRects(doc, page, textPagePtr, startIndex, charCount) {
18623    const rectsCount = this.pdfiumModule.FPDFText_CountRects(textPagePtr, startIndex, charCount);
18624    const highlightRects = [];
18625    const l = this.memoryManager.malloc(8);
18626    const t = this.memoryManager.malloc(8);
18627    const r = this.memoryManager.malloc(8);
18628    const b = this.memoryManager.malloc(8);
18629    for (let i = 0; i < rectsCount; i++) {
18630      const ok = this.pdfiumModule.FPDFText_GetRect(textPagePtr, i, l, t, r, b);
18631      if (!ok) continue;
18632      const left = this.pdfiumModule.pdfium.getValue(l, "double");
18633      const top = this.pdfiumModule.pdfium.getValue(t, "double");
18634      const right = this.pdfiumModule.pdfium.getValue(r, "double");
18635      const bottom = this.pdfiumModule.pdfium.getValue(b, "double");
18636      const p1 = this.convertPagePointToDevicePoint(doc, page, { x: left, y: top });
18637      const p2 = this.convertPagePointToDevicePoint(doc, page, { x: right, y: top });
18638      const p3 = this.convertPagePointToDevicePoint(doc, page, { x: right, y: bottom });
18639      const p4 = this.convertPagePointToDevicePoint(doc, page, { x: left, y: bottom });
18640      const xs = [p1.x, p2.x, p3.x, p4.x];
18641      const ys = [p1.y, p2.y, p3.y, p4.y];
18642      const x = Math.min(...xs);
18643      const y = Math.min(...ys);
18644      const width = Math.max(...xs) - x;
18645      const height = Math.max(...ys) - y;
18646      highlightRects.push({
18647        origin: { x, y },
18648        size: { width: Math.ceil(width), height: Math.ceil(height) }
18649      });
18650    }
18651    this.memoryManager.free(l);
18652    this.memoryManager.free(t);
18653    this.memoryManager.free(r);
18654    this.memoryManager.free(b);
18655    return highlightRects;
18656  }
18657  /**
18658   * {@inheritDoc @embedpdf/models!PdfEngine.searchAllPages}
18659   *
18660   * Runs inside the worker.
18661   * Emits per-page progress: { page, results }
18662   *
18663   * @public
18664   */
18665  searchInPage(doc, page, keyword, flags) {
18666    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "searchInPage", doc, page, keyword, flags);
18667    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SearchInPage\`, "Begin", \`\${doc.id}-\${page.index}\`);
18668    const ctx = this.cache.getContext(doc.id);
18669    if (!ctx) {
18670      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18671      return PdfTaskHelper.reject({
18672        code: PdfErrorCode.DocNotOpen,
18673        message: "Document is not open"
18674      });
18675    }
18676    const length = 2 * (keyword.length + 1);
18677    const keywordPtr = this.memoryManager.malloc(length);
18678    this.pdfiumModule.pdfium.stringToUTF16(keyword, keywordPtr, length);
18679    try {
18680      const results = this.searchAllInPage(doc, ctx, page, keywordPtr, flags);
18681      return PdfTaskHelper.resolve(results);
18682    } finally {
18683      this.memoryManager.free(keywordPtr);
18684    }
18685  }
18686  /**
18687   * Get annotations for multiple pages in a single batch.
18688   * Emits progress per page for streaming updates.
18689   *
18690   * @param doc - PDF document
18691   * @param pages - Array of pages to process
18692   * @returns Task with results keyed by page index, with per-page progress
18693   *
18694   * @public
18695   */
18696  getAnnotationsBatch(doc, pages) {
18697    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getAnnotationsBatch", doc.id, pages.length);
18698    const task = new Task();
18699    queueMicrotask(() => {
18700      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetAnnotationsBatch", "Begin", doc.id);
18701      const ctx = this.cache.getContext(doc.id);
18702      if (!ctx) {
18703        task.reject({ code: PdfErrorCode.DocNotOpen, message: "Document is not open" });
18704        return;
18705      }
18706      const results = {};
18707      const total = pages.length;
18708      const formInfoPtr = this.pdfiumModule.PDFiumExt_OpenFormFillInfo();
18709      const formHandle = this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(
18710        ctx.docPtr,
18711        formInfoPtr
18712      );
18713      try {
18714        for (let i = 0; i < pages.length; i++) {
18715          const page = pages[i];
18716          const annotations = this.readPageAnnotationsRaw(doc, ctx, page, formHandle);
18717          results[page.index] = annotations;
18718          task.progress({
18719            pageIndex: page.index,
18720            result: annotations,
18721            completed: i + 1,
18722            total
18723          });
18724        }
18725      } finally {
18726        this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);
18727        this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formInfoPtr);
18728      }
18729      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetAnnotationsBatch", "End", doc.id);
18730      task.resolve(results);
18731    });
18732    return task;
18733  }
18734  /**
18735   * Search across multiple pages in a single batch.
18736   * Emits progress per page for streaming updates.
18737   *
18738   * @param doc - PDF document
18739   * @param pages - Array of pages to search
18740   * @param keyword - Search keyword
18741   * @param flags - Search flags
18742   * @returns Task with results keyed by page index, with per-page progress
18743   *
18744   * @public
18745   */
18746  searchBatch(doc, pages, keyword, flags) {
18747    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "searchBatch", doc.id, pages.length, keyword);
18748    const task = new Task();
18749    queueMicrotask(() => {
18750      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SearchBatch", "Begin", doc.id);
18751      const ctx = this.cache.getContext(doc.id);
18752      if (!ctx) {
18753        task.reject({ code: PdfErrorCode.DocNotOpen, message: "Document is not open" });
18754        return;
18755      }
18756      const length = 2 * (keyword.length + 1);
18757      const keywordPtr = this.memoryManager.malloc(length);
18758      this.pdfiumModule.pdfium.stringToUTF16(keyword, keywordPtr, length);
18759      try {
18760        const results = {};
18761        const total = pages.length;
18762        for (let i = 0; i < pages.length; i++) {
18763          const page = pages[i];
18764          const pageResults = this.searchAllInPage(doc, ctx, page, keywordPtr, flags);
18765          results[page.index] = pageResults;
18766          task.progress({
18767            pageIndex: page.index,
18768            result: pageResults,
18769            completed: i + 1,
18770            total
18771          });
18772        }
18773        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SearchBatch", "End", doc.id);
18774        task.resolve(results);
18775      } finally {
18776        this.memoryManager.free(keywordPtr);
18777      }
18778    });
18779    return task;
18780  }
18781  /**
18782   * Extract word-aligned context for a search hit.
18783   *
18784   * @param fullText      full UTF-16 page text (fetch this once per page!)
18785   * @param start         index of 1st char that matched
18786   * @param count         number of chars in the match
18787   * @param windowChars   minimum context chars to keep left & right
18788   */
18789  buildContext(fullText, start, count, windowChars = 30) {
18790    const WORD_BREAK = /[\\s\\u00A0.,;:!?()\\[\\]{}<>/\\\\\\-"'\`"”\\u2013\\u2014]/;
18791    const findWordStart = (index) => {
18792      while (index > 0 && !WORD_BREAK.test(fullText[index - 1])) index--;
18793      return index;
18794    };
18795    const findWordEnd = (index) => {
18796      while (index < fullText.length && !WORD_BREAK.test(fullText[index])) index++;
18797      return index;
18798    };
18799    let left = start;
18800    while (left > 0 && WORD_BREAK.test(fullText[left - 1])) left--;
18801    let collected = 0;
18802    while (left > 0 && collected < windowChars) {
18803      left--;
18804      if (!WORD_BREAK.test(fullText[left])) collected++;
18805    }
18806    left = findWordStart(left);
18807    let right = start + count;
18808    while (right < fullText.length && WORD_BREAK.test(fullText[right])) right++;
18809    collected = 0;
18810    while (right < fullText.length && collected < windowChars) {
18811      if (!WORD_BREAK.test(fullText[right])) collected++;
18812      right++;
18813    }
18814    right = findWordEnd(right);
18815    const before = fullText.slice(left, start).replace(/\\s+/g, " ").trimStart();
18816    const match = fullText.slice(start, start + count);
18817    const after = fullText.slice(start + count, right).replace(/\\s+/g, " ").trimEnd();
18818    return {
18819      before: this.tidy(before),
18820      match: this.tidy(match),
18821      after: this.tidy(after),
18822      truncatedLeft: left > 0,
18823      truncatedRight: right < fullText.length
18824    };
18825  }
18826  /**
18827   * Tidy the text to remove any non-printable characters and whitespace
18828   * @param s - text to tidy
18829   * @returns tidied text
18830   *
18831   * @private
18832   */
18833  tidy(s) {
18834    return s.replace(/-\\uFFFE\\s*/g, "").replace(/[\\uFFFE\\u00AD\\u200B\\u2060\\uFEFF]/g, "").replace(/\\s+/g, " ");
18835  }
18836  /**
18837   * Search for all occurrences of a keyword on a single page
18838   * This method efficiently loads the page only once and finds all matches
18839   *
18840   * @param docPtr - pointer to pdf document
18841   * @param page - pdf page object
18842   * @param pageIndex - index of the page
18843   * @param keywordPtr - pointer to the search keyword
18844   * @param flag - search flags
18845   * @returns array of search results on this page
18846   *
18847   * @private
18848   */
18849  searchAllInPage(doc, ctx, page, keywordPtr, flag) {
18850    return ctx.borrowPage(page.index, (pageCtx) => {
18851      const textPagePtr = pageCtx.getTextPage();
18852      const total = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
18853      const bufPtr = this.memoryManager.malloc(2 * (total + 1));
18854      this.pdfiumModule.FPDFText_GetText(textPagePtr, 0, total, bufPtr);
18855      const fullText = this.pdfiumModule.pdfium.UTF16ToString(bufPtr);
18856      this.memoryManager.free(bufPtr);
18857      const pageResults = [];
18858      const searchHandle = this.pdfiumModule.FPDFText_FindStart(
18859        textPagePtr,
18860        keywordPtr,
18861        flag,
18862        0
18863        // Start from the beginning of the page
18864      );
18865      while (this.pdfiumModule.FPDFText_FindNext(searchHandle)) {
18866        const charIndex = this.pdfiumModule.FPDFText_GetSchResultIndex(searchHandle);
18867        const charCount = this.pdfiumModule.FPDFText_GetSchCount(searchHandle);
18868        const rects = this.getHighlightRects(doc, page, textPagePtr, charIndex, charCount);
18869        const context = this.buildContext(fullText, charIndex, charCount);
18870        pageResults.push({
18871          pageIndex: page.index,
18872          charIndex,
18873          charCount,
18874          rects,
18875          context
18876        });
18877      }
18878      this.pdfiumModule.FPDFText_FindClose(searchHandle);
18879      return pageResults;
18880    });
18881  }
18882  /**
18883   * {@inheritDoc @embedpdf/models!PdfEngine.preparePrintDocument}
18884   *
18885   * Prepares a PDF document for printing with specified options.
18886   * Creates a new document with selected pages and optionally removes annotations
18887   * for optimal printing performance.
18888   *
18889   * @public
18890   */
18891  preparePrintDocument(doc, options) {
18892    const { includeAnnotations = true, pageRange = null } = options ?? {};
18893    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "preparePrintDocument", doc, options);
18894    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "Begin", doc.id);
18895    const ctx = this.cache.getContext(doc.id);
18896    if (!ctx) {
18897      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18898      return PdfTaskHelper.reject({
18899        code: PdfErrorCode.DocNotOpen,
18900        message: "Document is not open"
18901      });
18902    }
18903    const printDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();
18904    if (!printDocPtr) {
18905      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18906      return PdfTaskHelper.reject({
18907        code: PdfErrorCode.CantCreateNewDoc,
18908        message: "Cannot create print document"
18909      });
18910    }
18911    try {
18912      const sanitizedPageRange = this.sanitizePageRange(pageRange, doc.pageCount);
18913      if (!this.pdfiumModule.FPDF_ImportPages(
18914        printDocPtr,
18915        ctx.docPtr,
18916        sanitizedPageRange ?? "",
18917        0
18918        // Insert at beginning
18919      )) {
18920        this.pdfiumModule.FPDF_CloseDocument(printDocPtr);
18921        this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "Failed to import pages for printing");
18922        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18923        return PdfTaskHelper.reject({
18924          code: PdfErrorCode.CantImportPages,
18925          message: "Failed to import pages for printing"
18926        });
18927      }
18928      if (!includeAnnotations) {
18929        const removalResult = this.removeAnnotationsFromPrintDocument(printDocPtr);
18930        if (!removalResult.success) {
18931          this.pdfiumModule.FPDF_CloseDocument(printDocPtr);
18932          this.logger.error(
18933            LOG_SOURCE$1,
18934            LOG_CATEGORY$1,
18935            \`Failed to remove annotations: \${removalResult.error}\`
18936          );
18937          this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18938          return PdfTaskHelper.reject({
18939            code: PdfErrorCode.Unknown,
18940            message: \`Failed to prepare print document: \${removalResult.error}\`
18941          });
18942        }
18943        this.logger.debug(
18944          LOG_SOURCE$1,
18945          LOG_CATEGORY$1,
18946          \`Removed \${removalResult.annotationsRemoved} annotations from \${removalResult.pagesProcessed} pages\`
18947        );
18948      }
18949      const buffer = this.saveDocument(printDocPtr);
18950      this.pdfiumModule.FPDF_CloseDocument(printDocPtr);
18951      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18952      return PdfTaskHelper.resolve(buffer);
18953    } catch (error) {
18954      if (printDocPtr) {
18955        this.pdfiumModule.FPDF_CloseDocument(printDocPtr);
18956      }
18957      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "preparePrintDocument failed", error);
18958      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18959      return PdfTaskHelper.reject({
18960        code: PdfErrorCode.Unknown,
18961        message: error instanceof Error ? error.message : "Failed to prepare print document"
18962      });
18963    }
18964  }
18965  /**
18966   * Removes all annotations from a print document using fast raw annotation functions.
18967   * This method is optimized for performance by avoiding full page loading.
18968   *
18969   * @param printDocPtr - Pointer to the print document
18970   * @returns Result object with success status and statistics
18971   *
18972   * @private
18973   */
18974  removeAnnotationsFromPrintDocument(printDocPtr) {
18975    let totalAnnotationsRemoved = 0;
18976    let pagesProcessed = 0;
18977    try {
18978      const pageCount = this.pdfiumModule.FPDF_GetPageCount(printDocPtr);
18979      for (let pageIndex = 0; pageIndex < pageCount; pageIndex++) {
18980        const annotCount = this.pdfiumModule.EPDFPage_GetAnnotCountRaw(printDocPtr, pageIndex);
18981        if (annotCount <= 0) {
18982          pagesProcessed++;
18983          continue;
18984        }
18985        let annotationsRemovedFromPage = 0;
18986        for (let annotIndex = annotCount - 1; annotIndex >= 0; annotIndex--) {
18987          const removed = this.pdfiumModule.EPDFPage_RemoveAnnotRaw(
18988            printDocPtr,
18989            pageIndex,
18990            annotIndex
18991          );
18992          if (removed) {
18993            annotationsRemovedFromPage++;
18994            totalAnnotationsRemoved++;
18995          } else {
18996            this.logger.warn(
18997              LOG_SOURCE$1,
18998              LOG_CATEGORY$1,
18999              \`Failed to remove annotation \${annotIndex} from page \${pageIndex}\`
19000            );
19001          }
19002        }
19003        if (annotationsRemovedFromPage > 0) {
19004          const pagePtr = this.pdfiumModule.FPDF_LoadPage(printDocPtr, pageIndex);
19005          if (pagePtr) {
19006            this.pdfiumModule.FPDFPage_GenerateContent(pagePtr);
19007            this.pdfiumModule.FPDF_ClosePage(pagePtr);
19008          }
19009        }
19010        pagesProcessed++;
19011      }
19012      return {
19013        success: true,
19014        annotationsRemoved: totalAnnotationsRemoved,
19015        pagesProcessed
19016      };
19017    } catch (error) {
19018      return {
19019        success: false,
19020        annotationsRemoved: totalAnnotationsRemoved,
19021        pagesProcessed,
19022        error: error instanceof Error ? error.message : "Unknown error during annotation removal"
19023      };
19024    }
19025  }
19026  /**
19027   * Sanitizes and validates a page range string.
19028   * Ensures page numbers are within valid bounds and properly formatted.
19029   *
19030   * @param pageRange - Page range string (e.g., "1,3,5-7") or null for all pages
19031   * @param totalPages - Total number of pages in the document
19032   * @returns Sanitized page range string or null for all pages
19033   *
19034   * @private
19035   */
19036  sanitizePageRange(pageRange, totalPages) {
19037    if (!pageRange || pageRange.trim() === "") {
19038      return null;
19039    }
19040    try {
19041      const sanitized = [];
19042      const parts = pageRange.split(",");
19043      for (const part of parts) {
19044        const trimmed = part.trim();
19045        if (trimmed.includes("-")) {
19046          const [startStr, endStr] = trimmed.split("-").map((s) => s.trim());
19047          const start = parseInt(startStr, 10);
19048          const end = parseInt(endStr, 10);
19049          if (isNaN(start) || isNaN(end)) {
19050            this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, \`Invalid range: \${trimmed}\`);
19051            continue;
19052          }
19053          const validStart = Math.max(1, Math.min(start, totalPages));
19054          const validEnd = Math.max(1, Math.min(end, totalPages));
19055          for (let i = validStart; i <= validEnd; i++) {
19056            if (!sanitized.includes(i)) {
19057              sanitized.push(i);
19058            }
19059          }
19060        } else {
19061          const pageNum = parseInt(trimmed, 10);
19062          if (isNaN(pageNum)) {
19063            this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, \`Invalid page number: \${trimmed}\`);
19064            continue;
19065          }
19066          const validPageNum = Math.max(1, Math.min(pageNum, totalPages));
19067          if (!sanitized.includes(validPageNum)) {
19068            sanitized.push(validPageNum);
19069          }
19070        }
19071      }
19072      if (sanitized.length === 0) {
19073        this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, "No valid pages in range, using all pages");
19074        return null;
19075      }
19076      sanitized.sort((a, b) => a - b);
19077      const optimized = [];
19078      let rangeStart = sanitized[0];
19079      let rangeEnd = sanitized[0];
19080      for (let i = 1; i < sanitized.length; i++) {
19081        if (sanitized[i] === rangeEnd + 1) {
19082          rangeEnd = sanitized[i];
19083        } else {
19084          if (rangeStart === rangeEnd) {
19085            optimized.push(rangeStart.toString());
19086          } else if (rangeEnd - rangeStart === 1) {
19087            optimized.push(rangeStart.toString());
19088            optimized.push(rangeEnd.toString());
19089          } else {
19090            optimized.push(\`\${rangeStart}-\${rangeEnd}\`);
19091          }
19092          rangeStart = sanitized[i];
19093          rangeEnd = sanitized[i];
19094        }
19095      }
19096      if (rangeStart === rangeEnd) {
19097        optimized.push(rangeStart.toString());
19098      } else if (rangeEnd - rangeStart === 1) {
19099        optimized.push(rangeStart.toString());
19100        optimized.push(rangeEnd.toString());
19101      } else {
19102        optimized.push(\`\${rangeStart}-\${rangeEnd}\`);
19103      }
19104      const result = optimized.join(",");
19105      this.logger.debug(
19106        LOG_SOURCE$1,
19107        LOG_CATEGORY$1,
19108        \`Sanitized page range: "\${pageRange}" -> "\${result}"\`
19109      );
19110      return result;
19111    } catch (error) {
19112      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, \`Error sanitizing page range: \${error}\`);
19113      return null;
19114    }
19115  }
19116}
19117const LOG_SOURCE = "PdfiumNativeRunner";
19118const LOG_CATEGORY = "Worker";
19119class PdfiumNativeRunner {
19120  constructor(logger) {
19121    this.native = null;
19122    this.activeTasks = /* @__PURE__ */ new Map();
19123    this.logger = logger ?? new NoopLogger();
19124    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "PdfiumNativeRunner created");
19125  }
19126  /**
19127   * Initialize PDFium with WASM binary
19128   */
19129  async prepare(wasmBinary, logger) {
19130    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Preparing PDFium...");
19131    try {
19132      const module = await init({ wasmBinary });
19133      this.native = new PdfiumNative(module, { logger: logger ?? this.logger });
19134      this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "PDFium initialized successfully");
19135    } catch (error) {
19136      this.logger.error(LOG_SOURCE, LOG_CATEGORY, "Failed to initialize PDFium:", error);
19137      throw error;
19138    }
19139  }
19140  /**
19141   * Start listening for messages
19142   */
19143  listen() {
19144    self.onmessage = (evt) => {
19145      this.handle(evt);
19146    };
19147    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Listening for messages");
19148  }
19149  /**
19150   * Handle incoming messages
19151   */
19152  handle(evt) {
19153    const request = evt.data;
19154    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Received message:", request.type);
19155    try {
19156      switch (request.type) {
19157        case "init":
19158          this.handleInit(request);
19159          break;
19160        case "execute":
19161          this.handleExecute(request);
19162          break;
19163        default:
19164          this.logger.warn(LOG_SOURCE, LOG_CATEGORY, "Unknown message type:", request.type);
19165      }
19166    } catch (error) {
19167      this.logger.error(LOG_SOURCE, LOG_CATEGORY, "Error handling message:", error);
19168      this.respond({
19169        id: request.id,
19170        type: "error",
19171        error: {
19172          type: "reject",
19173          reason: { code: PdfErrorCode.Unknown, message: String(error) }
19174        }
19175      });
19176    }
19177  }
19178  /**
19179   * Handle initialization request
19180   */
19181  async handleInit(request) {
19182    if (!request.wasmUrl) {
19183      this.respond({
19184        id: request.id,
19185        type: "error",
19186        error: {
19187          type: "reject",
19188          reason: { code: PdfErrorCode.Unknown, message: "Missing wasmUrl" }
19189        }
19190      });
19191      return;
19192    }
19193    try {
19194      const response = await fetch(request.wasmUrl);
19195      const wasmBinary = await response.arrayBuffer();
19196      await this.prepare(wasmBinary);
19197      this.respond({
19198        id: request.id,
19199        type: "ready"
19200      });
19201    } catch (error) {
19202      this.respond({
19203        id: request.id,
19204        type: "error",
19205        error: {
19206          type: "reject",
19207          reason: { code: PdfErrorCode.Unknown, message: String(error) }
19208        }
19209      });
19210    }
19211  }
19212  /**
19213   * Handle method execution request
19214   */
19215  async handleExecute(request) {
19216    if (!this.native) {
19217      this.respond({
19218        id: request.id,
19219        type: "error",
19220        error: {
19221          type: "reject",
19222          reason: { code: PdfErrorCode.NotReady, message: "PDFium not initialized" }
19223        }
19224      });
19225      return;
19226    }
19227    if (!request.method) {
19228      this.respond({
19229        id: request.id,
19230        type: "error",
19231        error: {
19232          type: "reject",
19233          reason: { code: PdfErrorCode.Unknown, message: "Missing method n
19233ame" }
19234        }
19235      });
19236      return;
19237    }
19238    const method = request.method;
19239    const args = request.args ?? [];
19240    if (!(method in this.native) || typeof this.native[method] !== "function") {
19241      this.respond({
19242        id: request.id,
19243        type: "error",
19244        error: {
19245          type: "reject",
19246          reason: { code: PdfErrorCode.NotSupport, message: \`Method \${method} not supported\` }
19247        }
19248      });
19249      return;
19250    }
19251    try {
19252      this.logger.debug(LOG_SOURCE, LOG_CATEGORY, \`Executing method: \${method}\`);
19253      const result = this.native[method](...args);
19254      if (result && typeof result === "object" && "wait" in result) {
19255        const task = result;
19256        this.activeTasks.set(request.id, task);
19257        task.onProgress((progress) => {
19258          this.respond({
19259            id: request.id,
19260            type: "progress",
19261            progress
19262          });
19263        });
19264        task.wait(
19265          (data) => {
19266            this.logger.debug(LOG_SOURCE, LOG_CATEGORY, \`Method \${method} resolved\`);
19267            this.respond({
19268              id: request.id,
19269              type: "result",
19270              data
19271            });
19272            this.activeTasks.delete(request.id);
19273          },
19274          (error) => {
19275            this.logger.debug(LOG_SOURCE, LOG_CATEGORY, \`Method \${method} failed:\`, error);
19276            this.respond({
19277              id: request.id,
19278              type: "error",
19279              error
19280            });
19281            this.activeTasks.delete(request.id);
19282          }
19283        );
19284      } else {
19285        this.respond({
19286          id: request.id,
19287          type: "result",
19288          data: result
19289        });
19290      }
19291    } catch (error) {
19292      this.logger.error(LOG_SOURCE, LOG_CATEGORY, \`Error executing \${method}:\`, error);
19293      this.respond({
19294        id: request.id,
19295        type: "error",
19296        error: {
19297          type: "reject",
19298          reason: { code: PdfErrorCode.Unknown, message: String(error) }
19299        }
19300      });
19301    }
19302  }
19303  /**
19304   * Send response back to main thread
19305   */
19306  respond(response) {
19307    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Sending response:", response.type);
19308    self.postMessage(response);
19309  }
19310  /**
19311   * Ready notification
19312   */
19313  ready() {
19314    this.listen();
19315    this.respond({
19316      id: "0",
19317      type: "ready"
19318    });
19319    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Runner is ready");
19320  }
19321}
19322class PdfiumEngineRunner extends PdfiumNativeRunner {
19323  /**
19324   * Create an instance of PdfiumEngineRunner
19325   * @param wasmBinary - wasm binary that contains the pdfium wasm file
19326   * @param logger - optional logger instance
19327   * @param fontFallback - optional font fallback configuration
19328   */
19329  constructor(wasmBinary, logger, fontFallback) {
19330    super(logger);
19331    this.wasmBinary = wasmBinary;
19332    this.fontFallback = fontFallback;
19333  }
19334  /**
19335   * Initialize runner
19336   */
19337  async prepare() {
19338    const wasmBinary = this.wasmBinary;
19339    const wasmModule = await init({ wasmBinary });
19340    this.native = new PdfiumNative(wasmModule, {
19341      logger: this.logger,
19342      fontFallback: this.fontFallback
19343    });
19344    this.ready();
19345  }
19346}
19347const fonts$6 = [
19348  { file: "NotoSansJP-Thin.otf", weight: 100 },
19349  { file: "NotoSansJP-Light.otf", weight: 300 },
19350  { file: "NotoSansJP-DemiLight.otf", weight: 350 },
19351  { file: "NotoSansJP-Regular.otf", weight: 400 },
19352  { file: "NotoSansJP-Medium.otf", weight: 500 },
19353  { file: "NotoSansJP-Bold.otf", weight: 700 },
19354  { file: "NotoSansJP-Black.otf", weight: 900 }
19355];
19356const fonts$5 = [
19357  { file: "NotoSansKR-Thin.otf", weight: 100 },
19358  { file: "NotoSansKR-Light.otf", weight: 300 },
19359  { file: "NotoSansKR-DemiLight.otf", weight: 350 },
19360  { file: "NotoSansKR-Regular.otf", weight: 400 },
19361  { file: "NotoSansKR-Medium.otf", weight: 500 },
19362  { file: "NotoSansKR-Bold.otf", weight: 700 },
19363  { file: "NotoSansKR-Black.otf", weight: 900 }
19364];
19365const fonts$4 = [
19366  { file: "NotoSansHans-Light.otf", weight: 300 },
19367  { file: "NotoSansHans-DemiLight.otf", weight: 350 },
19368  { file: "NotoSansHans-Regular.otf", weight: 400 },
19369  { file: "NotoSansHans-Medium.otf", weight: 500 },
19370  { file: "NotoSansHans-Bold.otf", weight: 700 }
19371];
19372const fonts$3 = [
19373  { file: "NotoSansHant-Thin.otf", weight: 100 },
19374  { file: "NotoSansHant-Light.otf", weight: 300 },
19375  { file: "NotoSansHant-DemiLight.otf", weight: 350 },
19376  { file: "NotoSansHant-Regular.otf", weight: 400 },
19377  { file: "NotoSansHant-Medium.otf", weight: 500 },
19378  { file: "NotoSansHant-Bold.otf", weight: 700 },
19379  { file: "NotoSansHant-Black.otf", weight: 900 }
19380];
19381const fonts$2 = [
19382  { file: "NotoNaskhArabic-Regular.ttf", weight: 400 },
19383  { file: "NotoNaskhArabic-Bold.ttf", weight: 700 }
19384];
19385const fonts$1 = [
19386  { file: "NotoSansHebrew-Regular.ttf", weight: 400 },
19387  { file: "NotoSansHebrew-Bold.ttf", weight: 700 }
19388];
19389const fonts = [
19390  // Thin (100)
19391  { file: "NotoSans-Thin.ttf", weight: 100 },
19392  { file: "NotoSans-ThinItalic.ttf", weight: 100, italic: true },
19393  // ExtraLight (200)
19394  { file: "NotoSans-ExtraLight.ttf", weight: 200 },
19395  { file: "NotoSans-ExtraLightItalic.ttf", weight: 200, italic: true },
19396  // Light (300)
19397  { file: "NotoSans-Light.ttf", weight: 300 },
19398  { file: "NotoSans-LightItalic.ttf", weight: 300, italic: true },
19399  // Regular (400)
19400  { file: "NotoSans-Regular.ttf", weight: 400 },
19401  { file: "NotoSans-Italic.ttf", weight: 400, italic: true },
19402  // Medium (500)
19403  { file: "NotoSans-Medium.ttf", weight: 500 },
19404  { file: "NotoSans-MediumItalic.ttf", weight: 500, italic: true },
19405  // SemiBold (600)
19406  { file: "NotoSans-SemiBold.ttf", weight: 600 },
19407  { file: "NotoSans-SemiBoldItalic.ttf", weight: 600, italic: true },
19408  // Bold (700)
19409  { file: "NotoSans-Bold.ttf", weight: 700 },
19410  { file: "NotoSans-BoldItalic.ttf", weight: 700, italic: true },
19411  // ExtraBold (800)
19412  { file: "NotoSans-ExtraBold.ttf", weight: 800 },
19413  { file: "NotoSans-ExtraBoldItalic.ttf", weight: 800, italic: true },
19414  // Black (900)
19415  { file: "NotoSans-Black.ttf", weight: 900 },
19416  { file: "NotoSans-BlackItalic.ttf", weight: 900, italic: true }
19417];
19418function buildCdnUrls(version = "latest") {
19419  return {
19420    jp: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-jp@\${version}/fonts\`,
19421    kr: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-kr@\${version}/fonts\`,
19422    sc: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-sc@\${version}/fonts\`,
19423    tc: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-tc@\${version}/fonts\`,
19424    arabic: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-arabic@\${version}/fonts\`,
19425    hebrew: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-hebrew@\${version}/fonts\`,
19426    latin: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-latin@\${version}/fonts\`
19427  };
19428}
19429function toFontVariants(fonts2, baseUrl) {
19430  return fonts2.map((f) => ({
19431    url: \`\${baseUrl}/\${f.file}\`,
19432    weight: f.weight,
19433    italic: f.italic
19434  }));
19435}
19436function buildCdnFontConfig(urls) {
19437  return {
19438    fonts: {
19439      [FontCharset.SHIFTJIS]: toFontVariants(fonts$6, urls.jp),
19440      [FontCharset.HANGEUL]: toFontVariants(fonts$5, urls.kr),
19441      [FontCharset.GB2312]: toFontVariants(fonts$4, urls.sc),
19442      [FontCharset.CHINESEBIG5]: toFontVariants(fonts$3, urls.tc),
19443      [FontCharset.ARABIC]: toFontVariants(fonts$2, urls.arabic),
19444      [FontCharset.HEBREW]: toFontVariants(fonts$1, urls.hebrew),
19445      [FontCharset.CYRILLIC]: toFontVariants(fonts, urls.latin),
19446      [FontCharset.GREEK]: toFontVariants(fonts, urls.latin),
19447      [FontCharset.VIETNAMESE]: toFontVariants(fonts, urls.latin)
19448    }
19449  };
19450}
19451const FONT_CDN_URLS = buildCdnUrls("latest");
19452const cdnFontConfig = buildCdnFontConfig(FONT_CDN_URLS);
19453let runner = null;
19454self.onmessage = async (event) => {
19455  const { type, wasmUrl, logger: serializedLogger, fontFallback } = event.data;
19456  if (type === "wasmInit" && wasmUrl && !runner) {
19457    try {
19458      const response = await fetch(wasmUrl);
19459      const wasmBinary = await response.arrayBuffer();
19460      const logger = serializedLogger ? deserializeLogger(serializedLogger) : void 0;
19461      const effectiveFontFallback = fontFallback === null ? void 0 : fontFallback ?? cdnFontConfig;
19462      runner = new PdfiumEngineRunner(wasmBinary, logger, effectiveFontFallback);
19463      await runner.prepare();
19464    } catch (error) {
19465      const message = error instanceof Error ? error.message : String(error);
19466      self.postMessage({ type: "wasmError", error: message });
19467    }
19468  }
19469};
19470`],{type:"application/javascript"})),{type:"module"}),u=new E(l,{wasmUrl:m,logger:t,fontFallback:o}),p=URL.createObjectURL(new Blob([`function rgbaToBmpBlob(rgba, width, height) {
19471  const pixels = width * height * 4;
19472  const headerLength = 66;
19473  const le32 = (v) => [v & 255, v >>> 8 & 255, v >>> 16 & 255, v >>> 24 & 255];
19474  const header = new Uint8Array([
19475    66,
19476    77,
19477    // 'BM' signature
19478    ...le32(headerLength + pixels),
19479    // file size
19480    0,
19481    0,
19482    0,
19483    0,
19484    // reserved
19485    headerLength,
19486    0,
19487    0,
19488    0,
19489    // pixel data offset
19490    40,
19491    0,
19492    0,
19493    0,
19494    // DIB header size
19495    ...le32(width),
19496    // width
19497    ...le32(-height),
19498    // height (negative = top-down)
19499    1,
19500    0,
19501    // color planes
19502    32,
19503    0,
19504    // bits per pixel
19505    3,
19506    0,
19507    0,
19508    0,
19509    // compression = BI_BITFIELDS
19510    ...le32(pixels),
19511    // image data size
19512    0,
19513    0,
19514    0,
19515    0,
19516    // h resolution
19517    0,
19518    0,
19519    0,
19520    0,
19521    // v resolution
19522    0,
19523    0,
19524    0,
19525    0,
19526    // colors in palette
19527    0,
19528    0,
19529    0,
19530    0,
19531    // important colors
19532    255,
19533    0,
19534    0,
19535    0,
19536    // R channel mask
19537    0,
19538    255,
19539    0,
19540    0,
19541    // G channel mask
19542    0,
19543    0,
19544    255,
19545    0
19546    // B channel mask
19547  ]);
19548  return new Blob(
19549    [header, new Uint8Array(rgba.buffer, rgba.byteOffset, rgba.byteLength)],
19550    { type: "image/bmp" }
19551  );
19552}
19553async function encodeImage(imageData, imageType, quality) {
19554  if (imageType === "image/bmp") {
19555    return rgbaToBmpBlob(imageData.data, imageData.width, imageData.height);
19556  }
19557  if (typeof OffscreenCanvas === "undefined") {
19558    throw new Error("OffscreenCanvas is not available in this worker environment");
19559  }
19560  const { data, width, height } = imageData;
19561  const imgData = new ImageData(new Uint8ClampedArray(data), width, height);
19562  const canvas = new OffscreenCanvas(width, height);
19563  const ctx = canvas.getContext("2d");
19564  if (!ctx) {
19565    throw new Error("Failed to get 2D context from OffscreenCanvas");
19566  }
19567  ctx.putImageData(imgData, 0, 0);
19568  return canvas.convertToBlob({ type: imageType, quality });
19569}
19570self.onmessage = async (event) => {
19571  const request = event.data;
19572  if (request.type !== "encode") {
19573    return;
19574  }
19575  try {
19576    const { imageData, imageType, quality } = request.data;
19577    const blob = await encodeImage(imageData, imageType, quality);
19578    const response = {
19579      id: request.id,
19580      type: "result",
19581      data: blob
19582    };
19583    self.postMessage(response);
19584  } catch (error) {
19585    const response = {
19586      id: request.id,
19587      type: "error",
19588      data: {
19589        message: error instanceof Error ? error.message : String(error)
19590      }
19591    };
19592    self.postMessage(response);
19593  }
19594};
19595`],{type:"application/javascript"})),h=new A(r??2,p,t);return new _(u,{imageConverter:b(h),logger:t})}export{O as createPdfiumEngine};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.