PageSourceSearch

https://royalleafs.ca/_nuxt/EsfuhbQ_.js

js royalleafs.ca collected 2026-09-30 16:42:13 UTC 694,770 bytes, 19,501 lines download raw bytes

vendor: 11,608 bytes, lines 1-111
1import{h as _,x as b}from"./BNo1M3_d.js";import{l as P,g,C as f,F as D}from"./DRwVmnKV.js";import"./BFMX5MT1.js";import"./C6ahHraB.js";import"./CUVTqrYa.js";import"./C9_l-fYa.js";import"./DXvOZ2wd.js";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 G(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  return PdfAnnotationColorType2;
830})(PdfAnnotationColorType || {});
831var PdfAnnotationBorderStyle = /* @__PURE__ */ ((PdfAnnotationBorderStyle2) => {
832  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["UNKNOWN"] = 0] = "UNKNOWN";
833  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["SOLID"] = 1] = "SOLID";
834  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["DASHED"] = 2] = "DASHED";
835  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["BEVELED"] = 3] = "BEVELED";
836  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["INSET"] = 4] = "INSET";
837  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["UNDERLINE"] = 5] = "UNDERLINE";
838  PdfAnnotationBorderStyle2[PdfAnnotationBorderStyle2["CLOUDY"] = 6] = "CLOUDY";
839  return PdfAnnotationBorderStyle2;
840})(PdfAnnotationBorderStyle || {});
841var PDF_FORM_FIELD_FLAG = /* @__PURE__ */ ((PDF_FORM_FIELD_FLAG2) => {
842  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["NONE"] = 0] = "NONE";
843  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["READONLY"] = 1] = "READONLY";
844  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["REQUIRED"] = 2] = "REQUIRED";
845  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["NOEXPORT"] = 4] = "NOEXPORT";
846  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_MULTIPLINE"] = 4096] = "TEXT_MULTIPLINE";
847  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_PASSWORD"] = 8192] = "TEXT_PASSWORD";
848  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_FILESELECT"] = 1048576] = "TEXT_FILESELECT";
849  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_DONOTSPELLCHECK"] = 4194304] = "TEXT_DONOTSPELLCHECK";
850  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_DONOTSCROLL"] = 8388608] = "TEXT_DONOTSCROLL";
851  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_COMB"] = 16777216] = "TEXT_COMB";
852  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["TEXT_RICHTEXT"] = 33554432] = "TEXT_RICHTEXT";
853  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["BUTTON_NOTOGGLETOOFF"] = 16384] = "BUTTON_NOTOGGLETOOFF";
854  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["BUTTON_RADIO"] = 32768] = "BUTTON_RADIO";
855  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["BUTTON_PUSHBUTTON"] = 65536] = "BUTTON_PUSHBUTTON";
856  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["BUTTON_RADIOSINUNISON"] = 33554432] = "BUTTON_RADIOSINUNISON";
857  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_COMBO"] = 131072] = "CHOICE_COMBO";
858  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_EDIT"] = 262144] = "CHOICE_EDIT";
859  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_SORT"] = 524288] = "CHOICE_SORT";
860  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_MULTL_SELECT"] = 2097152] = "CHOICE_MULTL_SELECT";
861  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_DONOTSPELLCHECK"] = 4194304] = "CHOICE_DONOTSPELLCHECK";
862  PDF_FORM_FIELD_FLAG2[PDF_FORM_FIELD_FLAG2["CHOICE_COMMITONSELCHANGE"] = 67108864] = "CHOICE_COMMITONSELCHANGE";
863  return PDF_FORM_FIELD_FLAG2;
864})(PDF_FORM_FIELD_FLAG || {});
865var PdfPageObjectType = /* @__PURE__ */ ((PdfPageObjectType2) => {
866  PdfPageObjectType2[PdfPageObjectType2["UNKNOWN"] = 0] = "UNKNOWN";
867  PdfPageObjectType2[PdfPageObjectType2["TEXT"] = 1] = "TEXT";
868  PdfPageObjectType2[PdfPageObjectType2["PATH"] = 2] = "PATH";
869  PdfPageObjectType2[PdfPageObjectType2["IMAGE"] = 3] = "IMAGE";
870  PdfPageObjectType2[PdfPageObjectType2["SHADING"] = 4] = "SHADING";
871  PdfPageObjectType2[PdfPageObjectType2["FORM"] = 5] = "FORM";
872  return PdfPageObjectType2;
873})(PdfPageObjectType || {});
874const PdfAnnotationFlagName = Object.freeze({
875  [
876    1
877    /* INVISIBLE */
878  ]: "invisible",
879  [
880    2
881    /* HIDDEN */
882  ]: "hidden",
883  [
884    4
885    /* PRINT */
886  ]: "print",
887  [
888    8
889    /* NO_ZOOM */
890  ]: "noZoom",
891  [
892    16
893    /* NO_ROTATE */
894  ]: "noRotate",
895  [
896    32
897    /* NO_VIEW */
898  ]: "noView",
899  [
900    64
901    /* READ_ONLY */
902  ]: "readOnly",
903  [
904    128
905    /* LOCKED */
906  ]: "locked",
907  [
908    256
909    /* TOGGLE_NOVIEW */
910  ]: "toggleNoView"
911});
912const PdfAnnotationFlagValue = Object.entries(
913  PdfAnnotationFlagName
914).reduce(
915  (acc, [bit, name]) => {
916    acc[name] = Number(bit);
917    return acc;
918  },
919  {}
920);
921function flagsToNames(raw) {
922  return Object.keys(PdfAnnotationFlagName).filter((flag) => (raw & flag) !== 0).map((flag) => PdfAnnotationFlagName[flag]);
923}
924function namesToFlags(names) {
925  return names.reduce(
926    (mask, name) => mask | PdfAnnotationFlagValue[name],
927    0
928    /* NONE */
929  );
930}
931var PDF_ANNOT_AACTION_EVENT = /* @__PURE__ */ ((PDF_ANNOT_AACTION_EVENT2) => {
932  PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2["KEY_STROKE"] = 12] = "KEY_STROKE";
933  PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2["FORMAT"] = 13] = "FORMAT";
934  PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2["VALIDATE"] = 14] = "VALIDATE";
935  PDF_ANNOT_AACTION_EVENT2[PDF_ANNOT_AACTION_EVENT2["CALCULATE"] = 15] = "CALCULATE";
936  return PDF_ANNOT_AACTION_EVENT2;
937})(PDF_ANNOT_AACTION_EVENT || {});
938var PdfJavaScriptWidgetEventType = /* @__PURE__ */ ((PdfJavaScriptWidgetEventType2) => {
939  PdfJavaScriptWidgetEventType2["Keystroke"] = "keystroke";
940  PdfJavaScriptWidgetEventType2["Format"] = "format";
941  PdfJavaScriptWidgetEventType2["Validate"] = "validate";
942  PdfJavaScriptWidgetEventType2["Calculate"] = "calculate";
943  return PdfJavaScriptWidgetEventType2;
944})(PdfJavaScriptWidgetEventType || {});
945var PdfJavaScriptActionTrigger = /* @__PURE__ */ ((PdfJavaScriptActionTrigger2) => {
946  PdfJavaScriptActionTrigger2["DocumentNamed"] = "document_named";
947  PdfJavaScriptActionTrigger2["WidgetKeystroke"] = "widget_keystroke";
948  PdfJavaScriptActionTrigger2["WidgetFormat"] = "widget_format";
949  PdfJavaScriptActionTrigger2["WidgetValidate"] = "widget_validate";
950  PdfJavaScriptActionTrigger2["WidgetCalculate"] = "widget_calculate";
951  return PdfJavaScriptActionTrigger2;
952})(PdfJavaScriptActionTrigger || {});
953var FontCharset = /* @__PURE__ */ ((FontCharset2) => {
954  FontCharset2[FontCharset2["ANSI"] = 0] = "ANSI";
955  FontCharset2[FontCharset2["DEFAULT"] = 1] = "DEFAULT";
956  FontCharset2[FontCharset2["SYMBOL"] = 2] = "SYMBOL";
957  FontCharset2[FontCharset2["SHIFTJIS"] = 128] = "SHIFTJIS";
958  FontCharset2[FontCharset2["HANGEUL"] = 129] = "HANGEUL";
959  FontCharset2[FontCharset2["GB2312"] = 134] = "GB2312";
960  FontCharset2[FontCharset2["CHINESEBIG5"] = 136] = "CHINESEBIG5";
961  FontCharset2[FontCharset2["GREEK"] = 161] = "GREEK";
962  FontCharset2[FontCharset2["VIETNAMESE"] = 163] = "VIETNAMESE";
963  FontCharset2[FontCharset2["HEBREW"] = 177] = "HEBREW";
964  FontCharset2[FontCharset2["ARABIC"] = 178] = "ARABIC";
965  FontCharset2[FontCharset2["CYRILLIC"] = 204] = "CYRILLIC";
966  FontCharset2[FontCharset2["THAI"] = 222] = "THAI";
967  FontCharset2[FontCharset2["EASTERNEUROPEAN"] = 238] = "EASTERNEUROPEAN";
968  return FontCharset2;
969})(FontCharset || {});
970var PdfPageFlattenFlag = /* @__PURE__ */ ((PdfPageFlattenFlag2) => {
971  PdfPageFlattenFlag2[PdfPageFlattenFlag2["Display"] = 0] = "Display";
972  PdfPageFlattenFlag2[PdfPageFlattenFlag2["Print"] = 1] = "Print";
973  return PdfPageFlattenFlag2;
974})(PdfPageFlattenFlag || {});
975var PdfErrorCode = /* @__PURE__ */ ((PdfErrorCode2) => {
976  PdfErrorCode2[PdfErrorCode2["Ok"] = 0] = "Ok";
977  PdfErrorCode2[PdfErrorCode2["Unknown"] = 1] = "Unknown";
978  PdfErrorCode2[PdfErrorCode2["NotFound"] = 2] = "NotFound";
979  PdfErrorCode2[PdfErrorCode2["WrongFormat"] = 3] = "WrongFormat";
980  PdfErrorCode2[PdfErrorCode2["Password"] = 4] = "Password";
981  PdfErrorCode2[PdfErrorCode2["Security"] = 5] = "Security";
982  PdfErrorCode2[PdfErrorCode2["PageError"] = 6] = "PageError";
983  PdfErrorCode2[PdfErrorCode2["XFALoad"] = 7] = "XFALoad";
984  PdfErrorCode2[PdfErrorCode2["XFALayout"] = 8] = "XFALayout";
985  PdfErrorCode2[PdfErrorCode2["Cancelled"] = 9] = "Cancelled";
986  PdfErrorCode2[PdfErrorCode2["Initialization"] = 10] = "Initialization";
987  PdfErrorCode2[PdfErrorCode2["NotReady"] = 11] = "NotReady";
988  PdfErrorCode2[PdfErrorCode2["NotSupport"] = 12] = "NotSupport";
989  PdfErrorCode2[PdfErrorCode2["LoadDoc"] = 13] = "LoadDoc";
990  PdfErrorCode2[PdfErrorCode2["DocNotOpen"] = 14] = "DocNotOpen";
991  PdfErrorCode2[PdfErrorCode2["CantCloseDoc"] = 15] = "CantCloseDoc";
992  PdfErrorCode2[PdfErrorCode2["CantCreateNewDoc"] = 16] = "CantCreateNewDoc";
993  PdfErrorCode2[PdfErrorCode2["CantImportPages"] = 17] = "CantImportPages";
994  PdfErrorCode2[PdfErrorCode2["CantCreateAnnot"] = 18] = "CantCreateAnnot";
995  PdfErrorCode2[PdfErrorCode2["CantSetAnnotRect"] = 19] = "CantSetAnnotRect";
996  PdfErrorCode2[PdfErrorCode2["CantSetAnnotContent"] = 20] = "CantSetAnnotContent";
997  PdfErrorCode2[PdfErrorCode2["CantRemoveInkList"] = 21] = "CantRemoveInkList";
998  PdfErrorCode2[PdfErrorCode2["CantAddInkStoke"] = 22] = "CantAddInkStoke";
999  PdfErrorCode2[PdfErrorCode2["CantReadAttachmentSize"] = 23] = "CantReadAttachmentSize";
1000  PdfErrorCode2[PdfErrorCode2["CantReadAttachmentContent"] = 24] = "CantReadAttachmentContent";
1001  PdfErrorCode2[PdfErrorCode2["CantFocusAnnot"] = 25] = "CantFocusAnnot";
1002  PdfErrorCode2[PdfErrorCode2["CantSelectText"] = 26] = "CantSelectText";
1003  PdfErrorCode2[PdfErrorCode2["CantSelectOption"] = 27] = "CantSelectOption";
1004  PdfErrorCode2[PdfErrorCode2["CantCheckField"] = 28] = "CantCheckField";
1005  PdfErrorCode2[PdfErrorCode2["CantSetAnnotString"] = 29] = "CantSetAnnotString";
1006  PdfErrorCode2[PdfErrorCode2["CantDeletePage"] = 30] = "CantDeletePage";
1007  return PdfErrorCode2;
1008})(PdfErrorCode || {});
1009class PdfTaskHelper {
1010  /**
1011   * Create a task
1012   * @returns new task
1013   */
1014  static create() {
1015    return new Task();
1016  }
1017  /**
1018   * Create a task that has been resolved with value
1019   * @param result - resolved value
1020   * @returns resolved task
1021   */
1022  static resolve(result) {
1023    const task = new Task();
1024    task.resolve(result);
1025    return task;
1026  }
1027  /**
1028   * Create a task that has been rejected with error
1029   * @param reason - rejected error
1030   * @returns rejected task
1031   */
1032  static reject(reason) {
1033    const task = new Task();
1034    task.reject(reason);
1035    return task;
1036  }
1037  /**
1038   * Create a task that has been aborted with error
1039   * @param reason - aborted error
1040   * @returns aborted task
1041   */
1042  static abort(reason) {
1043    const task = new Task();
1044    task.reject(reason);
1045    return task;
1046  }
1047}
1048function pdfColorToWebColor(c) {
1049  const clamp = (n) => Math.max(0, Math.min(255, n));
1050  const toHex = (n) => clamp(n).toString(16).padStart(2, "0");
1051  return \`#\${toHex(c.red)}\${toHex(c.green)}\${toHex(c.blue)}\`;
1052}
1053function webColorToPdfColor(color) {
1054  if (/^#?[0-9a-f]{3}$/i.test(color)) {
1055    color = color.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, "#$1$1$2$2$3$3").toLowerCase();
1056  }
1057  const [, r, g, b] = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color) ?? (() => {
1058    throw new Error(\`Invalid hex colour: "\${color}"\`);
1059  })();
1060  return {
1061    red: parseInt(r, 16),
1062    green: parseInt(g, 16),
1063    blue: parseInt(b, 16)
1064  };
1065}
1066function pdfAlphaToWebOpacity(alpha) {
1067  const clamp = (n) => Math.max(0, Math.min(255, n));
1068  return clamp(alpha) / 255;
1069}
1070function webOpacityToPdfAlpha(opacity) {
1071  const clamp = (n, hi = 255) => Math.max(0, Math.min(hi, n));
1072  return clamp(Math.round(opacity * 255));
1073}
1074function pdfDateToDate(pdf) {
1075  if (!(pdf == null ? void 0 : pdf.startsWith("D:")) || pdf.length < 16) return;
1076  const y = +pdf.slice(2, 6);
1077  const mo = +pdf.slice(6, 8) - 1;
1078  const d = +pdf.slice(8, 10);
1079  const H = +pdf.slice(10, 12);
1080  const M = +pdf.slice(12, 14);
1081  const S = +pdf.slice(14, 16);
1082  return new Date(Date.UTC(y, mo, d, H, M, S));
1083}
1084function dateToPdfDate(date = /* @__PURE__ */ new Date()) {
1085  const z = (n, len = 2) => n.toString().padStart(len, "0");
1086  const YYYY = date.getUTCFullYear();
1087  const MM = z(date.getUTCMonth() + 1);
1088  const DD = z(date.getUTCDate());
1089  const HH = z(date.getUTCHours());
1090  const mm = z(date.getUTCMinutes());
1091  const SS = z(date.getUTCSeconds());
1092  return \`D:\${YYYY}\${MM}\${DD}\${HH}\${mm}\${SS}\`;
1093}
1094const TEXT_ALIGNMENT_INFOS = Object.freeze([
1095  { id: PdfTextAlignment.Left, label: "Left", css: "left" },
1096  { id: PdfTextAlignment.Center, label: "Center", css: "center" },
1097  { id: PdfTextAlignment.Right, label: "Right", css: "right" }
1098]);
1099TEXT_ALIGNMENT_INFOS.reduce(
1100  (m, info) => {
1101    m[info.id] = info;
1102    return m;
1103  },
1104  {}
1105);
1106TEXT_ALIGNMENT_INFOS.reduce(
1107  (m, info) => {
1108    m[info.css] = info.id;
1109    return m;
1110  },
1111  {}
1112);
1113TEXT_ALIGNMENT_INFOS.map((info) => ({
1114  value: info.id,
1115  label: info.label
1116}));
1117var PdfStandardFontFamily = /* @__PURE__ */ ((PdfStandardFontFamily2) => {
1118  PdfStandardFontFamily2["Courier"] = "Courier";
1119  PdfStandardFontFamily2["Helvetica"] = "Helvetica";
1120  PdfStandardFontFamily2["Times"] = "Times";
1121  PdfStandardFontFamily2["Symbol"] = "Symbol";
1122  PdfStandardFontFamily2["ZapfDingbats"] = "ZapfDingbats";
1123  PdfStandardFontFamily2["Unknown"] = "Unknown";
1124  return PdfStandardFontFamily2;
1125})(PdfStandardFontFamily || {});
1126PdfStandardFont.Helvetica;
1127const HELVETICA_DESC = {
1128  id: PdfStandardFont.Helvetica,
1129  family: "Helvetica",
1130  bold: false,
1131  italic: false,
1132  label: "Helvetica",
1133  css: "Helvetica, Arial, sans-serif"
1134};
1135const STANDARD_FONT_DESCRIPTORS = Object.freeze([
1136  {
1137    id: PdfStandardFont.Courier,
1138    family: "Courier",
1139    bold: false,
1140    italic: false,
1141    label: "Courier",
1142    css: "Courier, monospace"
1143  },
1144  {
1145    id: PdfStandardFont.Courier_Bold,
1146    family: "Courier",
1147    bold: true,
1148    italic: false,
1149    label: "Courier Bold",
1150    css: "Courier, monospace"
1151  },
1152  {
1153    id: PdfStandardFont.Courier_BoldOblique,
1154    family: "Courier",
1155    bold: true,
1156    italic: true,
1157    label: "Courier Bold Oblique",
1158    css: "Courier, monospace"
1159  },
1160  {
1161    id: PdfStandardFont.Courier_Oblique,
1162    family: "Courier",
1163    bold: false,
1164    italic: true,
1165    label: "Courier Oblique",
1166    css: "Courier, monospace"
1167  },
1168  HELVETICA_DESC,
1169  {
1170    id: PdfStandardFont.Helvetica_Bold,
1171    family: "Helvetica",
1172    bold: true,
1173    italic: false,
1174    label: "Helvetica Bold",
1175    css: "Helvetica, Arial, sans-serif"
1176  },
1177  {
1178    id: PdfStandardFont.Helvetica_BoldOblique,
1179    family: "Helvetica",
1180    bold: true,
1181    italic: true,
1182    label: "Helvetica Bold Oblique",
1183    css: "Helvetica, Arial, sans-serif"
1184  },
1185  {
1186    id: PdfStandardFont.Helvetica_Oblique,
1187    family: "Helvetica",
1188    bold: false,
1189    italic: true,
1190    label: "Helvetica Oblique",
1191    css: "Helvetica, Arial, sans-serif"
1192  },
1193  {
1194    id: PdfStandardFont.Times_Roman,
1195    family: "Times",
1196    bold: false,
1197    italic: false,
1198    label: "Times Roman",
1199    css: '"Times New Roman", Times, serif'
1200  },
1201  {
1202    id: PdfStandardFont.Times_Bold,
1203    family: "Times",
1204    bold: true,
1205    italic: false,
1206    label: "Times Bold",
1207    css: '"Times New Roman", Times, serif'
1208  },
1209  {
1210    id: PdfStandardFont.Times_BoldItalic,
1211    family: "Times",
1212    bold: true,
1213    italic: true,
1214    label: "Times Bold Italic",
1215    css: '"Times New Roman", Times, serif'
1216  },
1217  {
1218    id: PdfStandardFont.Times_Italic,
1219    family: "Times",
1220    bold: false,
1221    italic: true,
1222    label: "Times Italic",
1223    css: '"Times New Roman", Times, serif'
1224  },
1225  {
1226    id: PdfStandardFont.Symbol,
1227    family: "Symbol",
1228    bold: false,
1229    italic: false,
1230    label: "Symbol",
1231    css: "Symbol, serif"
1232  },
1233  {
1234    id: PdfStandardFont.ZapfDingbats,
1235    family: "ZapfDingbats",
1236    bold: false,
1237    italic: false,
1238    label: "Zapf Dingbats",
1239    css: "ZapfDingbats, serif"
1240  }
1241]);
1242STANDARD_FONT_DESCRIPTORS.reduce((m, d) => (m[d.id] = d, m), {});
1243const familyStyleToId = /* @__PURE__ */ new Map();
1244for (const d of STANDARD_FONT_DESCRIPTORS) {
1245  familyStyleToId.set(\`\${d.family}_\${d.bold}_\${d.italic}\`, d.id);
1246}
1247Object.values(PdfStandardFontFamily).filter(
1248  (f) => f !== "Unknown"
1249  /* Unknown */
1250).map((family) => ({ value: family, label: family }));
1251[
1252  ...new Set(STANDARD_FONT_DESCRIPTORS.map((d) => d.family))
1253];
1254const BLEND_MODE_INFOS = Object.freeze([
1255  { id: PdfBlendMode.Normal, label: "Normal", css: "normal" },
1256  { id: PdfBlendMode.Multiply, label: "Multiply", css: "multiply" },
1257  { id: PdfBlendMode.Screen, label: "Screen", css: "screen" },
1258  { id: PdfBlendMode.Overlay, label: "Overlay", css: "overlay" },
1259  { id: PdfBlendMode.Darken, label: "Darken", css: "darken" },
1260  { id: PdfBlendMode.Lighten, label: "Lighten", css: "lighten" },
1261  { id: PdfBlendMode.ColorDodge, label: "Color Dodge", css: "color-dodge" },
1262  { id: PdfBlendMode.ColorBurn, label: "Color Burn", css: "color-burn" },
1263  { id: PdfBlendMode.HardLight, label: "Hard Light", css: "hard-light" },
1264  { id: PdfBlendMode.SoftLight, label: "Soft Light", css: "soft-light" },
1265  { id: PdfBlendMode.Difference, label: "Difference", css: "difference" },
1266  { id: PdfBlendMode.Exclusion, label: "Exclusion", css: "exclusion" },
1267  { id: PdfBlendMode.Hue, label: "Hue", css: "hue" },
1268  { id: PdfBlendMode.Saturation, label: "Saturation", css: "saturation" },
1269  { id: PdfBlendMode.Color, label: "Color", css: "color" },
1270  { id: PdfBlendMode.Luminosity, label: "Luminosity", css: "luminosity" }
1271]);
1272BLEND_MODE_INFOS.reduce(
1273  (m, info) => {
1274    m[info.id] = info;
1275    return m;
1276  },
1277  {}
1278);
1279BLEND_MODE_INFOS.reduce(
1280  (m, info) => {
1281    m[info.css] = info.id;
1282    return m;
1283  },
1284  {}
1285);
1286BLEND_MODE_INFOS.map((info) => ({
1287  value: info.id,
1288  label: info.label
1289}));
1290BLEND_MODE_INFOS.map((info) => info.id);
1291function deserializeLogger(serialized) {
1292  var _a, _b, _c;
1293  switch (serialized.type) {
1294    case "noop":
1295      return new NoopLogger();
1296    case "console":
1297      return new ConsoleLogger();
1298    case "perf":
1299      return new PerfLogger();
1300    case "level":
1301      if (!((_a = serialized.config) == null ? void 0 : _a.logger) || ((_b = serialized.config) == null ? void 0 : _b.level) === void 0) {
1302        throw new Error("LevelLogger requires logger and level in config");
1303      }
1304      return new LevelLogger(deserializeLogger(serialized.config.logger), serialized.config.level);
1305    case "all":
1306      if (!((_c = serialized.config) == null ? void 0 : _c.loggers)) {
1307        throw new Error("AllLogger requires loggers array in config");
1308      }
1309      return new AllLogger(serialized.config.loggers.map(deserializeLogger));
1310    default:
1311      return new NoopLogger();
1312  }
1313}
1314const 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;
1315function isUuidV4(str) {
1316  return V4_REGEX.test(str);
1317}
1318function getRandomBytes(len) {
1319  var _a;
1320  if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.getRandomValues) === "function") {
1321    return globalThis.crypto.getRandomValues(new Uint8Array(len));
1322  }
1323  if (typeof require === "function") {
1324    try {
1325      const { randomBytes } = require("crypto");
1326      return randomBytes(len);
1327    } catch {
1328    }
1329  }
1330  const bytes = new Uint8Array(len);
1331  for (let i = 0; i < len; i++) bytes[i] = Math.floor(Math.random() * 256);
1332  return bytes;
1333}
1334function uuidV4() {
1335  var _a;
1336  if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) === "function") {
1337    return globalThis.crypto.randomUUID();
1338  }
1339  const bytes = getRandomBytes(16);
1340  bytes[6] = bytes[6] & 15 | 64;
1341  bytes[8] = bytes[8] & 63 | 128;
1342  const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1343  return \`\${hex.slice(0, 8)}-\${hex.slice(8, 12)}-\${hex.slice(12, 16)}-\${hex.slice(16, 20)}-\${hex.slice(20)}\`;
1344}
1345function getImageMetadata(buffer) {
1346  if (buffer.byteLength < 4) return null;
1347  const bytes = new Uint8Array(buffer);
1348  if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {
1349    return parsePng(buffer);
1350  }
1351  if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {
1352    return parseJpeg(buffer);
1353  }
1354  if (bytes[0] === 37 && bytes[1] === 80 && bytes[2] === 68 && bytes[3] === 70) {
1355    return { mimeType: "application/pdf" };
1356  }
1357  return null;
1358}
1359function parsePng(buffer) {
1360  if (buffer.byteLength < 24) return null;
1361  const view = new DataView(buffer);
1362  const width = view.getUint32(16);
1363  const height = view.getUint32(20);
1364  if (width === 0 || height === 0) return null;
1365  return { mimeType: "image/png", width, height };
1366}
1367function parseJpeg(buffer) {
1368  const bytes = new Uint8Array(buffer);
1369  let offset = 2;
1370  while (offset + 4 < bytes.byteLength) {
1371    if (bytes[offset] !== 255) return null;
1372    const marker = bytes[offset + 1];
1373    if (marker >= 192 && marker <= 195) {
1374      if (offset + 9 > bytes.byteLength) return null;
1375      const view = new DataView(buffer, offset + 5);
1376      const height = view.getUint16(0);
1377      const width = view.getUint16(2);
1378      if (width === 0 || height === 0) return null;
1379      return { mimeType: "image/jpeg", width, height };
1380    }
1381    if (marker === 216 || marker === 217) {
1382      offset += 2;
1383    } else if (marker === 255) {
1384      offset += 1;
1385    } else {
1386      const segLen = bytes[offset + 2] << 8 | bytes[offset + 3];
1387      offset += 2 + segLen;
1388    }
1389  }
1390  return null;
1391}
1392var createPdfium = (() => {
1393  var _scriptName = import.meta.url;
1394  return async function(moduleArg = {}) {
1395    var moduleRtn;
1396    var Module = moduleArg;
1397    var readyPromiseResolve, readyPromiseReject;
1398    var readyPromise = new Promise((resolve, reject) => {
1399      readyPromiseResolve = resolve;
1400      readyPromiseReject = reject;
1401    });
1402    [
1403      "_EPDF_GetMetaKeyCount",
1404      "_EPDF_GetMetaKeyName",
1405      "_EPDF_GetMetaTrapped",
1406      "_EPDF_GetPageRotationByIndex",
1407      "_EPDF_GetPageSizeByIndexNormalized",
1408      "_EPDF_HasMetaText",
1409      "_EPDF_IsEncrypted",
1410      "_EPDF_IsOwnerUnlocked",
1411      "_EPDF_LoadPageNormalized",
1412      "_EPDF_PNG_EncodeRGBA",
1413      "_EPDF_RemoveEncryption",
1414      "_EPDF_RenderAnnotBitmap",
1415      "_EPDF_RenderAnnotBitmapUnrotated",
1416      "_EPDF_SetEncryption",
1417      "_EPDF_SetMetaText",
1418      "_EPDF_SetMetaTrapped",
1419      "_EPDF_UnlockOwnerPermissions",
1420      "_EPDFAction_CreateGoTo",
1421      "_EPDFAction_CreateGoToNamed",
1422      "_EPDFAction_CreateLaunch",
1423      "_EPDFAction_CreateRemoteGoToByName",
1424      "_EPDFAction_CreateRemoteGoToDest",
1425      "_EPDFAction_CreateURI",
1426      "_EPDFAnnot_ApplyRedaction",
1427      "_EPDFAnnot_ClearBorderEffect",
1428      "_EPDFAnnot_ClearColor",
1429      "_EPDFAnnot_ClearMKColor",
1430      "_EPDFAnnot_ClearRectangleDifferences",
1431      "_EPDFAnnot_ExportAppearanceAsDocument",
1432      "_EPDFAnnot_ExportMultipleAppearancesAsDocument",
1433      "_EPDFAnnot_Flatten",
1434      "_EPDFAnnot_GenerateAppearance",
1435      "_EPDFAnnot_GenerateAppearanceWithBlend",
1436      "_EPDFAnnot_GenerateFormFieldAP",
1437      "_EPDFAnnot_GetAPMatrix",
1438      "_EPDFAnnot_GetAvailableAppearanceModes",
1439      "_EPDFAnnot_GetBlendMode",
1440      "_EPDFAnnot_GetBorderDashPattern",
1441      "_EPDFAnnot_GetBorderDashPatternCount",
1442      "_EPDFAnnot_GetBorderEffect",
1443      "_EPDFAnnot_GetBorderStyle",
1444      "_EPDFAnnot_GetButtonExportValue",
1445      "_EPDFAnnot_GetColor",
1446      "_EPDFAnnot_GetDefaultAppearance",
1447      "_EPDFAnnot_GetExtendedRotation",
1448      "_EPDFAnnot_GetFormFieldObjectNumber",
1449      "_EPDFAnnot_GetFormFieldRawValue",
1450      "_EPDFAnnot_GetIntent",
1451      "_EPDFAnnot_GetLineEndings",
1452      "_EPDFAnnot_GetMKColor",
1453      "_EPDFAnnot_GetName",
1454      "_EPDFAnnot_GetOpacity",
1455      "_EPDFAnnot_GetOverlayText",
1456      "_EPDFAnnot_GetOverlayTextRepeat",
1457      "_EPDFAnnot_GetRect",
1458      "_EPDFAnnot_GetRectangleDifferences",
1459      "_EPDFAnnot_GetReplyType",
1460      "_EPDFAnnot_GetRichContent",
1461      "_EPDFAnnot_GetRotate",
1462      "_EPDFAnnot_GetTextAlignment",
1463      "_EPDFAnnot_GetUnrotatedRect",
1464      "_EPDFAnnot_GetVerticalAlignment",
1465      "_EPDFAnnot_HasAppearanceStream",
1466      "_EPDFAnnot_SetAction",
1467      "_EPDFAnnot_SetAPMatrix",
1468      "_EPDFAnnot_SetAppearanceFromPage",
1469      "_EPDFAnnot_SetBorderDashPattern",
1470      "_EPDFAnnot_SetBorderEffect",
1471      "_EPDFAnnot_SetBorderStyle",
1472      "_EPDFAnnot_SetColor",
1473      "_EPDFAnnot_SetDefaultAppearance",
1474      "_EPDFAnnot_SetExtendedRotation",
1475      "_EPDFAnnot_SetFormFieldName",
1476      "_EPDFAnnot_SetFormFieldOptions",
1477      "_EPDFAnnot_SetFormFieldValue",
1478      "_EPDFAnnot_SetIntent",
1479      "_EPDFAnnot_SetLine",
1480      "_EPDFAnnot_SetLineEndings",
1481      "_EPDFAnnot_SetLinkedAnnot",
1482      "_EPDFAnnot_SetMKColor",
1483      "_EPDFAnnot_SetName",
1484      "_EPDFAnnot_SetNumberValue",
1485      "_EPDFAnnot_SetOpacity",
1486      "_EPDFAnnot_SetOverlayText",
1487      "_EPDFAnnot_SetOverlayTextRepeat",
1488      "_EPDFAnnot_SetRectangleDifferences",
1489      "_EPDFAnnot_SetReplyType",
1490      "_EPDFAnnot_SetRotate",
1491      "_EPDFAnnot_SetTextAlignment",
1492      "_EPDFAnnot_SetUnrotatedRect",
1493      "_EPDFAnnot_SetVerticalAlignment",
1494      "_EPDFAnnot_SetVertices",
1495      "_EPDFAnnot_ShareFormField",
1496      "_EPDFAnnot_UpdateAppearanceToRect",
1497      "_EPDFAttachment_GetDescription",
1498      "_EPDFAttachment_GetIntegerValue",
1499      "_EPDFAttachment_SetDescription",
1500      "_EPDFAttachment_SetSubtype",
1501      "_EPDFBookmark_AppendChild",
1502      "_EPDFBookmark_Clear",
1503      "_EPDFBookmark_ClearTarget",
1504      "_EPDFBookmark_Create",
1505      "_EPDFBookmark_Delete",
1506      "_EPDFBookmark_InsertAfter",
1507      "_EPDFBookmark_SetAction",
1508      "_EPDFBookmark_SetDest",
1509      "_EPDFBookmark_SetTitle",
1510      "_EPDFCatalog_GetLanguage",
1511      "_EPDFDest_CreateRemoteView",
1512      "_EPDFDest_CreateRemoteXYZ",
1513      "_EPDFDest_CreateView",
1514      "_EPDFDest_CreateXYZ",
1515      "_EPDFImageObj_SetJpeg",
1516      "_EPDFImageObj_SetPng",
1517      "_EPDFNamedDest_Remove",
1518      "_EPDFNamedDest_SetDest",
1519      "_EPDFPage_ApplyRedactions",
1520      "_EPDFPage_CreateAnnot",
1521      "_EPDFPage_CreateFormField",
1522      "_EPDFPage_GetAnnotByName",
1523      "_EPDFPage_GetAnnotCountRaw",
1524      "_EPDFPage_GetAnnotRaw",
1525      "_EPDFPage_RemoveAnnotByName",
1526      "_EPDFPage_RemoveAnnotRaw",
1527      "_EPDFText_RedactInQuads",
1528      "_EPDFText_RedactInRect",
1529      "_FORM_CanRedo",
1530      "_FORM_CanUndo",
1531      "_FORM_DoDocumentAAction",
1532      "_FORM_DoDocumentJSAction",
1533      "_FORM_DoDocumentOpenAction",
1534      "_FORM_DoPageAAction",
1535      "_FORM_ForceToKillFocus",
1536      "_FORM_GetFocusedAnnot",
1537      "_FORM_GetFocusedText",
1538      "_FORM_GetSelectedText",
1539      "_FORM_IsIndexSelected",
1540      "_FORM_OnAfterLoadPage",
1541      "_FORM_OnBeforeClosePage",
1542      "_FORM_OnChar",
1543      "_FORM_OnFocus",
1544      "_FORM_OnKeyDown",
1545      "_FORM_OnKeyUp",
1546      "_FORM_OnLButtonDoubleClick",
1547      "_FORM_OnLButtonDown",
1548      "_FORM_OnLButtonUp",
1549      "_FORM_OnMouseMove",
1550      "_FORM_OnMouseWheel",
1551      "_FORM_OnRButtonDown",
1552      "_FORM_OnRButtonUp",
1553      "_FORM_Redo",
1554      "_FORM_ReplaceAndKeepSelection",
1555      "_FORM_ReplaceSelection",
1556      "_FORM_SelectAllText",
1557      "_FORM_SetFocusedAnnot",
1558      "_FORM_SetIndexSelected",
1559      "_FORM_Undo",
1560      "_FPDF_AddInstalledFont",
1561      "_FPDF_CloseDocument",
1562      "_FPDF_ClosePage",
1563      "_FPDF_CloseXObject",
1564      "_FPDF_CopyViewerPreferences",
1565      "_FPDF_CountNamedDests",
1566      "_FPDF_CreateClipPath",
1567      "_FPDF_CreateNewDocument",
1568      "_FPDF_DestroyClipPath",
1569      "_FPDF_DestroyLibrary",
1570      "_FPDF_DeviceToPage",
1571      "_FPDF_DocumentHasValidCrossReferenceTable",
1572      "_FPDF_FFLDraw",
1573      "_FPDF_FreeDefaultSystemFontInfo",
1574      "_FPDF_GetDefaultSystemFontInfo",
1575      "_FPDF_GetDefaultTTFMap",
1576      "_FPDF_GetDefaultTTFMapCount",
1577      "_FPDF_GetDefaultTTFMapEntry",
1578      "_FPDF_GetDocPermissions",
1579      "_FPDF_GetDocUserPermissions",
1580      "_FPDF_GetFileIdentifier",
1581      "_FPDF_GetFileVersion",
1582      "_FPDF_GetFormType",
1583      "_FPDF_GetLastError",
1584      "_FPDF_GetMetaText",
1585      "_FPDF_GetNamedDest",
1586      "_FPDF_GetNamedDestByName",
1587      "_FPDF_GetPageAAction",
1588      "_FPDF_GetPageBoundingBox",
1589      "_FPDF_GetPageCount",
1590      "_FPDF_GetPageHeight",
1591      "_FPDF_GetPageHeightF",
1592      "_FPDF_GetPageLabel",
1593      "_FPDF_GetPageSizeByIndex",
1594      "_FPDF_GetPageSizeByIndexF",
1595      "_FPDF_GetPageWidth",
1596      "_FPDF_GetPageWidthF",
1597      "_FPDF_GetSecurityHandlerRevision",
1598      "_FPDF_GetSignatureCount",
1599      "_FPDF_GetSignatureObject",
1600      "_FPDF_GetTrailerEnds",
1601      "_FPDF_GetXFAPacketContent",
1602      "_FPDF_GetXFAPacketCount",
1603      "_FPDF_GetXFAPacketName",
1604      "_FPDF_ImportNPagesToOne",
1605      "_FPDF_ImportPages",
1606      "_FPDF_ImportPagesByIndex",
1607      "_FPDF_InitLibrary",
1608      "_FPDF_InitLibraryWithConfig",
1609      "_FPDF_LoadCustomDocument",
1610      "_FPDF_LoadDocument",
1611      "_FPDF_LoadMemDocument",
1612      "_FPDF_LoadMemDocument64",
1613      "_FPDF_LoadPage",
1614      "_FPDF_LoadXFA",
1615      "_FPDF_MovePages",
1616      "_FPDF_NewFormObjectFromXObject",
1617      "_FPDF_NewXObjectFromPage",
1618      "_FPDF_PageToDevice",
1619      "_FPDF_RemoveFormFieldHighlight",
1620      "_FPDF_RenderPage_Close",
1621      "_FPDF_RenderPage_Continue",
1622      "_FPDF_RenderPageBitmap",
1623      "_FPDF_RenderPageBitmap_Start",
1624      "_FPDF_RenderPageBitmapWithColorScheme_Start",
1625      "_FPDF_RenderPageBitmapWithMatrix",
1626      "_FPDF_SaveAsCopy",
1627      "_FPDF_SaveWithVersion",
1628      "_FPDF_SetFormFieldHighlightAlpha",
1629      "_FPDF_SetFormFieldHighlightColor",
1630      "_FPDF_SetSandBoxPolicy",
1631      "_FPDF_SetSystemFontInfo",
1632      "_FPDF_StructElement_Attr_CountChildren",
1633      "_FPDF_StructElement_Attr_GetBlobValue",
1634      "_FPDF_StructElement_Attr_GetBooleanValue",
1635      "_FPDF_StructElement_Attr_GetChildAtIndex",
1636      "_FPDF_StructElement_Attr_GetCount",
1637      "_FPDF_StructElement_Attr_GetName",
1638      "_FPDF_StructElement_Attr_GetNumberValue",
1639      "_FPDF_StructElement_Attr_GetStringValue",
1640      "_FPDF_StructElement_Attr_GetType",
1641      "_FPDF_StructElement_Attr_GetValue",
1642      "_FPDF_StructElement_CountChildren",
1643      "_FPDF_StructElement_GetActualText",
1644      "_FPDF_StructElement_GetAltText",
1645      "_FPDF_StructElement_GetAttributeAtIndex",
1646      "_FPDF_StructElement_GetAttributeCount",
1647      "_FPDF_StructElement_GetChildAtIndex",
1648      "_FPDF_StructElement_GetChildMarkedContentID",
1649      "_FPDF_StructElement_GetID",
1650      "_FPDF_StructElement_GetLang",
1651      "_FPDF_StructElement_GetMarkedContentID",
1652      "_FPDF_StructElement_GetMarkedContentIdAtIndex",
1653      "_FPDF_StructElement_GetMarkedContentIdCount",
1654      "_FPDF_StructElement_GetObjType",
1655      "_FPDF_StructElement_GetParent",
1656      "_FPDF_StructElement_GetStringAttribute",
1657      "_FPDF_StructElement_GetTitle",
1658      "_FPDF_StructElement_GetType",
1659      "_FPDF_StructTree_Close",
1660      "_FPDF_StructTree_CountChildren",
1661      "_FPDF_StructTree_GetChildAtIndex",
1662      "_FPDF_StructTree_GetForPage",
1663      "_FPDF_VIEWERREF_GetDuplex",
1664      "_FPDF_VIEWERREF_GetName",
1665      "_FPDF_VIEWERREF_GetNumCopies",
1666      "_FPDF_VIEWERREF_GetPrintPageRange",
1667      "_FPDF_VIEWERREF_GetPrintPageRangeCount",
1668      "_FPDF_VIEWERREF_GetPrintPageRangeElement",
1669      "_FPDF_VIEWERREF_GetPrintScaling",
1670      "_FPDFAction_GetDest",
1671      "_FPDFAction_GetFilePath",
1672      "_FPDFAction_GetType",
1673      "_FPDFAction_GetURIPath",
1674      "_FPDFAnnot_AddFileAttachment",
1675      "_FPDFAnnot_AddInkStroke",
1676      "_FPDFAnnot_AppendAttachmentPoints",
1677      "_FPDFAnnot_AppendObject",
1678      "_FPDFAnnot_CountAttachmentPoints",
1679      "_FPDFAnnot_GetAP",
1680      "_FPDFAnnot_GetAttachmentPoints",
1681      "_FPDFAnnot_GetBorder",
1682      "_FPDFAnnot_GetColor",
1683      "_FPDFAnnot_GetFileAttachment",
1684      "_FPDFAnnot_GetFlags",
1685      "_FPDFAnnot_GetFocusableSubtypes",
1686      "_FPDFAnnot_GetFocusableSubtypesCount",
1687      "_FPDFAnnot_GetFontColor",
1688      "_FPDFAnnot_GetFontSize",
1689      "_FPDFAnnot_GetFormAdditionalActionJavaScript",
1690      "_FPDFAnnot_GetFormControlCount",
1691      "_FPDFAnnot_GetFormControlIndex",
1692      "_FPDFAnnot_GetFormFieldAlternateName",
1693      "_FPDFAnnot_GetFormFieldAtPoint",
1694      "_FPDFAnnot_GetFormFieldExportValue",
1695      "_FPDFAnnot_GetFormFieldFlags",
1696      "_FPDFAnnot_GetFormFieldName",
1697      "_FPDFAnnot_GetFormFieldType",
1698      "_FPDFAnnot_GetFormFieldValue",
1699      "_FPDFAnnot_GetInkListCount",
1700      "_FPDFAnnot_GetInkListPath",
1701      "_FPDFAnnot_GetLine",
1702      "_FPDFAnnot_GetLink",
1703      "_FPDFAnnot_GetLinkedAnnot",
1704      "_FPDFAnnot_GetNumberValue",
1705      "_FPDFAnnot_GetObject",
1706      "_FPDFAnnot_GetObjectCount",
1707      "_FPDFAnnot_GetOptionCount",
1708      "_FPDFAnnot_GetOptionLabel",
1709      "_FPDFAnnot_GetRect",
1710      "_FPDFAnnot_GetStringValue",
1711      "_FPDFAnnot_GetSubtype",
1712      "_FPDFAnnot_GetValueType",
1713      "_FPDFAnnot_GetVertices",
1714      "_FPDFAnnot_HasAttachmentPoints",
1715      "_FPDFAnnot_HasKey",
1716      "_FPDFAnnot_IsChecked",
1717      "_FPDFAnnot_IsObjectSupportedSubtype",
1718      "_FPDFAnnot_IsOptionSelected",
1719      "_FPDFAnnot_IsSupportedSubtype",
1720      "_FPDFAnnot_RemoveInkList",
1721      "_FPDFAnnot_RemoveObject",
1722      "_FPDFAnnot_SetAP",
1723      "_FPDFAnnot_SetAttachmentPoints",
1724      "_FPDFAnnot_SetBorder",
1725      "_FPDFAnnot_SetColor",
1726      "_FPDFAnnot_SetFlags",
1727      "_FPDFAnnot_SetFocusableSubtypes",
1728      "_FPDFAnnot_SetFontColor",
1729      "_FPDFAnnot_SetFormFieldFlags",
1730      "_FPDFAnnot_SetRect",
1731      "_FPDFAnnot_SetStringValue",
1732      "_FPDFAnnot_SetURI",
1733      "_FPDFAnnot_UpdateObject",
1734      "_FPDFAttachment_GetFile",
1735      "_FPDFAttachment_GetName",
1736      "_FPDFAttachment_GetStringValue",
1737      "_FPDFAttachment_GetSubtype",
1738      "_FPDFAttachment_GetValueType",
1739      "_FPDFAttachment_HasKey",
1740      "_FPDFAttachment_SetFile",
1741      "_FPDFAttachment_SetStringValue",
1742      "_FPDFAvail_Create",
1743      "_FPDFAvail_Destroy",
1744      "_FPDFAvail_GetDocument",
1745      "_FPDFAvail_GetFirstPageNum",
1746      "_FPDFAvail_IsDocAvail",
1747      "_FPDFAvail_IsFormAvail",
1748      "_FPDFAvail_IsLinearized",
1749      "_FPDFAvail_IsPageAvail",
1750      "_FPDFBitmap_Create",
1751      "_FPDFBitmap_CreateEx",
1752      "_FPDFBitmap_Destroy",
1753      "_FPDFBitmap_FillRect",
1754      "_FPDFBitmap_GetBuffer",
1755      "_FPDFBitmap_GetFormat",
1756      "_FPDFBitmap_GetHeight",
1757      "_FPDFBitmap_GetStride",
1758      "_FPDFBitmap_GetWidth",
1759      "_FPDFBookmark_Find",
1760      "_FPDFBookmark_GetAction",
1761      "_FPDFBookmark_GetCount",
1762      "_FPDFBookmark_GetDest",
1763      "_FPDFBookmark_GetFirstChild",
1764      "_FPDFBookmark_GetNextSibling",
1765      "_FPDFBookmark_GetTitle",
1766      "_FPDFCatalog_GetLanguage",
1767      "_FPDFCatalog_IsTagged",
1768      "_FPDFCatalog_SetLanguage",
1769      "_FPDFClipPath_CountPaths",
1770      "_FPDFClipPath_CountPathSegments",
1771      "_FPDFClipPath_GetPathSegment",
1772      "_FPDFDest_GetDestPageIndex",
1773      "_FPDFDest_GetLocationInPage",
1774      "_FPDFDest_GetView",
1775      "_FPDFDoc_AddAttachment",
1776      "_FPDFDoc_CloseJavaScriptAction",
1777      "_FPDFDoc_DeleteAttachment",
1778      "_FPDFDOC_ExitFormFillEnvironment",
1779      "_FPDFDoc_GetAttachment",
1780      "_FPDFDoc_GetAttachmentCount",
1781      "_FPDFDoc_GetJavaScriptAction",
1782      "_FPDFDoc_GetJavaScriptActionCount",
1783      "_FPDFDoc_GetPageMode",
1784      "_FPDFDOC_InitFormFillEnvironment",
1785      "_FPDFFont_Close",
1786      "_FPDFFont_GetAscent",
1787      "_FPDFFont_GetBaseFontName",
1788      "_FPDFFont_GetDescent",
1789      "_FPDFFont_GetFamilyName",
1790      "_FPDFFont_GetFlags",
1791      "_FPDFFont_GetFontData",
1792      "_FPDFFont_GetGlyphPath",
1793      "_FPDFFont_GetGlyphWidth",
1794      "_FPDFFont_GetIsEmbedded",
1795      "_FPDFFont_GetItalicAngle",
1796      "_FPDFFont_GetWeight",
1797      "_FPDFFormObj_CountObjects",
1798      "_FPDFFormObj_GetObject",
1799      "_FPDFFormObj_RemoveObject",
1800      "_FPDFGlyphPath_CountGlyphSegments",
1801      "_FPDFGlyphPath_GetGlyphPathSegment",
1802      "_FPDFImageObj_GetBitmap",
1803      "_FPDFImageObj_GetIccProfileDataDecoded",
1804      "_FPDFImageObj_GetImageDataDecoded",
1805      "_FPDFImageObj_GetImageDataRaw",
1806      "_FPDFImageObj_GetImageFilter",
1807      "_FPDFImageObj_GetImageFilterCount",
1808      "_FPDFImageObj_GetImageMetadata",
1809      "_FPDFImageObj_GetImagePixelSize",
1810      "_FPDFImageObj_GetRenderedBitmap",
1811      "_FPDFImageObj_LoadJpegFile",
1812      "_FPDFImageObj_LoadJpegFileInline",
1813      "_FPDFImageObj_SetBitmap",
1814      "_FPDFImageObj_SetMatrix",
1815      "_FPDFJavaScriptAction_GetName",
1816      "_FPDFJavaScriptAction_GetScript",
1817      "_FPDFLink_CloseWebLinks",
1818      "_FPDFLink_CountQuadPoints",
1819      "_FPDFLink_CountRects",
1820      "_FPDFLink_CountWebLinks",
1821      "_FPDFLink_Enumerate",
1822      "_FPDFLink_GetAction",
1823      "_FPDFLink_GetAnnot",
1824      "_FPDFLink_GetAnnotRect",
1825      "_FPDFLink_GetDest",
1826      "_FPDFLink_GetLinkAtPoint",
1827      "_FPDFLink_GetLinkZOrderAtPoint",
1828      "_FPDFLink_GetQuadPoints",
1829      "_FPDFLink_GetRect",
1830      "_FPDFLink_GetTextRange",
1831      "_FPDFLink_GetURL",
1832      "_FPDFLink_LoadWebLinks",
1833      "_FPDFPage_CloseAnnot",
1834      "_FPDFPage_CountObjects",
1835      "_FPDFPage_CreateAnnot",
1836      "_FPDFPage_Delete",
1837      "_FPDFPage_Flatten",
1838      "_FPDFPage_FormFieldZOrderAtPoint",
1839      "_FPDFPage_GenerateContent",
1840      "_FPDFPage_GetAnnot",
1841      "_FPDFPage_GetAnnotCount",
1842      "_FPDFPage_GetAnnotIndex",
1843      "_FPDFPage_GetArtBox",
1844      "_FPDFPage_GetBleedBox",
1845      "_FPDFPage_GetCropBox",
1846      "_FPDFPage_GetDecodedThumbnailData",
1847      "_FPDFPage_GetMediaBox",
1848      "_FPDFPage_GetObject",
1849      "_FPDFPage_GetRawThumbnailData",
1850      "_FPDFPage_GetRotation",
1851      "_FPDFPage_GetThumbnailAsBitmap",
1852      "_FPDFPage_GetTrimBox",
1853      "_FPDFPage_HasFormFieldAtPoint",
1854      "_FPDFPage_HasTransparency",
1855      "_FPDFPage_InsertClipPath",
1856      "_FPDFPage_InsertObject",
1857      "_FPDFPage_InsertObjectAtIndex",
1858      "_FPDFPage_New",
1859      "_FPDFPage_RemoveAnnot",
1860      "_FPDFPage_RemoveObject",
1861      "_FPDFPage_SetArtBox",
1862      "_FPDFPage_SetBleedBox",
1863      "_FPDFPage_SetCropBox",
1864      "_FPDFPage_SetMediaBox",
1865      "_FPDFPage_SetRotation",
1866      "_FPDFPage_SetTrimBox",
1867      "_FPDFPage_TransformAnnots",
1868      "_FPDFPage_TransFormWithClip",
1869      "_FPDFPageObj_AddMark",
1870      "_FPDFPageObj_CountMarks",
1871      "_FPDFPageObj_CreateNewPath",
1872      "_FPDFPageObj_CreateNewRect",
1873      "_FPDFPageObj_CreateTextObj",
1874      "_FPDFPageObj_Destroy",
1875      "_FPDFPageObj_GetBounds",
1876      "_FPDFPageObj_GetClipPath",
1877      "_FPDFPageObj_GetDashArray",
1878      "_FPDFPageObj_GetDashCount",
1879      "_FPDFPageObj_GetDashPhase",
1880      "_FPDFPageObj_GetFillColor",
1881      "_FPDFPageObj_GetIsActive",
1882      "_FPDFPageObj_GetLineCap",
1883      "_FPDFPageObj_GetLineJoin",
1884      "_FPDFPageObj_GetMark",
1885      "_FPDFPageObj_GetMarkedContentID",
1886      "_FPDFPageObj_GetMatrix",
1887      "_FPDFPageObj_GetRotatedBounds",
1888      "_FPDFPageObj_GetStrokeColor",
1889      "_FPDFPageObj_GetStrokeWidth",
1890      "_FPDFPageObj_GetType",
1891      "_FPDFPageObj_HasTransparency",
1892      "_FPDFPageObj_NewImageObj",
1893      "_FPDFPageObj_NewTextObj",
1894      "_FPDFPageObj_RemoveMark",
1895      "_FPDFPageObj_SetBlendMode",
1896      "_FPDFPageObj_SetDashArray",
1897      "_FPDFPageObj_SetDashPhase",
1898      "_FPDFPageObj_SetFillColor",
1899      "_FPDFPageObj_SetIsActive",
1900      "_FPDFPageObj_SetLineCap",
1901      "_FPDFPageObj_SetLineJoin",
1902      "_FPDFPageObj_SetMatrix",
1903      "_FPDFPageObj_SetStrokeColor",
1904      "_FPDFPageObj_SetStrokeWidth",
1905      "_FPDFPageObj_Transform",
1906      "_FPDFPageObj_TransformClipPath",
1907      "_FPDFPageObj_TransformF",
1908      "_FPDFPageObjMark_CountParams",
1909      "_FPDFPageObjMark_GetName",
1910      "_FPDFPageObjMark_GetParamBlobValue",
1911      "_FPDFPageObjMark_GetParamFloatValue",
1912      "_FPDFPageObjMark_GetParamIntValue",
1913      "_FPDFPageObjMark_GetParamKey",
1914      "_FPDFPageObjMark_GetParamStringValue",
1915      "_FPDFPageObjMark_GetParamValueType",
1916      "_FPDFPageObjMark_RemoveParam",
1917      "_FPDFPageObjMark_SetBlobParam",
1918      "_FPDFPageObjMark_SetFloatParam",
1919      "_FPDFPageObjMark_SetIntParam",
1920      "_FPDFPageObjMark_SetStringParam",
1921      "_FPDFPath_BezierTo",
1922      "_FPDFPath_Close",
1923      "_FPDFPath_CountSegments",
1924      "_FPDFPath_GetDrawMode",
1925      "_FPDFPath_GetPathSegment",
1926      "_FPDFPath_LineTo",
1927      "_FPDFPath_MoveTo",
1928      "_FPDFPath_SetDrawMode",
1929      "_FPDFPathSegment_GetClose",
1930      "_FPDFPathSegment_GetPoint",
1931      "_FPDFPathSegment_GetType",
1932      "_FPDFSignatureObj_GetByteRange",
1933      "_FPDFSignatureObj_GetContents",
1934      "_FPDFSignatureObj_GetDocMDPPermission",
1935      "_FPDFSignatureObj_GetReason",
1936      "_FPDFSignatureObj_GetSubFilter",
1937      "_FPDFSignatureObj_GetTime",
1938      "_FPDFText_ClosePage",
1939      "_FPDFText_CountChars",
1940      "_FPDFText_CountRects",
1941      "_FPDFText_FindClose",
1942      "_FPDFText_FindNext",
1943      "_FPDFText_FindPrev",
1944      "_FPDFText_FindStart",
1945      "_FPDFText_GetBoundedText",
1946      "_FPDFText_GetCharAngle",
1947      "_FPDFText_GetCharBox",
1948      "_FPDFText_GetCharIndexAtPos",
1949      "_FPDFText_GetCharIndexFromTextIndex",
1950      "_FPDFText_GetCharOrigin",
1951      "_FPDFText_GetFillColor",
1952      "_FPDFText_GetFontInfo",
1953      "_FPDFText_GetFontSize",
1954      "_FPDFText_GetFontWeight",
1955      "_FPDFText_GetLooseCharBox",
1956      "_FPDFText_GetMatrix",
1957      "_FPDFText_GetRect",
1958      "_FPDFText_GetSchCount",
1959      "_FPDFText_GetSchResultIndex",
1960      "_FPDFText_GetStrokeColor",
1961      "_FPDFText_GetText",
1962      "_FPDFText_GetTextIndexFromCharIndex",
1963      "_FPDFText_GetTextObject",
1964      "_FPDFText_GetUnicode",
1965      "_FPDFText_HasUnicodeMapError",
1966      "_FPDFText_IsGenerated",
1967      "_FPDFText_IsHyphen",
1968      "_FPDFText_LoadCidType2Font",
1969      "_FPDFText_LoadFont",
1970      "_FPDFText_LoadPage",
1971      "_FPDFText_LoadStandardFont",
1972      "_FPDFText_SetCharcodes",
1973      "_FPDFText_SetText",
1974      "_FPDFTextObj_GetFont",
1975      "_FPDFTextObj_GetFontSize",
1976      "_FPDFTextObj_GetRenderedBitmap",
1977      "_FPDFTextObj_GetText",
1978      "_FPDFTextObj_GetTextRenderMode",
1979      "_FPDFTextObj_SetTextRenderMode",
1980      "_PDFiumExt_CloseFileWriter",
1981      "_PDFiumExt_CloseFormFillInfo",
1982      "_PDFiumExt_ExitFormFillEnvironment",
1983      "_PDFiumExt_GetFileWriterData",
1984      "_PDFiumExt_GetFileWriterSize",
1985      "_PDFiumExt_Init",
1986      "_PDFiumExt_InitFormFillEnvironment",
1987      "_PDFiumExt_OpenFileWriter",
1988      "_PDFiumExt_OpenFormFillInfo",
1989      "_PDFiumExt_SaveAsCopy",
1990      "_malloc",
1991      "_free",
1992      "_memory",
1993      "___indirect_function_table",
1994      "onRuntimeInitialized"
1995    ].forEach((prop) => {
1996      if (!Object.getOwnPropertyDescriptor(readyPromise, prop)) {
1997        Object.defineProperty(readyPromise, prop, {
1998          get: () => abort(
1999            "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"
2000          ),
2001          set: () => abort(
2002            "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"
2003          )
2004        });
2005      }
2006    });
2007    var ENVIRONMENT_IS_WEB = typeof window == "object";
2008    var ENVIRONMENT_IS_WORKER = typeof importScripts == "function";
2009    typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string" && process.type != "renderer";
2010    var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && true && !ENVIRONMENT_IS_WORKER;
2011    var moduleOverrides = Object.assign({}, Module);
2012    var thisProgram = "./this.program";
2013    var scriptDirectory = "";
2014    function locateFile(path) {
2015      if (Module["locateFile"]) {
2016        return Module["locateFile"](path, scriptDirectory);
2017      }
2018      return scriptDirectory + path;
2019    }
2020    var readAsync, readBinary;
2021    if (ENVIRONMENT_IS_SHELL) {
2022      if (typeof window == "object" || typeof importScripts == "function")
2023        throw new Error(
2024          "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?)"
2025        );
2026      readBinary = (f) => {
2027        if (typeof readbuffer == "function") {
2028          return new Uint8Array(readbuffer(f));
2029        }
2030        let data = read(f, "binary");
2031        assert(typeof data == "object");
2032        return data;
2033      };
2034      readAsync = (f) => {
2035        return new Promise((resolve, reject) => {
2036          setTimeout(() => resolve(readBinary(f)));
2037        });
2038      };
2039      globalThis.clearTimeout ?? (globalThis.clearTimeout = (id) => {
2040      });
2041      globalThis.setTimeout ?? (globalThis.setTimeout = (f) => typeof f == "function" ? f() : abort());
2042      if (typeof print != "undefined") {
2043        globalThis.console ?? (globalThis.console = /** @type{!Console} */
2044        {});
2045        console.log = /** @type{!function(this:Console, ...*): undefined} */
2046        print;
2047        console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */
2048        globalThis.printErr ?? print;
2049      }
2050    } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
2051      if (ENVIRONMENT_IS_WORKER) {
2052        scriptDirectory = self.location.href;
2053      } else if (typeof document != "undefined" && document.currentScript) {
2054        scriptDirectory = document.currentScript.src;
2055      }
2056      if (_scriptName) {
2057        scriptDirectory = _scriptName;
2058      }
2059      if (scriptDirectory.startsWith("blob:")) {
2060        scriptDirectory = "";
2061      } else {
2062        scriptDirectory = scriptDirectory.substr(
2063          0,
2064          scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1
2065        );
2066      }
2067      if (!(typeof window == "object" || typeof importScripts == "function"))
2068        throw new Error(
2069          "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?)"
2070        );
2071      {
2072        if (ENVIRONMENT_IS_WORKER) {
2073          readBinary = (url) => {
2074            var xhr = new XMLHttpRequest();
2075            xhr.open("GET", url, false);
2076            xhr.responseType = "arraybuffer";
2077            xhr.send(null);
2078            return new Uint8Array(
2079              /** @type{!ArrayBuffer} */
2080              xhr.response
2081            );
2082          };
2083        }
2084        readAsync = (url) => {
2085          assert(!isFileURI(url), "readAsync does not work with file:// URLs");
2086          return fetch(url, { credentials: "same-origin" }).then((response) => {
2087            if (response.ok) {
2088              return response.arrayBuffer();
2089            }
2090            return Promise.reject(new Error(response.status + " : " + response.url));
2091          });
2092        };
2093      }
2094    } else {
2095      throw new Error("environment detection error");
2096    }
2097    var out = Module["print"] || console.log.bind(console);
2098    var err = Module["printErr"] || console.error.bind(console);
2099    Object.assign(Module, moduleOverrides);
2100    moduleOverrides = null;
2101    checkIncomingModuleAPI();
2102    if (Module["arguments"]) Module["arguments"];
2103    legacyModuleProp("arguments", "arguments_");
2104    if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
2105    legacyModuleProp("thisProgram", "thisProgram");
2106    assert(
2107      typeof Module["memoryInitializerPrefixURL"] == "undefined",
2108      "Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"
2109    );
2110    assert(
2111      typeof Module["pthreadMainPrefixURL"] == "undefined",
2112      "Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"
2113    );
2114    assert(
2115      typeof Module["cdInitializerPrefixURL"] == "undefined",
2116      "Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"
2117    );
2118    assert(
2119      typeof Module["filePackagePrefixURL"] == "undefined",
2120      "Module.filePackagePrefixURL option was removed, use Module.locateFile instead"
2121    );
2122    assert(typeof Module["read"] == "undefined", "Module.read option was removed");
2123    assert(
2124      typeof Module["readAsync"] == "undefined",
2125      "Module.readAsync option was removed (modify readAsync in JS)"
2126    );
2127    assert(
2128      typeof Module["readBinary"] == "undefined",
2129      "Module.readBinary option was removed (modify readBinary in JS)"
2130    );
2131    assert(
2132      typeof Module["setWindowTitle"] == "undefined",
2133      "Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"
2134    );
2135    assert(
2136      typeof Module["TOTAL_MEMORY"] == "undefined",
2137      "Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"
2138    );
2139    legacyModuleProp("asm", "wasmExports");
2140    legacyModuleProp("readAsync", "readAsync");
2141    legacyModuleProp("readBinary", "readBinary");
2142    legacyModuleProp("setWindowTitle", "setWindowTitle");
2143    var wasmBinary = Module["wasmBinary"];
2144    legacyModuleProp("wasmBinary", "wasmBinary");
2145    if (typeof WebAssembly != "object") {
2146      err("no native wasm support detected");
2147    }
2148    var wasmMemory;
2149    var ABORT = false;
2150    function assert(condition, text) {
2151      if (!condition) {
2152        abort("Assertion failed" + (text ? ": " + text : ""));
2153      }
2154    }
2155    var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
2156    function updateMemoryViews() {
2157      var b = wasmMemory.buffer;
2158      Module["HEAP8"] = HEAP8 = new Int8Array(b);
2159      Module["HEAP16"] = HEAP16 = new Int16Array(b);
2160      Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);
2161      Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);
2162      Module["HEAP32"] = HEAP32 = new Int32Array(b);
2163      Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);
2164      Module["HEAPF32"] = HEAPF32 = new Float32Array(b);
2165      Module["HEAPF64"] = HEAPF64 = new Float64Array(b);
2166    }
2167    assert(
2168      !Module["STACK_SIZE"],
2169      "STACK_SIZE can no longer be set at runtime.  Use -sSTACK_SIZE at link time"
2170    );
2171    assert(
2172      typeof Int32Array != "undefined" && typeof Float64Array !== "undefined" && Int32Array.prototype.subarray != void 0 && Int32Array.prototype.set != void 0,
2173      "JS engine does not provide full typed array support"
2174    );
2175    assert(
2176      !Module["wasmMemory"],
2177      "Use of \`wasmMemory\` detected.  Use -sIMPORTED_MEMORY to define wasmMemory externally"
2178    );
2179    assert(
2180      !Module["INITIAL_MEMORY"],
2181      "Detected runtime INITIAL_MEMORY setting.  Use -sIMPORTED_MEMORY to define wasmMemory dynamically"
2182    );
2183    function writeStackCookie() {
2184      var max = _emscripten_stack_get_end();
2185      assert((max & 3) == 0);
2186      if (max == 0) {
2187        max += 4;
2188      }
2189      HEAPU32[max >> 2] = 34821223;
2190      HEAPU32[max + 4 >> 2] = 2310721022;
2191      HEAPU32[0 >> 2] = 1668509029;
2192    }
2193    function checkStackCookie() {
2194      if (ABORT) return;
2195      var max = _emscripten_stack_get_end();
2196      if (max == 0) {
2197        max += 4;
2198      }
2199      var cookie1 = HEAPU32[max >> 2];
2200      var cookie2 = HEAPU32[max + 4 >> 2];
2201      if (cookie1 != 34821223 || cookie2 != 2310721022) {
2202        abort(
2203          \`Stack overflow! Stack cookie has been overwritten at \${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received \${ptrToString(cookie2)} \${ptrToString(cookie1)}\`
2204        );
2205      }
2206      if (HEAPU32[0 >> 2] != 1668509029) {
2207        abort("Runtime error: The application has corrupted its heap memory area (address zero)!");
2208      }
2209    }
2210    var __ATPRERUN__ = [];
2211    var __ATINIT__ = [];
2212    var __ATPOSTRUN__ = [];
2213    var runtimeInitialized = false;
vendor: 8,020 bytes, lines 2214-2437
2214    function preRun() {
2215      var preRuns = Module["preRun"];
2216      if (preRuns) {
2217        if (typeof preRuns == "function") preRuns = [preRuns];
2218        preRuns.forEach(addOnPreRun);
2219      }
2220      callRuntimeCallbacks(__ATPRERUN__);
2221    }
2222    function initRuntime() {
2223      assert(!runtimeInitialized);
2224      runtimeInitialized = true;
2225      checkStackCookie();
2226      if (!Module["noFSInit"] && !FS.initialized) FS.init();
2227      FS.ignorePermissions = false;
2228      callRuntimeCallbacks(__ATINIT__);
2229    }
2230    function postRun() {
2231      checkStackCookie();
2232      var postRuns = Module["postRun"];
2233      if (postRuns) {
2234        if (typeof postRuns == "function") postRuns = [postRuns];
2235        postRuns.forEach(addOnPostRun);
2236      }
2237      callRuntimeCallbacks(__ATPOSTRUN__);
2238    }
2239    function addOnPreRun(cb) {
2240      __ATPRERUN__.unshift(cb);
2241    }
2242    function addOnInit(cb) {
2243      __ATINIT__.unshift(cb);
2244    }
2245    function addOnPostRun(cb) {
2246      __ATPOSTRUN__.unshift(cb);
2247    }
2248    assert(
2249      Math.imul,
2250      "This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"
2251    );
2252    assert(
2253      Math.fround,
2254      "This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"
2255    );
2256    assert(
2257      Math.clz32,
2258      "This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"
2259    );
2260    assert(
2261      Math.trunc,
2262      "This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"
2263    );
2264    var runDependencies = 0;
2265    var runDependencyWatcher = null;
2266    var dependenciesFulfilled = null;
2267    var runDependencyTracking = {};
2268    function getUniqueRunDependency(id) {
2269      var orig = id;
2270      while (1) {
2271        if (!runDependencyTracking[id]) return id;
2272        id = orig + Math.random();
2273      }
2274    }
2275    function addRunDependency(id) {
2276      var _a;
2277      runDependencies++;
2278      (_a = Module["monitorRunDependencies"]) == null ? void 0 : _a.call(Module, runDependencies);
2279      if (id) {
2280        assert(!runDependencyTracking[id]);
2281        runDependencyTracking[id] = 1;
2282        if (runDependencyWatcher === null && typeof setInterval != "undefined") {
2283          runDependencyWatcher = setInterval(() => {
2284            if (ABORT) {
2285              clearInterval(runDependencyWatcher);
2286              runDependencyWatcher = null;
2287              return;
2288            }
2289            var shown = false;
2290            for (var dep in runDependencyTracking) {
2291              if (!shown) {
2292                shown = true;
2293                err("still waiting on run dependencies:");
2294              }
2295              err(\`dependency: \${dep}\`);
2296            }
2297            if (shown) {
2298              err("(end of list)");
2299            }
2300          }, 1e4);
2301        }
2302      } else {
2303        err("warning: run dependency added without ID");
2304      }
2305    }
2306    function removeRunDependency(id) {
2307      var _a;
2308      runDependencies--;
2309      (_a = Module["monitorRunDependencies"]) == null ? void 0 : _a.call(Module, runDependencies);
2310      if (id) {
2311        assert(runDependencyTracking[id]);
2312        delete runDependencyTracking[id];
2313      } else {
2314        err("warning: run dependency removed without ID");
2315      }
2316      if (runDependencies == 0) {
2317        if (runDependencyWatcher !== null) {
2318          clearInterval(runDependencyWatcher);
2319          runDependencyWatcher = null;
2320        }
2321        if (dependenciesFulfilled) {
2322          var callback = dependenciesFulfilled;
2323          dependenciesFulfilled = null;
2324          callback();
2325        }
2326      }
2327    }
2328    function abort(what) {
2329      var _a;
2330      (_a = Module["onAbort"]) == null ? void 0 : _a.call(Module, what);
2331      what = "Aborted(" + what + ")";
2332      err(what);
2333      ABORT = true;
2334      var e = new WebAssembly.RuntimeError(what);
2335      readyPromiseReject(e);
2336      throw e;
2337    }
2338    var dataURIPrefix = "data:application/octet-stream;base64,";
2339    var isDataURI = (filename) => filename.startsWith(dataURIPrefix);
2340    var isFileURI = (filename) => filename.startsWith("file://");
2341    function createExportWrapper(name, nargs) {
2342      return (...args) => {
2343        assert(
2344          runtimeInitialized,
2345          \`native function \\\`\${name}\\\` called before runtime initialization\`
2346        );
2347        var f = wasmExports[name];
2348        assert(f, \`exported native function \\\`\${name}\\\` not found\`);
2349        assert(
2350          args.length <= nargs,
2351          \`native function \\\`\${name}\\\` called with \${args.length} args but expects \${nargs}\`
2352        );
2353        return f(...args);
2354      };
2355    }
2356    function findWasmBinary() {
2357      if (Module["locateFile"]) {
2358        var f = "pdfium.wasm";
2359        if (!isDataURI(f)) {
2360          return locateFile(f);
2361        }
2362        return f;
2363      }
2364      if (ENVIRONMENT_IS_SHELL) return "pdfium.wasm";
2365      return "pdfium.wasm";
2366    }
2367    var wasmBinaryFile;
2368    function getBinarySync(file) {
2369      if (file == wasmBinaryFile && wasmBinary) {
2370        return new Uint8Array(wasmBinary);
2371      }
2372      if (readBinary) {
2373        return readBinary(file);
2374      }
2375      throw "both async and sync fetching of the wasm failed";
2376    }
2377    function getBinaryPromise(binaryFile) {
2378      if (!wasmBinary) {
2379        return readAsync(binaryFile).then(
2380          (response) => new Uint8Array(
2381            /** @type{!ArrayBuffer} */
2382            response
2383          ),
2384          // Fall back to getBinarySync if readAsync fails
2385          () => getBinarySync(binaryFile)
2386        );
2387      }
2388      return Promise.resolve().then(() => getBinarySync(binaryFile));
2389    }
2390    function instantiateArrayBuffer(binaryFile, imports, receiver) {
2391      return getBinaryPromise(binaryFile).then((binary) => {
2392        return WebAssembly.instantiate(binary, imports);
2393      }).then(receiver, (reason) => {
2394        err(\`failed to asynchronously prepare wasm: \${reason}\`);
2395        if (isFileURI(wasmBinaryFile)) {
2396          err(
2397            \`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\`
2398          );
2399        }
2400        abort(reason);
2401      });
2402    }
2403    function instantiateAsync(binary, binaryFile, imports, callback) {
2404      if (!binary && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && // Avoid instantiateStreaming() on Node.js environment for now, as while
2405      // Node.js v18.1.0 implements it, it does not have a full fetch()
2406      // implementation yet.
2407      //
2408      // Reference:
2409      //   https://github.com/emscripten-core/emscripten/pull/16917
2410      true && typeof fetch == "function") {
2411        return fetch(binaryFile, { credentials: "same-origin" }).then((response) => {
2412          var result = WebAssembly.instantiateStreaming(response, imports);
2413          return result.then(callback, function(reason) {
2414            err(\`wasm streaming compile failed: \${reason}\`);
2415            err("falling back to ArrayBuffer instantiation");
2416            return instantiateArrayBuffer(binaryFile, imports, callback);
2417          });
2418        });
2419      }
2420      return instantiateArrayBuffer(binaryFile, imports, callback);
2421    }
2422    function getWasmImports() {
2423      return {
2424        env: wasmImports,
2425        wasi_snapshot_preview1: wasmImports
2426      };
2427    }
2428    function createWasm() {
2429      var info = getWasmImports();
2430      function receiveInstance(instance, module) {
2431        wasmExports = instance.exports;
2432        Module["wasmExports"] = wasmExports;
2433        wasmMemory = wasmExports["memory"];
2434        assert(wasmMemory, "memory not found in wasm exports");
2435        updateMemoryViews();
2436        wasmTable = wasmExports["__indirect_function_table"];
2437        assert(wasmTable, "table not found in wasm exports");
2438        addOnInit(wasmExports["__wasm_call_ctors"]);
2439        removeRunDependency("wasm-instantiate");
2440        return wasmExports;
2441      }
2442      addRunDependency("wasm-instantiate");
2443      var trueModule = Module;
2444      function receiveInstantiationResult(result) {
2445        assert(
2446          Module === trueModule,
2447          "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"
2448        );
2449        trueModule = null;
2450        receiveInstance(result["instance"]);
2451      }
2452      if (Module["instantiateWasm"]) {
2453        try {
2454          return Module["instantiateWasm"](info, receiveInstance);
2455        } catch (e) {
2456          err(\`Module.instantiateWasm callback failed with error: \${e}\`);
2457          readyPromiseReject(e);
2458        }
2459      }
2460      wasmBinaryFile ?? (wasmBinaryFile = findWasmBinary());
2461      instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult).catch(
2462        readyPromiseReject
2463      );
2464      return {};
2465    }
2466    var tempDouble;
2467    var tempI64;
2468    (() => {
2469      var h16 = new Int16Array(1);
2470      var h8 = new Int8Array(h16.buffer);
2471      h16[0] = 25459;
2472      if (h8[0] !== 115 || h8[1] !== 99)
2473        throw "Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)";
2474    })();
2475    if (Module["ENVIRONMENT"]) {
2476      throw new Error(
2477        "Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)"
2478      );
2479    }
2480    function legacyModuleProp(prop, newName, incoming = true) {
2481      if (!Object.getOwnPropertyDescriptor(Module, prop)) {
2482        Object.defineProperty(Module, prop, {
2483          configurable: true,
2484          get() {
2485            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)" : "";
2486            abort(\`\\\`Module.\${prop}\\\` has been replaced by \\\`\${newName}\\\`\` + extra);
2487          }
2488        });
2489      }
2490    }
2491    function ignoredModuleProp(prop) {
2492      if (Object.getOwnPropertyDescriptor(Module, prop)) {
2493        abort(
2494          \`\\\`Module.\${prop}\\\` was supplied but \\\`\${prop}\\\` not included in INCOMING_MODULE_JS_API\`
2495        );
2496      }
2497    }
2498    function isExportedByForceFilesystem(name) {
2499      return name === "FS_createPath" || name === "FS_createDataFile" || name === "FS_createPreloadedFile" || name === "FS_unlink" || name === "addRunDependency" || // The old FS has some functionality that WasmFS lacks.
2500      name === "FS_createLazyFile" || name === "FS_createDevice" || name === "removeRunDependency";
2501    }
2502    function hookGlobalSymbolAccess(sym, func) {
2503      if (typeof globalThis != "undefined" && !Object.getOwnPropertyDescriptor(globalThis, sym)) {
2504        Object.defineProperty(globalThis, sym, {
2505          configurable: true,
2506          get() {
2507            func();
2508            return void 0;
2509          }
2510        });
2511      }
2512    }
2513    function missingGlobal(sym, msg) {
2514      hookGlobalSymbolAccess(sym, () => {
2515        warnOnce(\`\\\`\${sym}\\\` is not longer defined by emscripten. \${msg}\`);
2516      });
2517    }
2518    missingGlobal("buffer", "Please use HEAP8.buffer or wasmMemory.buffer");
2519    missingGlobal("asm", "Please use wasmExports instead");
2520    function missingLibrarySymbol(sym) {
2521      hookGlobalSymbolAccess(sym, () => {
2522        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\`;
2523        var librarySymbol = sym;
2524        if (!librarySymbol.startsWith("_")) {
2525          librarySymbol = "$" + sym;
2526        }
2527        msg += \` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='\${librarySymbol}')\`;
2528        if (isExportedByForceFilesystem(sym)) {
2529          msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";
2530        }
2531        warnOnce(msg);
2532      });
2533      unexportedRuntimeSymbol(sym);
2534    }
2535    function unexportedRuntimeSymbol(sym) {
2536      if (!Object.getOwnPropertyDescriptor(Module, sym)) {
2537        Object.defineProperty(Module, sym, {
2538          configurable: true,
2539          get() {
2540            var msg = \`'\${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)\`;
2541            if (isExportedByForceFilesystem(sym)) {
2542              msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";
2543            }
2544            abort(msg);
2545          }
2546        });
2547      }
2548    }
2549    var callRuntimeCallbacks = (callbacks) => {
2550      callbacks.forEach((f) => f(Module));
2551    };
2552    function getValue(ptr, type = "i8") {
2553      if (type.endsWith("*")) type = "*";
2554      switch (type) {
2555        case "i1":
2556          return HEAP8[ptr];
2557        case "i8":
2558          return HEAP8[ptr];
2559        case "i16":
2560          return HEAP16[ptr >> 1];
2561        case "i32":
2562          return HEAP32[ptr >> 2];
2563        case "i64":
2564          abort("to do getValue(i64) use WASM_BIGINT");
2565        case "float":
2566          return HEAPF32[ptr >> 2];
2567        case "double":
2568          return HEAPF64[ptr >> 3];
2569        case "*":
2570          return HEAPU32[ptr >> 2];
2571        default:
2572          abort(\`invalid type for getValue: \${type}\`);
2573      }
2574    }
2575    Module["noExitRuntime"] || true;
2576    var ptrToString = (ptr) => {
2577      assert(typeof ptr === "number");
2578      ptr >>>= 0;
2579      return "0x" + ptr.toString(16).padStart(8, "0");
2580    };
2581    function setValue(ptr, value, type = "i8") {
2582      if (type.endsWith("*")) type = "*";
2583      switch (type) {
2584        case "i1":
2585          HEAP8[ptr] = value;
2586          break;
2587        case "i8":
2588          HEAP8[ptr] = value;
2589          break;
2590        case "i16":
2591          HEAP16[ptr >> 1] = value;
2592          break;
2593        case "i32":
2594          HEAP32[ptr >> 2] = value;
2595          break;
2596        case "i64":
2597          abort("to do setValue(i64) use WASM_BIGINT");
2598        case "float":
2599          HEAPF32[ptr >> 2] = value;
2600          break;
2601        case "double":
2602          HEAPF64[ptr >> 3] = value;
2603          break;
2604        case "*":
2605          HEAPU32[ptr >> 2] = value;
2606          break;
2607        default:
2608          abort(\`invalid type for setValue: \${type}\`);
2609      }
2610    }
2611    var stackRestore = (val) => __emscripten_stack_restore(val);
2612    var stackSave = () => _emscripten_stack_get_current();
2613    var warnOnce = (text) => {
2614      warnOnce.shown || (warnOnce.shown = {});
2615      if (!warnOnce.shown[text]) {
2616        warnOnce.shown[text] = 1;
2617        err(text);
2618      }
2619    };
2620    var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;
2621    var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => {
2622      var endIdx = idx + maxBytesToRead;
2623      var endPtr = idx;
2624      while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
2625      if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
2626        return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
2627      }
2628      var str = "";
2629      while (idx < endPtr) {
2630        var u0 = heapOrArray[idx++];
2631        if (!(u0 & 128)) {
2632          str += String.fromCharCode(u0);
2633          continue;
2634        }
2635        var u1 = heapOrArray[idx++] & 63;
2636        if ((u0 & 224) == 192) {
2637          str += String.fromCharCode((u0 & 31) << 6 | u1);
2638          continue;
2639        }
2640        var u2 = heapOrArray[idx++] & 63;
2641        if ((u0 & 240) == 224) {
2642          u0 = (u0 & 15) << 12 | u1 << 6 | u2;
2643        } else {
2644          if ((u0 & 248) != 240)
2645            warnOnce(
2646              "Invalid UTF-8 leading byte " + ptrToString(u0) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!"
2647            );
2648          u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
2649        }
2650        if (u0 < 65536) {
2651          str += String.fromCharCode(u0);
2652        } else {
2653          var ch = u0 - 65536;
2654          str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
2655        }
2656      }
2657      return str;
2658    };
2659    var UTF8ToString = (ptr, maxBytesToRead) => {
2660      assert(typeof ptr == "number", \`UTF8ToString expects a number (got \${typeof ptr})\`);
2661      return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
2662    };
2663    var ___assert_fail = (condition, filename, line, func) => {
2664      abort(
2665        \`Assertion failed: \${UTF8ToString(condition)}, at: \` + [
2666          filename ? UTF8ToString(filename) : "unknown filename",
2667          line,
2668          func ? UTF8ToString(func) : "unknown function"
2669        ]
2670      );
2671    };
2672    function syscallGetVarargI() {
2673      assert(SYSCALLS.varargs != void 0);
2674      var ret = HEAP32[+SYSCALLS.varargs >> 2];
2675      SYSCALLS.varargs += 4;
2676      return ret;
2677    }
2678    var syscallGetVarargP = syscallGetVarargI;
2679    var PATH = {
2680      isAbs: (path) => path.charAt(0) === "/",
2681      splitPath: (filename) => {
2682        var splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;
2683        return splitPathRe.exec(filename).slice(1);
2684      },
2685      normalizeArray: (parts, allowAboveRoot) => {
2686        var up = 0;
2687        for (var i = parts.length - 1; i >= 0; i--) {
2688          var last = parts[i];
2689          if (last === ".") {
2690            parts.splice(i, 1);
2691          } else if (last === "..") {
2692            parts.splice(i, 1);
2693            up++;
2694          } else if (up) {
2695            parts.splice(i, 1);
2696            up--;
2697          }
2698        }
2699        if (allowAboveRoot) {
2700          for (; up; up--) {
2701            parts.unshift("..");
2702          }
2703        }
2704        return parts;
2705      },
2706      normalize: (path) => {
2707        var isAbsolute = PATH.isAbs(path), trailingSlash = path.substr(-1) === "/";
2708        path = PATH.normalizeArray(
2709          path.split("/").filter((p) => !!p),
2710          !isAbsolute
2711        ).join("/");
2712        if (!path && !isAbsolute) {
2713          path = ".";
2714        }
2715        if (path && trailingSlash) {
2716          path += "/";
2717        }
2718        return (isAbsolute ? "/" : "") + path;
2719      },
2720      dirname: (path) => {
2721        var result = PATH.splitPath(path), root = result[0], dir = result[1];
2722        if (!root && !dir) {
2723          return ".";
2724        }
2725        if (dir) {
2726          dir = dir.substr(0, dir.length - 1);
2727        }
2728        return root + dir;
2729      },
2730      basename: (path) => {
2731        if (path === "/") return "/";
2732        path = PATH.normalize(path);
2733        path = path.replace(/\\/$/, "");
2734        var lastSlash = path.lastIndexOf("/");
2735        if (lastSlash === -1) return path;
2736        return path.substr(lastSlash + 1);
2737      },
2738      join: (...paths) => PATH.normalize(paths.join("/")),
2739      join2: (l, r) =>
2739 PATH.normalize(l + "/" + r)
2740    };
2741    var initRandomFill = () => {
2742      if (typeof crypto == "object" && typeof crypto["getRandomValues"] == "function") {
2743        return (view) => crypto.getRandomValues(view);
2744      }
2745      abort(
2746        "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 } };"
2747      );
2748    };
2749    var randomFill = (view) => {
2750      return (randomFill = initRandomFill())(view);
2751    };
2752    var PATH_FS = {
2753      resolve: (...args) => {
2754        var resolvedPath = "", resolvedAbsolute = false;
2755        for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
2756          var path = i >= 0 ? args[i] : FS.cwd();
2757          if (typeof path != "string") {
2758            throw new TypeError("Arguments to path.resolve must be strings");
2759          } else if (!path) {
2760            return "";
2761          }
2762          resolvedPath = path + "/" + resolvedPath;
2763          resolvedAbsolute = PATH.isAbs(path);
2764        }
2765        resolvedPath = PATH.normalizeArray(
2766          resolvedPath.split("/").filter((p) => !!p),
2767          !resolvedAbsolute
2768        ).join("/");
2769        return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
2770      },
2771      relative: (from, to) => {
2772        from = PATH_FS.resolve(from).substr(1);
2773        to = PATH_FS.resolve(to).substr(1);
2774        function trim(arr) {
2775          var start = 0;
2776          for (; start < arr.length; start++) {
2777            if (arr[start] !== "") break;
2778          }
2779          var end = arr.length - 1;
2780          for (; end >= 0; end--) {
2781            if (arr[end] !== "") break;
2782          }
2783          if (start > end) return [];
2784          return arr.slice(start, end - start + 1);
2785        }
2786        var fromParts = trim(from.split("/"));
2787        var toParts = trim(to.split("/"));
2788        var length = Math.min(fromParts.length, toParts.length);
2789        var samePartsLength = length;
2790        for (var i = 0; i < length; i++) {
2791          if (fromParts[i] !== toParts[i]) {
2792            samePartsLength = i;
2793            break;
2794          }
2795        }
2796        var outputParts = [];
2797        for (var i = samePartsLength; i < fromParts.length; i++) {
2798          outputParts.push("..");
2799        }
2800        outputParts = outputParts.concat(toParts.slice(samePartsLength));
2801        return outputParts.join("/");
2802      }
2803    };
2804    var FS_stdin_getChar_buffer = [];
2805    var lengthBytesUTF8 = (str) => {
2806      var len = 0;
2807      for (var i = 0; i < str.length; ++i) {
2808        var c = str.charCodeAt(i);
2809        if (c <= 127) {
2810          len++;
2811        } else if (c <= 2047) {
2812          len += 2;
2813        } else if (c >= 55296 && c <= 57343) {
2814          len += 4;
2815          ++i;
2816        } else {
2817          len += 3;
2818        }
2819      }
2820      return len;
2821    };
2822    var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
2823      assert(typeof str === "string", \`stringToUTF8Array expects a string (got \${typeof str})\`);
2824      if (!(maxBytesToWrite > 0)) return 0;
2825      var startIdx = outIdx;
2826      var endIdx = outIdx + maxBytesToWrite - 1;
2827      for (var i = 0; i < str.length; ++i) {
2828        var u = str.charCodeAt(i);
2829        if (u >= 55296 && u <= 57343) {
2830          var u1 = str.charCodeAt(++i);
2831          u = 65536 + ((u & 1023) << 10) | u1 & 1023;
2832        }
2833        if (u <= 127) {
2834          if (outIdx >= endIdx) break;
2835          heap[outIdx++] = u;
2836        } else if (u <= 2047) {
2837          if (outIdx + 1 >= endIdx) break;
2838          heap[outIdx++] = 192 | u >> 6;
2839          heap[outIdx++] = 128 | u & 63;
2840        } else if (u <= 65535) {
2841          if (outIdx + 2 >= endIdx) break;
2842          heap[outIdx++] = 224 | u >> 12;
2843          heap[outIdx++] = 128 | u >> 6 & 63;
2844          heap[outIdx++] = 128 | u & 63;
2845        } else {
2846          if (outIdx + 3 >= endIdx) break;
2847          if (u > 1114111)
2848            warnOnce(
2849              "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)."
2850            );
2851          heap[outIdx++] = 240 | u >> 18;
2852          heap[outIdx++] = 128 | u >>
2852 12 & 63;
2853          heap[outIdx++] = 128 | u >> 6 & 63;
2854          heap[outIdx++] = 128 | u & 63;
2855        }
2856      }
2857      heap[outIdx] = 0;
2858      return outIdx - startIdx;
2859    };
2860    function intArrayFromString(stringy, dontAddNull, length) {
2861      var len = lengthBytesUTF8(stringy) + 1;
2862      var u8array = new Array(len);
2863      var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
2864      u8array.length = numBytesWritten;
2865      return u8array;
2866    }
2867    var FS_stdin_getChar = () => {
2868      if (!FS_stdin_getChar_buffer.length) {
2869        var result = null;
2870        if (typeof window != "undefined" && typeof window.prompt == "function") {
2871          result = window.prompt("Input: ");
2872          if (result !== null) {
2873            result += "\\n";
2874          }
2875        } else if (typeof readline == "function") {
2876          result = readline();
2877          if (result) {
2878            result += "\\n";
2879          }
2880        } else ;
2881        if (!result) {
2882          return null;
2883        }
2884        FS_stdin_getChar_buffer = intArrayFromString(result);
2885      }
2886      return FS_stdin_getChar_buffer.shift();
2887    };
2888    var TTY = {
2889      ttys: [],
2890      init() {
2891      },
2892      shutdown() {
2893      },
2894      register(dev, ops) {
2895        TTY.ttys[dev] = { input: [], output: [], ops };
2896        FS.registerDevice(dev, TTY.stream_ops);
2897      },
2898      stream_ops: {
2899        open(stream) {
2900          var tty = TTY.ttys[stream.node.rdev];
2901          if (!tty) {
2902            throw new FS.ErrnoError(43);
2903          }
2904          stream.tty = tty;
2905          stream.seekable = false;
2906        },
2907        close(stream) {
2908          stream.tty.ops.fsync(stream.tty);
2909        },
2910        fsync(stream) {
2911          stream.tty.ops.fsync(stream.tty);
2912        },
2913        read(stream, buffer, offset, length, pos) {
2914          if (!stream.tty || !stream.tty.ops.get_char) {
2915            throw new FS.ErrnoError(60);
2916          }
2917          var bytesRead = 0;
2918          for (var i = 0; i < length; i++) {
2919            var result;
2920            try {
2921              result = stream.tty.ops.get_char(stream.tty);
2922            } catch (e) {
2923              throw new FS.ErrnoError(29);
2924            }
2925            if (result === void 0 && bytesRead === 0) {
2926              throw new FS.ErrnoError(6);
2927            }
2928            if (result === null || result === void 0) break;
2929            bytesRead++;
2930            buffer[offset + i] = result;
2931          }
2932          if (bytesRead) {
2933            stream.node.timestamp = Date.now();
2934          }
2935          return bytesRead;
2936        },
2937        write(stream, buffer, offset, length, pos) {
2938          if (!stream.tty || !stream.tty.ops.put_char) {
2939            throw new FS.ErrnoError(60);
2940          }
2941          try {
2942            for (var i = 0; i < length; i++) {
2943              stream.tty.ops.put_char(stream.tty, buffer[offset + i]);
2944            }
2945          } catch (e) {
2946            throw new FS.ErrnoError(29);
2947          }
2948          if (length) {
2949            stream.node.timestamp = Date.now();
2950          }
2951          return i;
2952        }
2953      },
2954      default_tty_ops: {
2955        get_char(tty) {
2956          return FS_stdin_getChar();
2957        },
2958        put_char(tty, val) {
2959          if (val === null || val === 10) {
2960            out(UTF8ArrayToString(tty.output));
2961            tty.output = [];
2962          } else {
2963            if (val != 0) tty.output.push(val);
2964          }
2965        },
2966        fsync(tty) {
2967          if (tty.output && tty.output.length > 0) {
2968            out(UTF8ArrayToString(tty.output));
2969            tty.output = [];
2970          }
2971        },
2972        ioctl_tcgets(tty) {
2973          return {
2974            c_iflag: 25856,
2975            c_oflag: 5,
2976            c_cflag: 191,
2977            c_lflag: 35387,
2978            c_cc: [
2979              3,
2980              28,
2981              127,
2982              21,
2983              4,
2984              0,
2985              1,
2986              0,
2987              17,
2988              19,
2989              26,
2990              0,
2991              18,
2992              15,
2993              23,
2994              22,
2995              0,
2996              0,
2997              0,
2998              0,
2999              0,
3000              0,
3001              0,
3002              0,
3003              0,
3004              0,
3005              0,
3006              0,
3007              0,
3008              0,
3009              0,
3010              0
3011            ]
3012          };
3013        },
3014        ioctl_tcsets(tty, optional_actions, data) {
3015          return 0;
3016        },
3017        ioctl_tiocgwinsz(tty) {
3018          return [24, 80];
3019        }
3020      },
3021      default_tty1_ops: {
3022        put_char(tty, val) {
3023          if (val === null || val === 10) {
3024            err(UTF8ArrayToString(tty.output));
3025            tty.output = [];
3026          } else {
3027            if (val != 0) tty.output.push(val);
3028          }
3029        },
3030        fsync(tty) {
3031          if (tty.output && tty.output.length > 0) {
3032            err(UTF8ArrayToString(tty.output));
3033            tty.output = [];
3034          }
3035        }
3036      }
3037    };
3038    var zeroMemory = (address, size) => {
3039      HEAPU8.fill(0, address, address + size);
3040    };
3041    var alignMemory = (size, alignment) => {
3042      assert(alignment, "alignment argument is required");
3043      return Math.ceil(size / alignment) * alignment;
3044    };
3045    var mmapAlloc = (size) => {
3046      size = alignMemory(size, 65536);
3047      var ptr = _emscripten_builtin_memalign(65536, size);
3048      if (ptr) zeroMemory(ptr, size);
3049      return ptr;
3050    };
3051    var MEMFS = {
3052      ops_table: null,
3053      mount(mount) {
3054        return MEMFS.createNode(null, "/", 16384 | 511, 0);
3055      },
3056      createNode(parent, name, mode, dev) {
3057        if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
3058          throw new FS.ErrnoError(63);
3059        }
3060        MEMFS.ops_table || (MEMFS.ops_table = {
3061          dir: {
3062            node: {
3063              getattr: MEMFS.node_ops.getattr,
3064              setattr: MEMFS.node_ops.setattr,
3065              lookup: MEMFS.node_ops.lookup,
3066              mknod: MEMFS.node_ops.mknod,
3067              rename: MEMFS.node_ops.rename,
3068              unlink: MEMFS.node_ops.unlink,
3069              rmdir: MEMFS.node_ops.rmdir,
3070              readdir: MEMFS.node_ops.readdir,
3071              symlink: MEMFS.node_ops.symlink
3072            },
3073            stream: {
3074              llseek: MEMFS.stream_ops.llseek
3075            }
3076          },
3077          file: {
3078            node: {
3079              getattr: MEMFS.node_ops.getattr,
3080              setattr: MEMFS.node_ops.setattr
3081            },
3082            stream: {
3083              llseek: MEMFS.stream_ops.llseek,
3084              read: MEMFS.stream_ops.read,
3085              write: MEMFS.stream_ops.write,
3086              allocate: MEMFS.stream_ops.allocate,
3087              mmap: MEMFS.stream_ops.mmap,
3088              msync: MEMFS.stream_ops.msync
3089            }
3090          },
3091          link: {
3092            node: {
3093              getattr: MEMFS.node_ops.getattr,
3094              setattr: MEMFS.node_ops.setattr,
3095              readlink: MEMFS.node_ops.readlink
3096            },
3097            stream: {}
3098          },
3099          chrdev: {
3100            node: {
3101              getattr: MEMFS.node_ops.getattr,
3102              setattr: MEMFS.node_ops.setattr
3103            },
3104            stream: FS.chrdev_stream_ops
3105          }
3106        });
3107        var node = FS.createNode(parent, name, mode, dev);
3108        if (FS.isDir(node.mode)) {
3109          node.node_ops = MEMFS.ops_table.dir.node;
3110          node.stream_ops = MEMFS.ops_table.dir.stream;
3111          node.contents = {};
3112        } else if (FS.isFile(node.mode)) {
3113          node.node_ops = MEMFS.ops_table.file.node;
3114          node.stream_ops = MEMFS.ops_table.file.stream;
3115          node.usedBytes = 0;
3116          node.contents = null;
3117        } else if (FS.isLink(node.mode)) {
3118          node.node_ops = MEMFS.ops_table.link.node;
3119          node.stream_ops = MEMFS.ops_table.link.stream;
3120        } else if (FS.isChrdev(node.mode)) {
3121          node.node_ops = MEMFS.ops_table.chrdev.node;
3122          node.stream_ops = MEMFS.ops_table.chrdev.stream;
3123        }
3124        node.timestamp = Date.now();
3125        if (parent) {
3126          parent.contents[name] = node;
3127          parent.timestamp = node.timestamp;
3128        }
3129        return node;
3130      },
3131      getFileDataAsTypedArray(node) {
3132        if (!node.contents) return new Uint8Array(0);
3133        if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes);
3134        return new Uint8Array(node.contents);
3135      },
3136      expandFileStorage(node, newCapacity) {
3137        var prevCapacity = node.contents ? node.contents.length : 0;
3138        if (prevCapacity >= newCapacity) return;
3139        var CAPACITY_DOUBLING_MAX = 1024 * 1024;
3140        newCapacity = Math.max(
3141          newCapacity,
3142          prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0
3143        );
3144        if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256);
3145        var oldContents = node.contents;
3146        node.contents = new Uint8Array(newCapacity);
3147        if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0);
3148      },
3149      resizeFileStorage(node, newSize) {
3150        if (node.usedBytes == newSize) return;
3151        if (newSize == 0) {
3152          node.contents = null;
3153          node.usedBytes = 0;
3154        } else {
3155          var oldContents = node.contents;
3156          node.contents = new Uint8Array(newSize);
3157          if (oldContents) {
3158            node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));
3159          }
3160          node.usedBytes = newSize;
3161        }
3162      },
3163      node_ops: {
3164        getattr(node) {
3165          var attr = {};
3166          attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
3167          attr.ino = node.id;
3168          attr.mode = node.mode;
3169          attr.nlink = 1;
3170          attr.uid = 0;
3171          attr.gid = 0;
3172          attr.rdev = node.rdev;
3173          if (FS.isDir(node.mode)) {
3174            attr.size = 4096;
3175          } else if (FS.isFile(node.mode)) {
3176            attr.size = node.usedBytes;
3177          } else if (FS.isLink(node.mode)) {
3178            attr.size = node.link.length;
3179          } else {
3180            attr.size = 0;
3181          }
3182          attr.atime = new Date(node.timestamp);
3183          attr.mtime = new Date(node.timestamp);
3184          attr.ctime = new Date(node.timestamp);
3185          attr.blksize = 4096;
3186          attr.blocks = Math.ceil(attr.size / attr.blksize);
3187          return attr;
3188        },
3189        setattr(node, attr) {
3190          if (attr.mode !== void 0) {
3191            node.mode = attr.mode;
3192          }
3193          if (attr.timestamp !== void 0) {
3194            node.timestamp = attr.timestamp;
3195          }
3196          if (attr.size !== void 0) {
3197            MEMFS.resizeFileStorage(node, attr.size);
3198          }
3199        },
3200        lookup(parent, name) {
3201          throw FS.genericErrors[44];
3202        },
3203        mknod(parent, name, mode, dev) {
3204          return MEMFS.createNode(parent, name, mode, dev);
3205        },
3206        rename(old_node, new_dir, new_name) {
3207          if (FS.isDir(old_node.mode)) {
3208            var new_node;
3209            try {
vendor: 4,519 bytes, lines 3210-3329
3210              new_node = FS.lookupNode(new_dir, new_name);
3211            } catch (e) {
3212            }
3213            if (new_node) {
3214              for (var i in new_node.contents) {
3215                throw new FS.ErrnoError(55);
3216              }
3217            }
3218          }
3219          delete old_node.parent.contents[old_node.name];
3220          old_node.parent.timestamp = Date.now();
3221          old_node.name = new_name;
3222          new_dir.contents[new_name] = old_node;
3223          new_dir.timestamp = old_node.parent.timestamp;
3224        },
3225        unlink(parent, name) {
3226          delete parent.contents[name];
3227          parent.timestamp = Date.now();
3228        },
3229        rmdir(parent, name) {
3230          var node = FS.lookupNode(parent, name);
3231          for (var i in node.contents) {
3232            throw new FS.ErrnoError(55);
3233          }
3234          delete parent.contents[name];
3235          parent.timestamp = Date.now();
3236        },
3237        readdir(node) {
3238          var entries = [".", ".."];
3239          for (var key of Object.keys(node.contents)) {
3240            entries.push(key);
3241          }
3242          return entries;
3243        },
3244        symlink(parent, newname, oldpath) {
3245          var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);
3246          node.link = oldpath;
3247          return node;
3248        },
3249        readlink(node) {
3250          if (!FS.isLink(node.mode)) {
3251            throw new FS.ErrnoError(28);
3252          }
3253          return node.link;
3254        }
3255      },
3256      stream_ops: {
3257        read(stream, buffer, offset, length, position) {
3258          var contents = stream.node.contents;
3259          if (position >= stream.node.usedBytes) return 0;
3260          var size = Math.min(stream.node.usedBytes - position, length);
3261          assert(size >= 0);
3262          if (size > 8 && contents.subarray) {
3263            buffer.set(contents.subarray(position, position + size), offset);
3264          } else {
3265            for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
3266          }
3267          return size;
3268        },
3269        write(stream, buffer, offset, length, position, canOwn) {
3270          assert(!(buffer instanceof ArrayBuffer));
3271          if (buffer.buffer === HEAP8.buffer) {
3272            canOwn = false;
3273          }
3274          if (!length) return 0;
3275          var node = stream.node;
3276          node.timestamp = Date.now();
3277          if (buffer.subarray && (!node.contents || node.contents.subarray)) {
3278            if (canOwn) {
3279              assert(position === 0, "canOwn must imply no weird position inside the file");
3280              node.contents = buffer.subarray(offset, offset + length);
3281              node.usedBytes = length;
3282              return length;
3283            } else if (node.usedBytes === 0 && position === 0) {
3284              node.contents = buffer.slice(offset, offset + length);
3285              node.usedBytes = length;
3286              return length;
3287            } else if (position + length <= node.usedBytes) {
3288              node.contents.set(buffer.subarray(offset, offset + length), position);
3289              return length;
3290            }
3291          }
3292          MEMFS.expandFileStorage(node, position + length);
3293          if (node.contents.subarray && buffer.subarray) {
3294            node.contents.set(buffer.subarray(offset, offset + length), position);
3295          } else {
3296            for (var i = 0; i < length; i++) {
3297              node.contents[position + i] = buffer[offset + i];
3298            }
3299          }
3300          node.usedBytes = Math.max(node.usedBytes, position + length);
3301          return length;
3302        },
3303        llseek(stream, offset, whence) {
3304          var position = offset;
3305          if (whence === 1) {
3306            position += stream.position;
3307          } else if (whence === 2) {
3308            if (FS.isFile(stream.node.mode)) {
3309              position += stream.node.usedBytes;
3310            }
3311          }
3312          if (position < 0) {
3313            throw new FS.ErrnoError(28);
3314          }
3315          return position;
3316        },
3317        allocate(stream, offset, length) {
3318          MEMFS.expandFileStorage(stream.node, offset + length);
3319          stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);
3320        },
3321        mmap(stream, length, position, prot, flags) {
3322          if (!FS.isFile(stream.node.mode)) {
3323            throw new FS.ErrnoError(43);
3324          }
3325          var ptr;
3326          var allocated;
3327          var contents = stream.node.contents;
3328          if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {
3329            allocated = false;
3330            ptr = contents.byteOffset;
3331          } else {
3332            allocated = true;
3333            ptr = mmapAlloc(length);
3334            if (!ptr) {
3335              throw new FS.ErrnoError(48);
3336            }
3337            if (contents) {
3338              if (position > 0 || position + length < contents.length) {
3339                if (contents.subarray) {
3340                  contents = contents.subarray(position, position + length);
3341                } else {
3342                  contents = Array.prototype.slice.call(contents, position, position + length);
3343                }
3344              }
3345              HEAP8.set(contents, ptr);
3346            }
3347          }
3348          return { ptr, allocated };
3349        },
3350        msync(stream, buffer, offset, length, mmapFlags) {
3351          MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
3352          return 0;
3353        }
3354      }
3355    };
3356    var asyncLoad = (url, onload, onerror, noRunDep) => {
3357      var dep = getUniqueRunDependency(\`al \${url}\`);
3358      readAsync(url).then(
3359        (arrayBuffer) => {
3360          assert(arrayBuffer, \`Loading data file "\${url}" failed (no arrayBuffer).\`);
3361          onload(new Uint8Array(arrayBuffer));
3362          if (dep) removeRunDependency(dep);
3363        },
3364        (err2) => {
3365          if (onerror) {
3366            onerror();
3367          } else {
3368            throw \`Loading data file "\${url}" failed.\`;
3369          }
3370        }
3371      );
3372      if (dep) addRunDependency(dep);
3373    };
3374    var FS_createDataFile = (parent, name, fileData, canRead, canWrite, canOwn) => {
3375      FS.createDataFile(parent, name, fileData, canRead, canWrite, canOwn);
3376    };
3377    var preloadPlugins = Module["preloadPlugins"] || [];
3378    var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => {
3379      if (typeof Browser != "undefined") Browser.init();
3380      var handled = false;
3381      preloadPlugins.forEach((plugin) => {
3382        if (handled) return;
3383        if (plugin["canHandle"](fullname)) {
3384          plugin["handle"](byteArray, fullname, finish, onerror);
3385          handled = true;
3386        }
3387      });
3388      return handled;
3389    };
3390    var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
3391      var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
3392      var dep = getUniqueRunDependency(\`cp \${fullname}\`);
3393      function processData(byteArray) {
3394        function finish(byteArray2) {
3395          preFinish == null ? void 0 : preFinish();
3396          if (!dontCreateFile) {
3397            FS_createDataFile(parent, name, byteArray2, canRead, canWrite, canOwn);
3398          }
3399          onload == null ? void 0 : onload();
3400          removeRunDependency(dep);
3401        }
3402        if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => {
3403          onerror == null ? void 0 : onerror();
3404          removeRunDependency(dep);
3405        })) {
3406          return;
3407        }
3408        finish(byteArray);
3409      }
3410      addRunDependency(dep);
3411      if (typeof url == "string") {
3412        asyncLoad(url, processData, onerror);
3413      } else {
3414        processData(url);
3415      }
3416    };
3417    var FS_modeStringToFlags = (str) => {
3418      var flagModes = {
3419        r: 0,
3420        "r+": 2,
3421        w: 512 | 64 | 1,
3422        "w+": 512 | 64 | 2,
3423        a: 1024 | 64 | 1,
3424        "a+": 1024 | 64 | 2
3425      };
3426      var flags = flagModes[str];
3427      if (typeof flags == "undefined") {
3428        throw new Error(\`Unknown file open mode: \${str}\`);
3429      }
3430      return flags;
3431    };
3432    var FS_getMode = (canRead, canWrite) => {
3433      var mode = 0;
3434      if (canRead) mode |= 292 | 73;
3435      if (canWrite) mode |= 146;
3436      return mode;
3437    };
3438    var strError = (errno) => {
3439      return UTF8ToString(_strerror(errno));
3440    };
3441    var ERRNO_CODES = {
3442      EPERM: 63,
3443      ENOENT: 44,
3444      ESRCH: 71,
3445      EINTR: 27,
3446      EIO: 29,
3447      ENXIO: 60,
3448      E2BIG: 1,
3449      ENOEXEC: 45,
3450      EBADF: 8,
3451      ECHILD: 12,
3452      EAGAIN: 6,
3453      EWOULDBLOCK: 6,
3454      ENOMEM: 48,
3455      EACCES: 2,
3456      EFAULT: 21,
3457      ENOTBLK: 105,
3458      EBUSY: 10,
3459      EEXIST: 20,
3460      EXDEV: 75,
3461      ENODEV: 43,
3462      ENOTDIR: 54,
vendor: 4,549 bytes, lines 3463-3647
3463      EISDIR: 31,
3464      EINVAL: 28,
3465      ENFILE: 41,
3466      EMFILE: 33,
3467      ENOTTY: 59,
3468      ETXTBSY: 74,
3469      EFBIG: 22,
3470      ENOSPC: 51,
3471      ESPIPE: 70,
3472      EROFS: 69,
3473      EMLINK: 34,
3474      EPIPE: 64,
3475      EDOM: 18,
3476      ERANGE: 68,
3477      ENOMSG: 49,
3478      EIDRM: 24,
3479      ECHRNG: 106,
3480      EL2NSYNC: 156,
3481      EL3HLT: 107,
3482      EL3RST: 108,
3483      ELNRNG: 109,
3484      EUNATCH: 110,
3485      ENOCSI: 111,
3486      EL2HLT: 112,
3487      EDEADLK: 16,
3488      ENOLCK: 46,
3489      EBADE: 113,
3490      EBADR: 114,
3491      EXFULL: 115,
3492      ENOANO: 104,
3493      EBADRQC: 103,
3494      EBADSLT: 102,
3495      EDEADLOCK: 16,
3496      EBFONT: 101,
3497      ENOSTR: 100,
3498      ENODATA: 116,
3499      ETIME: 117,
3500      ENOSR: 118,
3501      ENONET: 119,
3502      ENOPKG: 120,
3503      EREMOTE: 121,
3504      ENOLINK: 47,
3505      EADV: 122,
3506      ESRMNT: 123,
3507      ECOMM: 124,
3508      EPROTO: 65,
3509      EMULTIHOP: 36,
3510      EDOTDOT: 125,
3511      EBADMSG: 9,
3512      ENOTUNIQ: 126,
3513      EBADFD: 127,
3514      EREMCHG: 128,
3515      ELIBACC: 129,
3516      ELIBBAD: 130,
3517      ELIBSCN: 131,
3518      ELIBMAX: 132,
3519      ELIBEXEC: 133,
3520      ENOSYS: 52,
3521      ENOTEMPTY: 55,
3522      ENAMETOOLONG: 37,
3523      ELOOP: 32,
3524      EOPNOTSUPP: 138,
3525      EPFNOSUPPORT: 139,
3526      ECONNRESET: 15,
3527      ENOBUFS: 42,
3528      EAFNOSUPPORT: 5,
3529      EPROTOTYPE: 67,
3530      ENOTSOCK: 57,
3531      ENOPROTOOPT: 50,
3532      ESHUTDOWN: 140,
3533      ECONNREFUSED: 14,
3534      EADDRINUSE: 3,
3535      ECONNABORTED: 13,
3536      ENETUNREACH: 40,
3537      ENETDOWN: 38,
3538      ETIMEDOUT: 73,
3539      EHOSTDOWN: 142,
3540      EHOSTUNREACH: 23,
3541      EINPROGRESS: 26,
3542      EALREADY: 7,
3543      EDESTADDRREQ: 17,
3544      EMSGSIZE: 35,
3545      EPROTONOSUPPORT: 66,
3546      ESOCKTNOSUPPORT: 137,
3547      EADDRNOTAVAIL: 4,
3548      ENETRESET: 39,
3549      EISCONN: 30,
3550      ENOTCONN: 53,
3551      ETOOMANYREFS: 141,
3552      EUSERS: 136,
3553      EDQUOT: 19,
3554      ESTALE: 72,
3555      ENOTSUP: 138,
3556      ENOMEDIUM: 148,
3557      EILSEQ: 25,
3558      EOVERFLOW: 61,
3559      ECANCELED: 11,
3560      ENOTRECOVERABLE: 56,
3561      EOWNERDEAD: 62,
3562      ESTRPIPE: 135
3563    };
3564    var FS = {
3565      root: null,
3566      mounts: [],
3567      devices: {},
3568      streams: [],
3569      nextInode: 1,
3570      nameTable: null,
3571      currentPath: "/",
3572      initialized: false,
3573      ignorePermissions: true,
3574      ErrnoError: class extends Error {
3575        // We set the \`name\` property to be able to identify \`FS.ErrnoError\`
3576        // - the \`name\` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.
3577        // - when using PROXYFS, an error can come from an underlying FS
3578        // as different FS objects have their own FS.ErrnoError each,
3579        // the test \`err instanceof FS.ErrnoError\` won't detect an error coming from another filesystem, causing bugs.
3580        // we'll use the reliable test \`err.name == "ErrnoError"\` instead
3581        constructor(errno) {
3582          super(runtimeInitialized ? strError(errno) : "");
3583          this.name = "ErrnoError";
3584          this.errno = errno;
3585          for (var key in ERRNO_CODES) {
3586            if (ERRNO_CODES[key] === errno) {
3587              this.code = key;
3588              break;
3589            }
3590          }
3591        }
3592      },
3593      genericErrors: {},
3594      filesystems: null,
3595      syncFSRequests: 0,
3596      readFiles: {},
3597      FSStream: class {
3598        constructor() {
3599          this.shared = {};
3600        }
3601        get object() {
3602          return this.node;
3603        }
3604        set object(val) {
3605          this.node = val;
3606        }
3607        get isRead() {
3608          return (this.flags & 2097155) !== 1;
3609        }
3610        get isWrite() {
3611          return (this.flags & 2097155) !== 0;
3612        }
3613        get isAppend() {
3614          return this.flags & 1024;
3615        }
3616        get flags() {
3617          return this.shared.flags;
3618        }
3619        set flags(val) {
3620          this.shared.flags = val;
3621        }
3622        get position() {
3623          return this.shared.position;
3624        }
3625        set position(val) {
3626          this.shared.position = val;
3627        }
3628      },
3629      FSNode: class {
3630        constructor(parent, name, mode, rdev) {
3631          if (!parent) {
3632            parent = this;
3633          }
3634          this.parent = parent;
3635          this.mount = parent.mount;
3636          this.mounted = null;
3637          this.id = FS.nextInode++;
3638          this.name = name;
3639          this.mode = mode;
3640          this.node_ops = {};
3641          this.stream_ops = {};
3642          this.rdev = rdev;
3643          this.readMode = 292 | 73;
3644          this.writeMode = 146;
3645        }
3646        get read() {
3647          return (this.mode & this.readMode) === this.readMode;
3648        }
3649        set read(val) {
3650          val ? this.mode |= this.readMode : this.mode &= ~this.readMode;
3651        }
3652        get write() {
3653          return (this.mode & this.writeMode) === this.writeMode;
3654        }
3655        set write(val) {
3656          val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;
3657        }
3658        get isFolder() {
3659          return FS.isDir(this.mode);
3660        }
3661        get isDevice() {
3662          return FS.isChrdev(this.mode);
3663        }
3664      },
3665      lookupPath(path, opts = {}) {
3666        path = PATH_FS.resolve(path);
3667        if (!path) return { path: "", node: null };
3668        var defaults = {
3669          follow_mount: true,
3670          recurse_count: 0
3671        };
3672        opts = Object.assign(defaults, opts);
3673        if (opts.recurse_count > 8) {
3674          throw new FS.ErrnoError(32);
3675        }
3676        var parts = path.split("/").filter((p) => !!p);
3677        var current = FS.root;
3678        var current_path = "/";
3679        for (var i = 0; i < parts.length; i++) {
3680          var islast = i === parts.length - 1;
3681          if (islast && opts.parent) {
3682            break;
3683          }
3684          current = FS.lookupNode(current, parts[i]);
3685          current_path = PATH.join2(current_path, parts[i]);
3686          if (FS.isMountpoint(current)) {
3687            if (!islast || islast && opts.follow_mount) {
3688              current = current.mounted.root;
3689            }
3690          }
3691          if (!islast || opts.follow) {
3692            var count = 0;
3693            while (FS.isLink(current.mode)) {
3694              var link = FS.readlink(current_path);
3695              current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
3696              var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count + 1 });
3697              current = lookup.node;
3698              if (count++ > 40) {
3699                throw new FS.ErrnoError(32);
3700              }
3701            }
3702          }
3703        }
3704        return { path: current_path, node: current };
3705      },
3706      getPath(node) {
3707        var path;
3708        while (true) {
3709          if (FS.isRoot(node)) {
3710            var mount = node.mount.mountpoint;
3711            if (!path) return mount;
3712            return mount[mount.length - 1] !== "/" ? \`\${mount}/\${path}\` : mount + path;
3713          }
3714          path = path ? \`\${node.name}/\${path}\` : node.name;
3715          node = node.parent;
3716        }
3717      },
3718      hashName(parentid, name) {
3719        var hash = 0;
3720        for (var i = 0; i < name.length; i++) {
3721          hash = (hash << 5) - hash + name.charCodeAt(i) | 0;
3722        }
3723        return (parentid + hash >>> 0) % FS.nameTable.length;
3724      },
3725      hashAddNode(node) {
3726        var hash = FS.hashName(node.parent.id, node.name);
3727        node.name_next = FS.nameTable[hash];
3728        FS.nameTable[hash] = node;
3729      },
3730      hashRemoveNode(node) {
3731        var hash = FS.hashName(node.parent.id, node.name);
3732        if (FS.nameTable[hash] === node) {
3733          FS.nameTable[hash] = node.name_next;
3734        } else {
3735          var current = FS.nameTable[hash];
3736          while (current) {
3737            if (current.name_next === node) {
3738              current.name_next = node.name_next;
3739              break;
3740            }
3741            current = current.name_next;
3742          }
3743        }
3744      },
3745      lookupNode(parent, name) {
3746        var errCode = FS.mayLookup(parent);
3747        if (errCode) {
3748          throw new FS.ErrnoError(errCode);
3749        }
3750        var hash = FS.hashName(parent.id, name);
3751        for (var node = FS.nameTable[hash]; node; node = node.name_next) {
3752          var nodeName = node.name;
3753          if (node.parent.id === parent.id && nodeName === name) {
3754            return node;
3755          }
3756        }
3757        return FS.lookup(parent, name);
3758      },
3759      createNode(parent, name, mode, rdev) {
3760        assert(typeof parent == "object");
3761        var node = new FS.FSNode(parent, name, mode, rdev);
3762        FS.hashAddNode(node);
3763        return node;
3764      },
3765      destroyNode(node) {
3766        FS.hashRemoveNode(node);
3767      },
3768      isRoot(node) {
3769        return node === node.parent;
3770      },
3771      isMountpoint(node) {
3772        return !!node.mounted;
3773      },
3774      isFile(mode) {
3775        return (mode & 61440) === 32768;
3776      },
3777      isDir(mode) {
3778        return (mode & 61440) === 16384;
3779      },
3780      isLink(mode) {
3781        return (mode & 61440) === 40960;
3782      },
3783      isChrdev(mode) {
3784        return (mode & 61440) === 8192;
3785      },
3786      isBlkdev(mode) {
3787        return (mode & 61440) === 24576;
3788      },
3789      isFIFO(mode) {
3790        return (mode & 61440) === 4096;
3791      },
3792      isSocket(mode) {
3793        return (mode & 49152) === 49152;
3794      },
3795      flagsToPermissionString(flag) {
3796        var perms = ["r", "w", "rw"][flag & 3];
3797        if (flag & 512) {
3798          perms += "w";
3799        }
3800        return perms;
3801      },
3802      nodePermissions(node, perms) {
3803        if (FS.ignorePermissions) {
3804          return 0;
3805        }
3806        if (perms.includes("r") && !(node.mode & 292)) {
3807          return 2;
3808        } else if (perms.includes("w") && !(node.mode & 146)) {
3809          return 2;
3810        } else if (perms.includes("x") && !(node.mode & 73)) {
3811          return 2;
3812        }
3813        return 0;
3814      },
3815      mayLookup(dir) {
3816        if (!FS.isDir(dir.mode)) return 54;
3817        var errCode = FS.nodePermissions(dir, "x");
3818        if (errCode) return errCode;
3819        if (!dir.node_ops.lookup) return 2;
3820        return 0;
3821      },
3822      mayCreate(dir, name) {
3823        try {
3824          var node = FS.lookupNode(dir, name);
3825          return 20;
3826        } catch (e) {
3827        }
3828        return FS.nodePermissions(dir, "wx");
3829      },
3830      mayDelete(dir, name, isdir) {
3831        var node;
3832        try {
3833          node = FS.lookupNode(dir, name);
3834        } catch (e) {
3835          return e.errno;
3836        }
3837        var errCode = FS.nodePermissions(dir, "wx");
3838        if (errCode) {
3839          return errCode;
3840        }
3841        if (isdir) {
3842          if (!FS.isDir(node.mode)) {
3843            return 54;
3844          }
3845          if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
3846            return 10;
3847          }
3848        } else {
3849          if (FS.isDir(node.mode)) {
3850            return 31;
3851          }
3852        }
3853        return 0;
3854      },
3855      mayOpen(node, flags) {
3856        if (!node) {
3857          return 44;
3858        }
3859        if (FS.isLink(node.mode)) {
3860          return 32;
3861        } else if (FS.isDir(node.mode)) {
3862          if (FS.flagsToPermissionString(flags) !== "r" || // opening for write
3863          flags & 512) {
3864            return 31;
3865          }
3866        }
3867        return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
3868      },
3869      MAX_OPEN_FDS: 4096,
3870      nextfd() {
3871        for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {
3872          if (!FS.streams[fd]) {
3873            return fd;
3874          }
3875        }
3876        throw new FS.ErrnoError(33);
3877      },
3878      getStreamChecked(fd) {
3879        var stream = FS.getStream(fd);
3880        if (!stream) {
3881          throw new FS.ErrnoError(8);
3882        }
3883        return stream;
3884      },
3885      getStream: (fd) => FS.streams[fd],
3886      createStream(stream, fd = -1) {
3887        assert(fd >= -1);
3888        stream = Object.assign(new FS.FSStream(), stream);
3889        if (fd == -1) {
3890          fd = FS.nextfd();
3891        }
3892        stream.fd = fd;
3893        FS.streams[fd] = stream;
3894        return stream;
3895      },
3896      closeStream(fd) {
3897        FS.streams[fd] = null;
3898      },
3899      dupStream(origStream, fd = -1) {
3900        var _a, _b;
3901        var stream = FS.createStream(origStream, fd);
3902        (_b = (_a = stream.stream_ops) == null ? void 0 : _a.dup) == null ? void 0 : _b.call(_a, stream);
3903        return stream;
3904      },
3905      chrdev_stream_ops: {
3906        open(stream) {
3907          var _a, _b;
3908          var device = FS.getDevice(stream.node.rdev);
3909          stream.stream_ops = device.stream_ops;
3910          (_b = (_a = stream.stream_ops).open) == null ? void 0 : _b.call(_a, stream);
3911        },
3912        llseek() {
3913          throw new FS.ErrnoError(70);
3914        }
3915      },
3916      major: (dev) => dev >> 8,
3917      minor: (dev) => dev & 255,
3918      makedev: (ma, mi) => ma << 8 | mi,
3919      registerDevice(dev, ops) {
3920        FS.devices[dev] = { stream_ops: ops };
3921      },
3922      getDevice: (dev) => FS.devices[dev],
3923      getMounts(mount) {
3924        var mounts = [];
3925        var check = [mount];
3926        while (check.length) {
3927          var m = check.pop();
3928          mounts.push(m);
3929          check.push(...m.mounts);
3930        }
3931        return mounts;
3932      },
3933      syncfs(populate, callback) {
3934        if (typeof populate == "function") {
3935          callback = populate;
3936          populate = false;
3937        }
3938        FS.syncFSRequests++;
3939        if (FS.syncFSRequests > 1) {
3940          err(
3941            \`warning: \${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work\`
3942          );
3943        }
3944        var mounts = FS.getMounts(FS.root.mount);
3945        var completed = 0;
3946        function doCallback(errCode) {
3947          assert(FS.syncFSRequests > 0);
3948          FS.syncFSRequests--;
3949          return callback(errCode);
3950        }
3951        function done(errCode) {
3952          if (errCode) {
3953            if (!done.errored) {
3954              done.errored = true;
3955              return doCallback(errCode);
3956            }
3957            return;
3958          }
3959          if (++completed >= mounts.length) {
3960            doCallback(null);
3961          }
3962        }
3963        mounts.forEach((mount) => {
3964          if (!mount.type.syncfs) {
3965            return done(null);
3966          }
3967          mount.type.syncfs(mount, populate, done);
3968        });
3969      },
3970      mount(type, opts, mountpoint) {
3971        if (typeof type == "string") {
3972          throw type;
3973        }
3974        var root = mountpoint === "/";
3975        var pseudo = !mountpoint;
3976        var node;
3977        if (root && FS.root) {
3978          throw new FS.ErrnoError(10);
3979        } else if (!root && !pseudo) {
3980          var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
3981          mountpoint = lookup.path;
3982          node = lookup.node;
3983          if (FS.isMountpoint(node)) {
3984            throw new FS.ErrnoError(10);
3985          }
3986          if (!FS.isDir(node.mode)) {
3987            throw new FS.ErrnoError(54);
3988          }
3989        }
3990        var mount = {
3991          type,
3992          opts,
3993          mountpoint,
3994          mounts: []
3995        };
3996        var mountRoot = type.mount(mount);
3997        mountRoot.mount = mount;
3998        mount.root = mountRoot;
3999        if (root) {
4000          FS.root = mountRoot;
4001        } else if (node) {
4002          node.mounted = mount;
4003          if (node.mount) {
4004            node.mount.mounts.push(mount);
4005          }
4006        }
4007        return mountRoot;
4008      },
4009      unmount(mountpoint) {
4010        var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
4011        if (!FS.isMountpoint(lookup.node)) {
4012          throw new FS.ErrnoError(28);
4013        }
4014        var node = lookup.node;
vendor: 25,470 bytes, lines 4015-4799
4015        var mount = node.mounted;
4016        var mounts = FS.getMounts(mount);
4017        Object.keys(FS.nameTable).forEach((hash) => {
4018          var current = FS.nameTable[hash];
4019          while (current) {
4020            var next = current.name_next;
4021            if (mounts.includes(current.mount)) {
4022              FS.destroyNode(current);
4023            }
4024            current = next;
4025          }
4026        });
4027        node.mounted = null;
4028        var idx = node.mount.mounts.indexOf(mount);
4029        assert(idx !== -1);
4030        node.mount.mounts.splice(idx, 1);
4031      },
4032      lookup(parent, name) {
4033        return parent.node_ops.lookup(parent, name);
4034      },
4035      mknod(path, mode, dev) {
4036        var lookup = FS.lookupPath(path, { parent: true });
4037        var parent = lookup.node;
4038        var name = PATH.basename(path);
4039        if (!name || name === "." || name === "..") {
4040          throw new FS.ErrnoError(28);
4041        }
4042        var errCode = FS.mayCreate(parent, name);
4043        if (errCode) {
4044          throw new FS.ErrnoError(errCode);
4045        }
4046        if (!parent.node_ops.mknod) {
4047          throw new FS.ErrnoError(63);
4048        }
4049        return parent.node_ops.mknod(parent, name, mode, dev);
4050      },
4051      create(path, mode) {
4052        mode = mode !== void 0 ? mode : 438;
4053        mode &= 4095;
4054        mode |= 32768;
4055        return FS.mknod(path, mode, 0);
4056      },
4057      mkdir(path, mode) {
4058        mode = mode !== void 0 ? mode : 511;
4059        mode &= 511 | 512;
4060        mode |= 16384;
4061        return FS.mknod(path, mode, 0);
4062      },
4063      mkdirTree(path, mode) {
4064        var dirs = path.split("/");
4065        var d = "";
4066        for (var i = 0; i < dirs.length; ++i) {
4067          if (!dirs[i]) continue;
4068          d += "/" + dirs[i];
4069          try {
4070            FS.mkdir(d, mode);
4071          } catch (e) {
4072            if (e.errno != 20) throw e;
4073          }
4074        }
4075      },
4076      mkdev(path, mode, dev) {
4077        if (typeof dev == "undefined") {
4078          dev = mode;
4079          mode = 438;
4080        }
4081        mode |= 8192;
4082        return FS.mknod(path, mode, dev);
4083      },
4084      symlink(oldpath, newpath) {
4085        if (!PATH_FS.resolve(oldpath)) {
4086          throw new FS.ErrnoError(44);
4087        }
4088        var lookup = FS.lookupPath(newpath, { parent: true });
4089        var parent = lookup.node;
4090        if (!parent) {
4091          throw new FS.ErrnoError(44);
4092        }
4093        var newname = PATH.basename(newpath);
4094        var errCode = FS.mayCreate(parent, newname);
4095        if (errCode) {
4096          throw new FS.ErrnoError(errCode);
4097        }
4098        if (!parent.node_ops.symlink) {
4099          throw new FS.ErrnoError(63);
4100        }
4101        return parent.node_ops.symlink(parent, newname, oldpath);
4102      },
4103      rename(old_path, new_path) {
4104        var old_dirname = PATH.dirname(old_path);
4105        var new_dirname = PATH.dirname(new_path);
4106        var old_name = PATH.basename(old_path);
4107        var new_name = PATH.basename(new_path);
4108        var lookup, old_dir, new_dir;
4109        lookup = FS.lookupPath(old_path, { parent: true });
4110        old_dir = lookup.node;
4111        lookup = FS.lookupPath(new_path, { parent: true });
4112        new_dir = lookup.node;
4113        if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
4114        if (old_dir.mount !== new_dir.mount) {
4115          throw new FS.ErrnoError(75);
4116        }
4117        var old_node = FS.lookupNode(old_dir, old_name);
4118        var relative = PATH_FS.relative(old_path, new_dirname);
4119        if (relative.charAt(0) !== ".") {
4120          throw new FS.ErrnoError(28);
4121        }
4122        relative = PATH_FS.relative(new_path, old_dirname);
4123        if (relative.charAt(0) !== ".") {
4124          throw new FS.ErrnoError(55);
4125        }
4126        var new_node;
4127        try {
4128          new_node = FS.lookupNode(new_dir, new_name);
4129        } catch (e) {
4130        }
4131        if (old_node === new_node) {
4132          return;
4133        }
4134        var isdir = FS.isDir(old_node.mode);
4135        var errCode = FS.mayDelete(old_dir, old_name, isdir);
4136        if (errCode) {
4137          throw new FS.ErrnoError(errCode);
4138        }
4139        errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);
4140        if (errCode) {
4141          throw new FS.ErrnoError(errCode);
4142        }
4143        if (!old_dir.node_ops.rename) {
4144          throw new FS.ErrnoError(63);
4145        }
4146        if (FS.isMountpoint(old_node) || new_node && FS.isMountpoint(new_node)) {
4147          throw new FS.ErrnoError(10);
4148        }
4149        if (new_dir !== old_dir) {
4150          errCode = FS.nodePermissions(old_dir, "w");
4151          if (errCode) {
4152            throw new FS.ErrnoError(errCode);
4153          }
4154        }
4155        FS.hashRemoveNode(old_node);
4156        try {
4157          old_dir.node_ops.rename(old_node, new_dir, new_name);
4158          old_node.parent = new_dir;
4159        } catch (e) {
4160          throw e;
4161        } finally {
4162          FS.hashAddNode(old_node);
4163        }
4164      },
4165      rmdir(path) {
4166        var lookup = FS.lookupPath(path, { parent: true });
4167        var parent = lookup.node;
4168        var name = PATH.basename(path);
4169        var node = FS.lookupNode(parent, name);
4170        var errCode = FS.mayDelete(parent, name, true);
4171        if (errCode) {
4172          throw new FS.ErrnoError(errCode);
4173        }
4174        if (!parent.node_ops.rmdir) {
4175          throw new FS.ErrnoError(63);
4176        }
4177        if (FS.isMountpoint(node)) {
4178          throw new FS.ErrnoError(10);
4179        }
4180        parent.node_ops.rmdir(parent, name);
4181        FS.destroyNode(node);
4182      },
4183      readdir(path) {
4184        var lookup = FS.lookupPath(path, { follow: true });
4185        var node = lookup.node;
4186        if (!node.node_ops.readdir) {
4187          throw new FS.ErrnoError(54);
4188        }
4189        return node.node_ops.readdir(node);
4190      },
4191      unlink(path) {
4192        var lookup = FS.lookupPath(path, { parent: true });
4193        var parent = lookup.node;
4194        if (!parent) {
4195          throw new FS.ErrnoError(44);
4196        }
4197        var name = PATH.basename(path);
4198        var node = FS.lookupNode(parent, name);
4199        var errCode = FS.mayDelete(parent, name, false);
4200        if (errCode) {
4201          throw new FS.ErrnoError(errCode);
4202        }
4203        if (!parent.node_ops.unlink) {
4204          throw new FS.ErrnoError(63);
4205        }
4206        if (FS.isMountpoint(node)) {
4207          throw new FS.ErrnoError(10);
4208        }
4209        parent.node_ops.unlink(parent, name);
4210        FS.destroyNode(node);
4211      },
4212      readlink(path) {
4213        var lookup = FS.lookupPath(path);
4214        var link = lookup.node;
4215        if (!link) {
4216          throw new FS.ErrnoError(44);
4217        }
4218        if (!link.node_ops.readlink) {
4219          throw new FS.ErrnoError(28);
4220        }
4221        return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));
4222      },
4223      stat(path, dontFollow) {
4224        var lookup = FS.lookupPath(path, { follow: !dontFollow });
4225        var node = lookup.node;
4226        if (!node) {
4227          throw new FS.ErrnoError(44);
4228        }
4229        if (!node.node_ops.getattr) {
4230          throw new FS.ErrnoError(63);
4231        }
4232        return node.node_ops.getattr(node);
4233      },
4234      lstat(path) {
4235        return FS.stat(path, true);
4236      },
4237      chmod(path, mode, dontFollow) {
4238        var node;
4239        if (typeof path == "string") {
4240          var lookup = FS.lookupPath(path, { follow: !dontFollow });
4241          node = lookup.node;
4242        } else {
4243          node = path;
4244        }
4245        if (!node.node_ops.setattr) {
4246          throw new FS.ErrnoError(63);
4247        }
4248        node.node_ops.setattr(node, {
4249          mode: mode & 4095 | node.mode & -4096,
4250          timestamp: Date.now()
4251        });
4252      },
4253      lchmod(path, mode) {
4254        FS.chmod(path, mode, true);
4255      },
4256      fchmod(fd, mode) {
4257        var stream = FS.getStreamChecked(fd);
4258        FS.chmod(stream.node, mode);
4259      },
4260      chown(path, uid, gid, dontFollow) {
4261        var node;
4262        if (typeof path == "string") {
4263          var lookup = FS.lookupPath(path, { follow: !dontFollow });
4264          node = lookup.node;
4265        } else {
4266          node = path;
4267        }
4268        if (!node.node_ops.setattr) {
4269          throw new FS.ErrnoError(63);
4270        }
4271        node.node_ops.setattr(node, {
4272          timestamp: Date.now()
4273          // we ignore the uid / gid for now
4274        });
4275      },
4276      lchown(path, uid, gid) {
4277        FS.chown(path, uid, gid, true);
4278      },
4279      fchown(fd, uid, gid) {
4280        var stream = FS.getStreamChecked(fd);
4281        FS.chown(stream.node, uid, gid);
4282      },
4283      truncate(path, len) {
4284        if (len < 0) {
4285          throw new FS.ErrnoError(28);
4286        }
4287        var node;
4288        if (typeof path == "string") {
4289          var lookup = FS.lookupPath(path, { follow: true });
4290          node = lookup.node;
4291        } else {
4292          node = path;
4293        }
4294        if (!node.node_ops.setattr) {
4295          throw new FS.ErrnoError(63);
4296        }
4297        if (FS.isDir(node.mode)) {
4298          throw new FS.ErrnoError(31);
4299        }
4300        if (!FS.isFile(node.mode)) {
4301          throw new FS.ErrnoError(28);
4302        }
4303        var errCode = FS.nodePermissions(node, "w");
4304        if (errCode) {
4305          throw new FS.ErrnoError(errCode);
4306        }
4307        node.node_ops.setattr(node, {
4308          size: len,
4309          timestamp: Date.now()
4310        });
4311      },
4312      ftruncate(fd, len) {
4313        var stream = FS.getStreamChecked(fd);
4314        if ((stream.flags & 2097155) === 0) {
4315          throw new FS.ErrnoError(28);
4316        }
4317        FS.truncate(stream.node, len);
4318      },
4319      utime(path, atime, mtime) {
4320        var lookup = FS.lookupPath(path, { follow: true });
4321        var node = lookup.node;
4322        node.node_ops.setattr(node, {
4323          timestamp: Math.max(atime, mtime)
4324        });
4325      },
4326      open(path, flags, mode) {
4327        if (path === "") {
4328          throw new FS.ErrnoError(44);
4329        }
4330        flags = typeof flags == "string" ? FS_modeStringToFlags(flags) : flags;
4331        if (flags & 64) {
4332          mode = typeof mode == "undefined" ? 438 : mode;
4333          mode = mode & 4095 | 32768;
4334        } else {
4335          mode = 0;
4336        }
4337        var node;
4338        if (typeof path == "object") {
4339          node = path;
4340        } else {
4341          path = PATH.normalize(path);
4342          try {
4343            var lookup = FS.lookupPath(path, {
4344              follow: !(flags & 131072)
4345            });
4346            node = lookup.node;
4347          } catch (e) {
4348          }
4349        }
4350        var created = false;
4351        if (flags & 64) {
4352          if (node) {
4353            if (flags & 128) {
4354              throw new FS.ErrnoError(20);
4355            }
4356          } else {
4357            node = FS.mknod(path, mode, 0);
4358            created = true;
4359          }
4360        }
4361        if (!node) {
4362          throw new FS.ErrnoError(44);
4363        }
4364        if (FS.isChrdev(node.mode)) {
4365          flags &= -513;
4366        }
4367        if (flags & 65536 && !FS.isDir(node.mode)) {
4368          throw new FS.ErrnoError(54);
4369        }
4370        if (!created) {
4371          var errCode = FS.mayOpen(node, flags);
4372          if (errCode) {
4373            throw new FS.ErrnoError(errCode);
4374          }
4375        }
4376        if (flags & 512 && !created) {
4377          FS.truncate(node, 0);
4378        }
4379        flags &= -131713;
4380        var stream = FS.createStream({
4381          node,
4382          path: FS.getPath(node),
4383          // we want the absolute path to the node
4384          flags,
4385          seekable: true,
4386          position: 0,
4387          stream_ops: node.stream_ops,
4388          // used by the file family libc calls (fopen, fwrite, ferror, etc.)
4389          ungotten: [],
4390          error: false
4391        });
4392        if (stream.stream_ops.open) {
4393          stream.stream_ops.open(stream);
4394        }
4395        if (Module["logReadFiles"] && !(flags & 1)) {
4396          if (!(path in FS.readFiles)) {
4397            FS.readFiles[path] = 1;
4398          }
4399        }
4400        return stream;
4401      },
4402      close(stream) {
4403        if (FS.isClosed(stream)) {
4404          throw new FS.ErrnoError(8);
4405        }
4406        if (stream.getdents) stream.getdents = null;
4407        try {
4408          if (stream.stream_ops.close) {
4409            stream.stream_ops.close(stream);
4410          }
4411        } catch (e) {
4412          throw e;
4413        } finally {
4414          FS.closeStream(stream.fd);
4415        }
4416        stream.fd = null;
4417      },
4418      isClosed(stream) {
4419        return stream.fd === null;
4420      },
4421      llseek(stream, offset, whence) {
4422        if (FS.isClosed(stream)) {
4423          throw new FS.ErrnoError(8);
4424        }
4425        if (!stream.seekable || !stream.stream_ops.llseek) {
4426          throw new FS.ErrnoError(70);
4427        }
4428        if (whence != 0 && whence != 1 && whence != 2) {
4429          throw new FS.ErrnoError(28);
4430        }
4431        stream.position = stream.stream_ops.llseek(stream, offset, whence);
4432        stream.ungotten = [];
4433        return stream.position;
4434      },
4435      read(stream, buffer, offset, length, position) {
4436        assert(offset >= 0);
4437        if (length < 0 || position < 0) {
4438          throw new FS.ErrnoError(28);
4439        }
4440        if (FS.isClosed(stream)) {
4441          throw new FS.ErrnoError(8);
4442        }
4443        if ((stream.flags & 2097155) === 1) {
4444          throw new FS.ErrnoError(8);
4445        }
4446        if (FS.isDir(stream.node.mode)) {
4447          throw new FS.ErrnoError(31);
4448        }
4449        if (!stream.stream_ops.read) {
4450          throw new FS.ErrnoError(28);
4451        }
4452        var seeking = typeof position != "undefined";
4453        if (!seeking) {
4454          position = stream.position;
4455        } else if (!stream.seekable) {
4456          throw new FS.ErrnoError(70);
4457        }
4458        var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
4459        if (!seeking) stream.position += bytesRead;
4460        return bytesRead;
4461      },
4462      write(stream, buffer, offset, length, position, canOwn) {
4463        assert(offset >= 0);
4464        if (length < 0 || position < 0) {
4465          throw new FS.ErrnoError(28);
4466        }
4467        if (FS.isClosed(stream)) {
4468          throw new FS.ErrnoError(8);
4469        }
4470        if ((stream.flags & 2097155) === 0) {
4471          throw new FS.ErrnoError(8);
4472        }
4473        if (FS.isDir(stream.node.mode)) {
4474          throw new FS.ErrnoError(31);
4475        }
4476        if (!stream.stream_ops.write) {
4477          throw new FS.ErrnoError(28);
4478        }
4479        if (stream.seekable && stream.flags & 1024) {
4480          FS.llseek(stream, 0, 2);
4481        }
4482        var seeking = typeof position != "undefined";
4483        if (!seeking) {
4484          position = stream.position;
4485        } else if (!stream.seekable) {
4486          throw new FS.ErrnoError(70);
4487        }
4488        var bytesWritten = stream.stream_ops.write(
4489          stream,
4490          buffer,
4491          offset,
4492          length,
4493          position,
4494          canOwn
4495        );
4496        if (!seeking) stream.position += bytesWritten;
4497        return bytesWritten;
4498      },
4499      allocate(stream, offset, length) {
4500        if (FS.isClosed(stream)) {
4501          throw new FS.ErrnoError(8);
4502        }
4503        if (offset < 0 || length <= 0) {
4504          throw new FS.ErrnoError(28);
4505        }
4506        if ((stream.flags & 2097155) === 0) {
4507          throw new FS.ErrnoError(8);
4508        }
4509        if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
4510          throw new FS.ErrnoError(43);
4511        }
4512        if (!stream.stream_ops.allocate) {
4513          throw new FS.ErrnoError(138);
4514        }
4515        stream.stream_ops.allocate(stream, offset, length);
4516      },
4517      mmap(stream, length, position, prot, flags) {
4518        if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {
4519          throw new FS.ErrnoError(2);
4520        }
4521        if ((stream.flags & 2097155) === 1) {
4522          throw new FS.ErrnoError(2);
4523        }
4524        if (!stream.stream_ops.mmap) {
4525          throw new FS.ErrnoError(43);
4526        }
4527        if (!length) {
4528          throw new FS.ErrnoError(28);
4529        }
4530        return stream.stream_ops.mmap(stream, length, position, prot, flags);
4531      },
4532      msync(stream, buffer, offset, length, mmapFlags) {
4533        assert(offset >= 0);
4534        if (!stream.stream_ops.msync) {
4535          return 0;
4536        }
4537        return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
4538      },
4539      ioctl(stream, cmd, arg) {
4540        if (!stream.stream_ops.ioctl) {
4541          throw new FS.ErrnoError(59);
4542        }
4543        return stream.stream_ops.ioctl(stream, cmd, arg);
4544      },
4545      readFile(path, opts = {}) {
4546        opts.flags = opts.flags || 0;
4547        opts.encoding = opts.encoding || "binary";
4548        if (opts.encoding !== "utf8" && opts.encoding !== "binary") {
4549          throw new Error(\`Invalid encoding type "\${opts.encoding}"\`);
4550        }
4551        var ret;
4552        var stream = FS.open(path, opts.flags);
4553        var stat = FS.stat(path);
4554        var length = stat.size;
4555        var buf = new Uint8Array(length);
4556        FS.read(stream, buf, 0, length, 0);
4557        if (opts.encoding === "utf8") {
4558          ret = UTF8ArrayToString(buf);
4559        } else if (opts.encoding === "binary") {
4560          ret = buf;
4561        }
4562        FS.close(stream);
4563        return ret;
4564      },
4565      writeFile(path, data, opts = {}) {
4566        opts.flags = opts.flags || 577;
4567        var stream = FS.open(path, opts.flags, opts.mode);
4568        if (typeof data == "string") {
4569          var buf = new Uint8Array(lengthBytesUTF8(data) + 1);
4570          var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
4571          FS.write(stream, buf, 0, actualNumBytes, void 0, opts.canOwn);
4572        } else if (ArrayBuffer.isView(data)) {
4573          FS.write(stream, data, 0, data.byteLength, void 0, opts.canOwn);
4574        } else {
4575          throw new Error("Unsupported data type");
4576        }
4577        FS.close(stream);
4578      },
4579      cwd: () => FS.currentPath,
4580      chdir(path) {
4581        var lookup = FS.lookupPath(path, { follow: true });
4582        if (lookup.node === null) {
4583          throw new FS.ErrnoError(44);
4584        }
4585        if (!FS.isDir(lookup.node.mode)) {
4586          throw new FS.ErrnoError(54);
4587        }
4588        var errCode = FS.nodePermissions(lookup.node, "x");
4589        if (errCode) {
4590          throw new FS.ErrnoError(errCode);
4591        }
4592        FS.currentPath = lookup.path;
4593      },
4594      createDefaultDirectories() {
4595        FS.mkdir("/tmp");
4596        FS.mkdir("/home");
4597        FS.mkdir("/home/web_user");
4598      },
4599      createDefaultDevices() {
4600        FS.mkdir("/dev");
4601        FS.registerDevice(FS.makedev(1, 3), {
4602          read: () => 0,
4603          write: (stream, buffer, offset, length, pos) => length
4604        });
4605        FS.mkdev("/dev/null", FS.makedev(1, 3));
4606        TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
4607        TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
4608        FS.mkdev("/dev/tty", FS.makedev(5, 0));
4609        FS.mkdev("/dev/tty1", FS.makedev(6, 0));
4610        var randomBuffer = new Uint8Array(1024), randomLeft = 0;
4611        var randomByte = () => {
4612          if (randomLeft === 0) {
4613            randomLeft = randomFill(randomBuffer).byteLength;
4614          }
4615          return randomBuffer[--randomLeft];
4616        };
4617        FS.createDevice("/dev", "random", randomByte);
4618        FS.createDevice("/dev", "urandom", randomByte);
4619        FS.mkdir("/dev/shm");
4620        FS.mkdir("/dev/shm/tmp");
4621      },
4622      createSpecialDirectories() {
4623        FS.mkdir("/proc");
4624        var proc_self = FS.mkdir("/proc/self");
4625        FS.mkdir("/proc/self/fd");
4626        FS.mount(
4627          {
4628            mount() {
4629              var node = FS.createNode(proc_self, "fd", 16384 | 511, 73);
4630              node.node_ops = {
4631                lookup(parent, name) {
4632                  var fd = +name;
4633                  var stream = FS.getStreamChecked(fd);
4634                  var ret = {
4635                    parent: null,
4636                    mount: { mountpoint: "fake" },
4637                    node_ops: { readlink: () => stream.path }
4638                  };
4639                  ret.parent = ret;
4640                  return ret;
4641                }
4642              };
4643              return node;
4644            }
4645          },
4646          {},
4647          "/proc/self/fd"
4648        );
4649      },
4650      createStandardStreams(input, output, error) {
4651        if (input) {
4652          FS.createDevice("/dev", "stdin", input);
4653        } else {
4654          FS.symlink("/dev/tty", "/dev/stdin");
4655        }
4656        if (output) {
4657          FS.createDevice("/dev", "stdout", null, output);
4658        } else {
4659          FS.symlink("/dev/tty", "/dev/stdout");
4660        }
4661        if (error) {
4662          FS.createDevice("/dev", "stderr", null, error);
4663        } else {
4664          FS.symlink("/dev/tty1", "/dev/stderr");
4665        }
4666        var stdin = FS.open("/dev/stdin", 0);
4667        var stdout = FS.open("/dev/stdout", 1);
4668        var stderr = FS.open("/dev/stderr", 1);
4669        assert(stdin.fd === 0, \`invalid handle for stdin (\${stdin.fd})\`);
4670        assert(stdout.fd === 1, \`invalid handle for stdout (\${stdout.fd})\`);
4671        assert(stderr.fd === 2, \`invalid handle for stderr (\${stderr.fd})\`);
4672      },
4673      staticInit() {
4674        [44].forEach((code) => {
4675          FS.genericErrors[code] = new FS.ErrnoError(code);
4676          FS.genericErrors[code].stack = "<generic error, no stack>";
4677        });
4678        FS.nameTable = new Array(4096);
4679        FS.mount(MEMFS, {}, "/");
4680        FS.createDefaultDirectories();
4681        FS.createDefaultDevices();
4682        FS.createSpecialDirectories();
4683        FS.filesystems = {
4684          MEMFS
4685        };
4686      },
4687      init(input, output, error) {
4688        assert(
4689          !FS.initialized,
4690          "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)"
4691        );
4692        FS.initialized = true;
4693        input ?? (input = Module["stdin"]);
4694        output ?? (output = Module["stdout"]);
4695        error ?? (error = Module["stderr"]);
4696        FS.createStandardStreams(input, output, error);
4697      },
4698      quit() {
4699        FS.initialized = false;
4700        _fflush(0);
4701        for (var i = 0; i < FS.streams.length; i++) {
4702          var stream = FS.streams[i];
4703          if (!stream) {
4704            continue;
4705          }
4706          FS.close(stream);
4707        }
4708      },
4709      findObject(path, dontResolveLastLink) {
4710        var ret = FS.analyzePath(path, dontResolveLastLink);
4711        if (!ret.exists) {
4712          return null;
4713        }
4714        return ret.object;
4715      },
4716      analyzePath(path, dontResolveLastLink) {
4717        try {
4718          var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
4719          path = lookup.path;
4720        } catch (e) {
4721        }
4722        var ret = {
4723          isRoot: false,
4724          exists: false,
4725          error: 0,
4726          name: null,
4727          path: null,
4728          object: null,
4729          parentExists: false,
4730          parentPath: null,
4731          parentObject: null
4732        };
4733        try {
4734          var lookup = FS.lookupPath(path, { parent: true });
4735          ret.parentExists = true;
4736          ret.parentPath = lookup.path;
4737          ret.parentObject = lookup.node;
4738          ret.name = PATH.basename(path);
4739          lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
4740          ret.exists = true;
4741          ret.path = lookup.path;
4742          ret.object = lookup.node;
4743          ret.name = lookup.node.name;
4744          ret.isRoot = lookup.path === "/";
4745        } catch (e) {
4746          ret.error = e.errno;
4747        }
4748        return ret;
4749      },
4750      createPath(parent, path, canRead, canWrite) {
4751        parent = typeof parent == "string" ? parent : FS.getPath(parent);
4752        var parts = path.split("/").reverse();
4753        while (parts.length) {
4754          var part = parts.pop();
4755          if (!part) continue;
4756          var current = PATH.join2(parent, part);
4757          try {
4758            FS.mkdir(current);
4759          } catch (e) {
4760          }
4761          parent = current;
4762        }
4763        return current;
4764      },
4765      createFile(parent, name, properties, canRead, canWrite) {
4766        var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);
4767        var mode = FS_getMode(canRead, canWrite);
4768        return FS.create(path, mode);
4769      },
4770      createDataFile(parent, name, data, canRead, canWrite, canOwn) {
4771        var path = name;
4772        if (parent) {
4773          parent = typeof parent == "string" ? parent : FS.getPath(parent);
4774          path = name ? PATH.join2(parent, name) : parent;
4775        }
4776        var mode = FS_getMode(canRead, canWrite);
4777        var node = FS.create(path, mode);
4778        if (data) {
4779          if (typeof data == "string") {
4780            var arr = new Array(data.length);
4781            for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
4782            data = arr;
4783          }
4784          FS.chmod(node, mode | 146);
4785          var stream = FS.open(node, 577);
4786          FS.write(stream, data, 0, data.length, 0, canOwn);
4787          FS.close(stream);
4788          FS.chmod(node, mode);
4789        }
4790      },
4791      createDevice(parent, name, input, output) {
4792        var _a;
4793        var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);
4794        var mode = FS_getMode(!!input, !!output);
4795        (_a = FS.createDevice).major ?? (_a.major = 64);
4796        var dev = FS.makedev(FS.createDevice.major++, 0);
4797        FS.registerDevice(dev, {
4798          open(stream) {
4799            stream.seekable = false;
4800          },
4801          close(stream) {
4802            var _a2;
4803            if ((_a2 = output == null ? void 0 : output.buffer) == null ? void 0 : _a2.length) {
4804              output(10);
4805            }
4806          },
4807          read(stream, buffer, offset, length, pos) {
4808            var bytesRead = 0;
4809            for (var i = 0; i < length; i++) {
4810              var result;
4811              try {
4812                result = input();
4813              } catch (e) {
4814                throw new FS.ErrnoError(29);
4815              }
4816              if (result === void 0 && bytesRead === 0) {
4817                throw new FS.ErrnoError(6);
4818              }
4819              if (result === null || result === void 0) break;
4820              bytesRead++;
4821              buffer[offset + i] = result;
4822            }
4823            if (bytesRead) {
4824              stream.node.timestamp = Date.now();
4825            }
4826            return bytesRead;
4827          },
4828          write(stream, buffer, offset, length, pos) {
4829            for (var i = 0; i < length; i++) {
4830              try {
4831                output(buffer[offset + i]);
4832              } catch (e) {
4833                throw new FS.ErrnoError(29);
4834              }
4835            }
4836            if (length) {
4837              stream.node.timestamp = Date.now();
4838            }
4839            return i;
4840          }
4841        });
4842        return FS.mkdev(path, mode, dev);
4843      },
4844      forceLoadFile(obj) {
4845        if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
4846        if (typeof XMLHttpRequest != "undefined") {
4847          throw new Error(
4848            "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."
4849          );
4850        } else {
4851          try {
4852            obj.contents = readBinary(obj.url);
4853            obj.usedBytes = obj.contents.length;
4854          } catch (e) {
4855            throw new FS.ErrnoError(29);
4856          }
4857        }
4858      },
4859      createLazyFile(parent, name, url, canRead, canWrite) {
4860        class LazyUint8Array {
4861          constructor() {
4862            this.lengthKnown = false;
4863            this.chunks = [];
4864          }
4865          get(idx) {
4866            if (idx > this.length - 1 || idx < 0) {
4867              return void 0;
4868            }
4869            var chunkOffset = idx % this.chunkSize;
4870            var chunkNum = idx / this.chunkSize | 0;
4871            return this.getter(chunkNum)[chunkOffset];
4872          }
4873          setDataGetter(getter) {
4874            this.getter = getter;
4875          }
4876          cacheLength() {
4877            var xhr = new XMLHttpRequest();
4878            xhr.open("HEAD", url, false);
4879            xhr.send(null);
4880            if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304))
4881              throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
4882            var datalength = Number(xhr.getResponseHeader("Content-length"));
4883            var header;
4884            var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
4885            var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
4886            var chunkSize = 1024 * 1024;
4887            if (!hasByteServing) chunkSize = datalength;
4888            var doXHR = (from, to) => {
4889              if (from > to)
4890                throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
4891              if (to > datalength - 1)
4892                throw new Error("only " + datalength + " bytes available! programmer error!");
4893              var xhr2 = new XMLHttpRequest();
4894              xhr2.open("GET", url, false);
4895              if (datalength !== chunkSize)
4896                xhr2.setRequestHeader("Range", "bytes=" + from + "-" + to);
4897              xhr2.responseType = "arraybuffer";
4898              if (xhr2.overrideMimeType) {
4899                xhr2.overrideMimeType("text/plain; charset=x-user-defined");
4900              }
4901              xhr2.send(null);
4902              if (!(xhr2.status >= 200 && xhr2.status < 300 || xhr2.status === 304))
4903                throw new Error("Couldn't load " + url + ". Status: " + xhr2.status);
4904              if (xhr2.response !== void 0) {
4905                return new Uint8Array(
4906                  /** @type{Array<number>} */
4907                  xhr2.response || []
4908                );
4909              }
4910              return intArrayFromString(xhr2.responseText || "");
4911            };
4912            var lazyArray2 = this;
4913            lazyArray2.setDataGetter((chunkNum) => {
4914              var start = chunkNum * chunkSize;
4915              var end = (chunkNum + 1) * chunkSize - 1;
4916              end = Math.min(end, datalength - 1);
4917              if (typeof lazyArray2.chunks[chunkNum] == "undefined") {
4918                lazyArray2.chunks[chunkNum] = doXHR(start, end);
4919              }
4920              if (typeof lazyArray2.chunks[chunkNum] == "undefined")
4921                throw new Error("doXHR failed!");
4922              return lazyArray2.chunks[chunkNum];
4923            });
4924            if (usesGzip || !datalength) {
4925              chunkSize = datalength = 1;
4926              datalength = this.getter(0).length;
4927              chunkSize = datalength;
4928              out("LazyFiles on gzip forces download of the whole file when length is accessed");
4929            }
4930            this._length = datalength;
4931            this._chunkSize = chunkSize;
4932            this.lengthKnown = true;
4933          }
4934          get length() {
4935            if (!this.lengthKnown) {
4936              this.cacheLength();
4937            }
4938            return this._length;
4939          }
4940          get chunkSize() {
4941            if (!this.lengthKnown) {
4942              this.cacheLength();
4943            }
4944            return this._chunkSize;
4945          }
4946        }
4947        if (typeof XMLHttpRequest != "undefined") {
4948          if (!ENVIRONMENT_IS_WORKER)
4949            throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";
4950          var lazyArray = new LazyUint8Array();
4951          var properties = { isDevice: false, contents: lazyArray };
4952        } else {
4953          var properties = { isDevice: false, url };
4954        }
4955        var node = FS.createFile(parent, name, properties, canRead, canWrite);
4956        if (properties.contents) {
4957          node.contents = properties.contents;
4958        } else if (properties.url) {
4959          node.contents = null;
4960          node.url = properties.url;
4961        }
4962        Object.defineProperties(node, {
4963          usedBytes: {
4964            get: function() {
4965              return this.contents.length;
4966            }
4967          }
4968        });
4969        var stream_ops = {};
4970        var keys = Object.keys(node.stream_ops);
4971        keys.forEach((key) => {
4972          var fn = node.stream_ops[key];
4973          stream_ops[key] = (...args) => {
4974            FS.forceLoadFile(node);
4975            return fn(...args);
4976          };
4977        });
4978        function writeChunks(stream, buffer, offset, length, position) {
4979          var contents = stream.node.contents;
4980          if (position >= contents.length) return 0;
4981          var size = Math.min(contents.length - position, length);
4982          assert(size >= 0);
4983          if (contents.slice) {
4984            for (var i = 0; i < size; i++) {
4985              buffer[offset + i] = contents[position + i];
4986            }
4987          } else {
4988            for (var i = 0; i < size; i++) {
4989              buffer[offset + i] = contents.get(position + i);
4990            }
4991          }
4992          return size;
4993        }
4994        stream_ops.read = (stream, buffer, offset, length, position) => {
4995          FS.forceLoadFile(node);
4996          return writeChunks(stream, buffer, offset, length, position);
4997        };
4998        stream_ops.mmap = (stream, length, position, prot, flags) => {
4999          FS.forceLoadFile(node);
5000          var ptr = mmapAlloc(length);
5001          if (!ptr) {
5002            throw new FS.ErrnoError(48);
5003          }
5004          writeChunks(stream, HEAP8, ptr, length, position);
5005          return { ptr, allocated: true };
5006        };
5007        node.stream_ops = stream_ops;
5008        return node;
5009      },
5010      absolutePath() {
5011        abort("FS.absolutePath has been removed; use PATH_FS.resolve instead");
5012      },
5013      createFolder() {
5014        abort("FS.createFolder has been removed; use FS.mkdir instead");
5015      },
5016      createLink() {
5017        abort("FS.createLink has been removed; use FS.symlink instead");
5018      },
5019      joinPath() {
5020        abort("FS.joinPath has been removed; use PATH.join instead");
5021      },
5022      mmapAlloc() {
5023        abort("FS.mmapAlloc has been replaced by the top level function mmapAlloc");
5024      },
5025      standardizePath() {
5026        abort("FS.standardizePath has been removed; use PATH.normalize instead");
5027      }
5028    };
5029    var SYSCALLS = {
5030      DEFAULT_POLLMASK: 5,
5031      calculateAt(dirfd, path, allowEmpty) {
5032        if (PATH.isAbs(path)) {
5033          return path;
5034        }
5035        var dir;
5036        if (dirfd === -100) {
5037          dir = FS.cwd();
5038        } else {
5039          var dirstream = SYSCALLS.getStreamFromFD(dirfd);
5040          dir = dirstream.path;
5041        }
5042        if (path.length == 0) {
5043          if (!allowEmpty) {
5044            throw new FS.ErrnoError(44);
5045          }
5046          return dir;
5047        }
5048        return PATH.join2(dir, path);
5049      },
5050      doStat(func, path, buf) {
5051        var stat = func(path);
5052        HEAP32[buf >> 2] = stat.dev;
5053        HEAP32[buf + 4 >> 2] = stat.mode;
5054        HEAPU32[buf + 8 >> 2] = stat.nlink;
5055        HEAP32[buf + 12 >> 2] = stat.uid;
5056        HEAP32[buf + 16 >> 2] = stat.gid;
5057        HEAP32[buf + 20 >> 2] = stat.rdev;
5058        tempI64 = [
5059          stat.size >>> 0,
5060          (tempDouble = stat.size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5061        ], HEAP32[buf + 24 >> 2] = tempI64[0], HEAP32[buf + 28 >> 2] = tempI64[1];
5062        HEAP32[buf + 32 >> 2] = 4096;
5063        HEAP32[buf + 36 >> 2] = stat.blocks;
5064        var atime = stat.atime.getTime();
5065        var mtime = stat.mtime.getTime();
5066        var ctime = stat.ctime.getTime();
5067        tempI64 = [
5068          Math.floor(atime / 1e3) >>> 0,
5069          (tempDouble = Math.floor(atime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5070        ], HEAP32[buf + 40 >> 2] = tempI64[0], HEAP32[buf + 44 >> 2] = tempI64[1];
5071        HEAPU32[buf + 48 >> 2] = atime % 1e3 * 1e3 * 1e3;
5072        tempI64 = [
5073          Math.floor(mtime / 1e3) >>> 0,
5074          (tempDouble = Math.floor(mtime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5075        ], HEAP32[buf + 56 >> 2] = tempI64[0], HEAP32[buf + 60 >> 2] = tempI64[1];
5076        HEAPU32[buf + 64 >> 2] = mtime % 1e3 * 1e3 * 1e3;
5077        tempI64 = [
5078          Math.floor(ctime / 1e3) >>> 0,
5079          (tempDouble = Math.floor(ctime / 1e3), +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5080        ], HEAP32[buf + 72 >> 2] = tempI64[0], HEAP32[buf + 76 >> 2] = tempI64[1];
5081        HEAPU32[buf + 80 >> 2] = ctime % 1e3 * 1e3 * 1e3;
5082        tempI64 = [
5083          stat.ino >>> 0,
5084          (tempDouble = stat.ino, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5085        ], HEAP32[buf + 88 >> 2] = tempI64[0], HEAP32[buf + 92 >> 2] = tempI64[1];
5086        return 0;
5087      },
5088      doMsync(addr, stream, len, flags, offset) {
5089        if (!FS.isFile(stream.node.mode)) {
5090          throw new FS.ErrnoError(43);
5091        }
5092        if (flags & 2) {
5093          return 0;
5094        }
5095        var buffer = HEAPU8.slice(addr, addr + len);
5096        FS.msync(stream, buffer, offset, len, flags);
5097      },
5098      getStreamFromFD(fd) {
5099        var stream = FS.getStreamChecked(fd);
5100        return stream;
5101      },
5102      varargs: void 0,
5103      getStr(ptr) {
5104        var ret = UTF8ToString(ptr);
5105        return ret;
5106      }
5107    };
5108    function ___syscall_fcntl64(fd, cmd, varargs) {
5109      SYSCALLS.varargs = varargs;
5110      try {
5111        var stream = SYSCALLS.getStreamFromFD(fd);
5112        switch (cmd) {
5113          case 0: {
5114            var arg = syscallGetVarargI();
5115            if (arg < 0) {
5116              return -28;
5117            }
5118            while (FS.streams[arg]) {
5119              arg++;
5120            }
5121            var newStream;
5122            newStream = FS.dupStream(stream, arg);
5123            return newStream.fd;
5124          }
5125          case 1:
5126          case 2:
5127            return 0;
5128          // FD_CLOEXEC makes no sense for a single process.
5129          case 3:
5130            return stream.flags;
5131          case 4: {
5132            var arg = syscallGetVarargI();
5133            stream.flags |= arg;
5134            return 0;
5135          }
5136          case 12: {
5137            var arg = syscallGetVarargP();
5138            var offset = 0;
5139            HEAP16[arg + offset >> 1] = 2;
5140            return 0;
5141          }
5142          case 13:
5143          case 14:
5144            return 0;
5145        }
5146        return -28;
5147      } catch (e) {
5148        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5149        return -e.errno;
5150      }
5151    }
5152    function ___syscall_fstat64(fd, buf) {
5153      try {
5154        var stream = SYSCALLS.getStreamFromFD(fd);
5155        return SYSCALLS.doStat(FS.stat, stream.path, buf);
5156      } catch (e) {
5157        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5158        return -e.errno;
5159      }
5160    }
5161    var convertI32PairToI53Checked = (lo, hi) => {
5162      assert(lo == lo >>> 0 || lo == (lo | 0));
5163      assert(hi === (hi | 0));
5164      return hi + 2097152 >>> 0 < 4194305 - !!lo ? (lo >>> 0) + hi * 4294967296 : NaN;
5165    };
5166    function ___syscall_ftruncate64(fd, length_low, length_high) {
5167      var length = convertI32PairToI53Checked(length_low, length_high);
5168      try {
5169        if (isNaN(length)) return 61;
5170        FS.ftruncate(fd, length);
5171        return 0;
5172      } catch (e) {
5173        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5174        return -e.errno;
5175      }
5176    }
5177    var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {
5178      assert(
5179        typeof maxBytesToWrite == "number",
5180        "stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"
5181      );
5182      return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
5183    };
5184    function ___syscall_getdents64(fd, dirp, count) {
5185      try {
5186        var stream = SYSCALLS.getStreamFromFD(fd);
5187        stream.getdents || (stream.getdents = FS.readdir(stream.path));
5188        var struct_size = 280;
5189        var pos = 0;
5190        var off = FS.llseek(stream, 0, 1);
5191        var idx = Math.floor(off / struct_size);
5192        while (idx < stream.getdents.length && pos + struct_size <= count) {
5193          var id;
5194          var type;
5195          var name = stream.getdents[idx];
5196          if (name === ".") {
5197            id = stream.node.id;
5198            type = 4;
5199          } else if (name === "..") {
5200            var lookup = FS.lookupPath(stream.path, { parent: true });
5201            id = lookup.node.id;
5202            type = 4;
5203          } else {
5204            var child = FS.lookupNode(stream.node, name);
5205            id = child.id;
5206            type = FS.isChrdev(child.mode) ? 2 : FS.isDir(child.mode) ? 4 : FS.isLink(child.mode) ? 10 : 8;
5207          }
5208          assert(id);
5209          tempI64 = [
5210            id >>> 0,
5211            (tempDouble = id, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5212          ], HEAP32[dirp + pos >> 2] = tempI64[0], HEAP32[dirp + pos + 4 >> 2] = tempI64[1];
5213          tempI64 = [
5214            (idx + 1) * struct_size >>> 0,
5215            (tempDouble = (idx + 1) * struct_size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5216          ], HEAP32[dirp + pos + 8 >> 2] = tempI64[0], HEAP32[dirp + pos + 12 >> 2] = tempI64[1];
5217          HEAP16[dirp + pos + 16 >> 1] = 280;
5218          HEAP8[dirp + pos + 18] = type;
5219          stringToUTF8(name, dirp + pos + 19, 256);
5220          pos += struct_size;
5221          idx += 1;
5222        }
5223        FS.llseek(stream, idx * struct_size, 0);
5224        return pos;
5225      } catch (e) {
5226        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5227        return -e.errno;
5228      }
5229    }
5230    function ___syscall_ioctl(fd, op, varargs) {
5231      SYSCALLS.varargs = varargs;
5232      try {
5233        var stream = SYSCALLS.getStreamFromFD(fd);
5234        switch (op) {
5235          case 21509: {
5236            if (!stream.tty) return -59;
5237            return 0;
5238          }
5239          case 21505: {
5240            if (!stream.tty) return -59;
5241            if (stream.tty.ops.ioctl_tcgets) {
5242              var termios = stream.tty.ops.ioctl_tcgets(stream);
5243              var argp = syscallGetVarargP();
5244              HEAP32[argp >> 2] = termios.c_iflag || 0;
5245              HEAP32[argp + 4 >> 2] = termios.c_oflag || 0;
5246              HEAP32[argp + 8 >> 2] = termios.c_cflag || 0;
5247              HEAP32[argp + 12 >> 2] = termios.c_lflag || 0;
5248              for (var i = 0; i < 32; i++) {
5249                HEAP8[argp + i + 17] = termios.c_cc[i] || 0;
5250              }
5251              return 0;
5252            }
5253            return 0;
5254          }
5255          case 21510:
5256          case 21511:
5257          case 21512: {
5258            if (!stream.tty) return -59;
5259            return 0;
5260          }
5261          case 21506:
5262          case 21507:
5263          case 21508: {
5264            if (!stream.tty) return -59;
5265            if (stream.tty.ops.ioctl_tcsets) {
5266              var argp = syscallGetVarargP();
5267              var c_iflag = HEAP32[argp >> 2];
5268              var c_oflag = HEAP32[argp + 4 >> 2];
5269              var c_cflag = HEAP32[argp + 8 >> 2];
5270              var c_lflag = HEAP32[argp + 12 >> 2];
5271              var c_cc = [];
5272              for (var i = 0; i < 32; i++) {
5273                c_cc.push(HEAP8[argp + i + 17]);
5274              }
5275              return stream.tty.ops.ioctl_tcsets(stream.tty, op, {
5276                c_iflag,
5277                c_oflag,
5278                c_cflag,
5279                c_lflag,
5280                c_cc
5281              });
5282            }
5283            return 0;
5284          }
5285          case 21519: {
5286            if (!stream.tty) return -59;
5287            var argp = syscallGetVarargP();
5288            HEAP32[argp >> 2] = 0;
5289            return 0;
5290          }
5291          case 21520: {
5292            if (!stream.tty) return -59;
5293            return -28;
5294          }
5295          case 21531: {
5296            var argp = syscallGetVarargP();
5297            return FS.ioctl(stream, op, argp);
5298          }
5299          case 21523: {
5300            if (!stream.tty) return -59;
5301            if (stream.tty.ops.ioctl_tiocgwinsz) {
5302              var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);
5303              var argp = syscallGetVarargP();
5304              HEAP16[argp >> 1] = winsize[0];
5305              HEAP16[argp + 2 >> 1] = winsize[1];
5306            }
5307            return 0;
5308          }
5309          case 21524: {
5310            if (!stream.tty) return -59;
5311            return 0;
5312          }
5313          case 21515: {
5314            if (!stream.tty) return -59;
5315            return 0;
5316          }
5317          default:
5318            return -28;
5319        }
5320      } catch (e) {
5321        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5322        return -e.errno;
5323      }
5324    }
5325    function ___syscall_lstat64(path, buf) {
5326      try {
5327        path = SYSCALLS.getStr(path);
5328        return SYSCALLS.doStat(FS.lstat, path, buf);
5329      } catch (e) {
5330        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5331        return -e.errno;
5332      }
5333    }
5334    function ___syscall_newfstatat(dirfd, path, buf, flags) {
5335      try {
5336        path = SYSCALLS.getStr(path);
5337        var nofollow = flags & 256;
5338        var allowEmpty = flags & 4096;
5339        flags = flags & ~6400;
5340        assert(!flags, \`unknown flags in __syscall_newfstatat: \${flags}\`);
5341        path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);
5342        return SYSCALLS.doStat(nofollow ? FS.lstat : FS.stat, path, buf);
5343      } catch (e) {
5344        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5345        return -e.errno;
5346      }
5347    }
5348    function ___syscall_openat(dirfd, path, flags, varargs) {
5349      SYSCALLS.varargs = varargs;
5350      try {
5351        path = SYSCALLS.getStr(path);
5352        path = SYSCALLS.calculateAt(dirfd, path);
5353        var mode = varargs ? syscallGetVarargI() : 0;
5354        return FS.open(path, flags, mode).fd;
5355      } catch (e) {
5356        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5357        return -e.errno;
5358      }
5359    }
5360    function ___syscall_rmdir(path) {
5361      try {
5362        path = SYSCALLS.getStr(path);
5363        FS.rmdir(path);
5364        return 0;
5365      } catch (e) {
5366        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5367        return -e.errno;
5368      }
5369    }
5370    function ___syscall_stat64(path, buf) {
5371      try {
5372        path = SYSCALLS.getStr(path);
5373        return SYSCALLS.doStat(FS.stat, path, buf);
5374      } catch (e) {
5375        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5376        return -e.errno;
5377      }
5378    }
5379    function ___syscall_unlinkat(dirfd, path, flags) {
5380      try {
5381        path = SYSCALLS.getStr(path);
5382        path = SYSCALLS.calculateAt(dirfd, path);
5383        if (flags === 0) {
5384          FS.unlink(path);
5385        } else if (flags === 512) {
5386          FS.rmdir(path);
5387        } else {
5388          abort("Invalid flags passed to unlinkat");
5389        }
5390        return 0;
5391      } catch (e) {
5392        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5393        return -e.errno;
5394      }
5395    }
5396    var __abort_js = () => {
5397      abort("native code called abort()");
5398    };
5399    var __emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num);
5400    var __emscripten_throw_longjmp = () => {
5401      throw Infinity;
5402    };
5403    function __gmtime_js(time_low, time_high, tmPtr) {
5404      var time = convertI32PairToI53Checked(time_low, time_high);
5405      var date = new Date(time * 1e3);
5406      HEAP32[tmPtr >> 2] = date.getUTCSeconds();
5407      HEAP32[tmPtr + 4 >> 2] = date.getUTCMinutes();
5408      HEAP32[tmPtr + 8 >> 2] = date.getUTCHours();
5409      HEAP32[tmPtr + 12 >> 2] = date.getUTCDate();
5410      HEAP32[tmPtr + 16 >> 2] = date.getUTCMonth();
5411      HEAP32[tmPtr + 20 >> 2] = date.getUTCFullYear() - 1900;
5412      HEAP32[tmPtr + 24 >> 2] = date.getUTCDay();
5413      var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
5414      var yday = (date.getTime() - start) / (1e3 * 60 * 60 * 24) | 0;
5415      HEAP32[tmPtr + 28 >> 2] = yday;
5416    }
5417    var isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
5418    var MONTH_DAYS_LEAP_CUMULATIVE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
5419    var MONTH_DAYS_REGULAR_CUMULATIVE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
5420    var ydayFromDate = (date) => {
5421      var leap = isLeapYear(date.getFullYear());
5422      var monthDaysCumulative = leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE;
5423      var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;
5424      return yday;
5425    };
5426    function __localtime_js(time_low, time_high, tmPtr) {
5427      var time = convertI32PairToI53Checked(time_low, time_high);
5428      var date = new Date(time * 1e3);
5429      HEAP32[tmPtr >> 2] = date.getSeconds();
5430      HEAP32[tmPtr + 4 >> 2] = date.getMinutes();
5431      HEAP32[tmPtr + 8 >> 2] = date.getHours();
5432      HEAP32[tmPtr + 12 >> 2] = date.getDate();
5433      HEAP32[tmPtr + 16 >> 2] = date.getMonth();
5434      HEAP32[tmPtr + 20 >> 2] = date.getFullYear() - 1900;
5435      HEAP32[tmPtr + 24 >> 2] = date.getDay();
5436      var yday = ydayFromDate(date) | 0;
5437      HEAP32[tmPtr + 28 >> 2] = yday;
5438      HEAP32[tmPtr + 36 >> 2] = -(date.getTimezoneOffset() * 60);
5439      var start = new Date(date.getFullYear(), 0, 1);
5440      var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
5441      var winterOffset = start.getTimezoneOffset();
5442      var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;
5443      HEAP32[tmPtr + 32 >> 2] = dst;
5444    }
5445    var __tzset_js = (timezone, daylight, std_name, dst_name) => {
5446      var currentYear = (/* @__PURE__ */ new Date()).getFullYear();
5447      var winter = new Date(currentYear, 0, 1);
5448      var summer = new Date(currentYear, 6, 1);
5449      var winterOffset = winter.getTimezoneOffset();
5450      var summerOffset = summer.getTimezoneOffset();
5451      var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
5452      HEAPU32[timezone >> 2] = stdTimezoneOffset * 60;
5453      HEAP32[daylight >> 2] = Number(winterOffset != summerOffset);
5454      var extractZone = (timezoneOffset) => {
5455        var sign = timezoneOffset >= 0 ? "-" : "+";
5456        var absOffset = Math.abs(timezoneOffset);
5457        var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");
5458        var minutes = String(absOffset % 60).padStart(2, "0");
5459        return \`UTC\${sign}\${hours}\${minutes}\`;
5460      };
5461      var winterName = extractZone(winterOffset);
5462      var summerName = extractZone(summerOffset);
5463      assert(winterName);
5464      assert(summerName);
5465      assert(
5466        lengthBytesUTF8(winterName) <= 16,
5467        \`timezone name truncated to fit in TZNAME_MAX (\${winterName})\`
5468      );
5469      assert(
5470        lengthBytesUTF8(summerName) <= 16,
5471        \`timezone name truncated to fit in TZNAME_MAX (\${summerName})\`
5472      );
5473      if (summerOffset < winterOffset) {
5474        stringToUTF8(winterName, std_name, 17);
5475        stringToUTF8(summerName, dst_name, 17);
5476      } else {
5477        stringToUTF8(winterName, dst_name, 17);
5478        stringToUTF8(summerName, std_name, 17);
5479      }
5480    };
5481    var _emscripten_date_now = () => Date.now();
5482    var getHeapMax = () => (
5483      // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
5484      // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
5485      // for any code that deals with heap sizes, which would require special
5486      // casing all heap size related code to treat 0 specially.
5487      2147483648
5488    );
5489    var growMemory = (size) => {
5490      var b = wasmMemory.buffer;
5491      var pages = (size - b.byteLength + 65535) / 65536 | 0;
5492      try {
5493        wasmMemory.grow(pages);
5494        updateMemoryViews();
5495        return 1;
5496      } catch (e) {
5497        err(
5498          \`growMemory: Attempted to grow heap from \${b.byteLength} bytes to \${size} bytes, but got error: \${e}\`
5499        );
5500      }
5501    };
5502    var _emscripten_resize_heap = (requestedSize) => {
5503      var oldSize = HEAPU8.length;
5504      requestedSize >>>= 0;
5505      assert(requestedSize > oldSize);
5506      var maxHeapSize = getHeapMax();
5507      if (requestedSize > maxHeapSize) {
5508        err(
5509          \`Cannot enlarge memory, requested \${requestedSize} bytes, but the limit is \${maxHeapSize} bytes!\`
5510        );
5511        return false;
5512      }
5513      for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
5514        var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
5515        overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
5516        var newSize = Math.min(
5517          maxHeapSize,
5518          alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)
5519        );
5520        var replacement = growMemory(newSize);
5521        if (replacement) {
5522          return true;
5523        }
5524      }
5525      err(\`Failed to grow the heap from \${oldSize} bytes to \${newSize} bytes, not enough memory!\`);
5526      return false;
5527    };
5528    var ENV = {};
5529    var getExecutableName = () => {
5530      return thisProgram || "./this.program";
5531    };
5532    var getEnvStrings = () => {
5533      if (!getEnvStrings.strings) {
5534        var lang = (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8";
5535        var env = {
5536          USER: "web_user",
5537          LOGNAME: "web_user",
5538          PATH: "/",
5539          PWD: "/",
5540          HOME: "/home/web_user",
5541          LANG: lang,
5542          _: getExecutableName()
5543        };
5544        for (var x in ENV) {
5545          if (ENV[x] === void 0) delete env[x];
5546          else env[x] = ENV[x];
5547        }
5548        var strings = [];
5549        for (var x in env) {
5550          strings.push(\`\${x}=\${env[x]}\`);
5551        }
5552        getEnvStrings.strings = strings;
5553      }
5554      return getEnvStrings.strings;
5555    };
5556    var stringToAscii = (str, buffer) => {
5557      for (var i = 0; i < str.length; ++i) {
5558        assert(str.charCodeAt(i) === (str.charCodeAt(i) & 255));
5559        HEAP8[buffer++] = str.charCodeAt(i);
5560      }
5561      HEAP8[buffer] = 0;
5562    };
5563    var _environ_get = (__environ, environ_buf) => {
5564      var bufSize = 0;
5565      getEnvStrings().forEach((string, i) => {
5566        var ptr = environ_buf + bufSize;
5567        HEAPU32[__environ + i * 4 >> 2] = ptr;
5568        stringToAscii(string, ptr);
5569        bufSize += string.length + 1;
5570      });
5571      return 0;
5572    };
5573    var _environ_sizes_get = (penviron_count, penviron_buf_size) => {
5574      var strings = getEnvStrings();
5575      HEAPU32[penviron_count >> 2] = strings.length;
5576      var bufSize = 0;
5577      strings.forEach((string) => bufSize += string.length + 1);
5578      HEAPU32[penviron_buf_size >> 2] = bufSize;
5579      return 0;
5580    };
5581    function _fd_close(fd) {
5582      try {
5583        var stream = SYSCALLS.getStreamFromFD(fd);
5584        FS.close(stream);
5585        return 0;
5586      } catch (e) {
5587        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5588        return e.errno;
5589      }
5590    }
5591    var doReadv = (stream, iov, iovcnt, offset) => {
5592      var ret = 0;
5593      for (var i = 0; i < iovcnt; i++) {
5594        var ptr = HEAPU32[iov >> 2];
5595        var len = HEAPU32[iov + 4 >> 2];
5596        iov += 8;
5597        var curr = FS.read(stream, HEAP8, ptr, len, offset);
5598        if (curr < 0) return -1;
5599        ret += curr;
5600        if (curr < len) break;
5601      }
5602      return ret;
5603    };
5604    function _fd_read(fd, iov, iovcnt, pnum) {
5605      try {
5606        var stream = SYSCALLS.getStreamFromFD(fd);
5607        var num = doReadv(stream, iov, iovcnt);
5608        HEAPU32[pnum >> 2] = num;
5609        return 0;
5610      } catch (e) {
5611        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5612        return e.errno;
5613      }
5614    }
5615    function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
5616      var offset = convertI32PairToI53Checked(offset_low, offset_high);
5617      try {
5618        if (isNaN(offset)) return 61;
5619        var stream = SYSCALLS.getStreamFromFD(fd);
5620        FS.llseek(stream, offset, whence);
5621        tempI64 = [
5622          stream.position >>> 0,
5623          (tempDouble = stream.position, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? +Math.floor(tempDouble / 4294967296) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)
5624        ], HEAP32[newOffset >> 2] = tempI64[0], HEAP32[newOffset + 4 >> 2] = tempI64[1];
5625        if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;
5626        return 0;
5627      } catch (e) {
5628        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5629        return e.errno;
5630      }
5631    }
5632    function _fd_sync(fd) {
5633      var _a;
5634      try {
5635        var stream = SYSCALLS.getStreamFromFD(fd);
5636        if ((_a = stream.stream_ops) == null ? void 0 : _a.fsync) {
5637          return stream.stream_ops.fsync(stream);
5638        }
5639        return 0;
5640      } catch (e) {
5641        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5642        return e.errno;
5643      }
5644    }
5645    var doWritev = (stream, iov, iovcnt, offset) => {
5646      var ret = 0;
5647      for (var i = 0; i < iovcnt; i++) {
5648        var ptr = HEAPU32[iov >> 2];
5649        var len = HEAPU32[iov + 4 >> 2];
5650        iov += 8;
5651        var curr = FS.write(stream, HEAP8, ptr, len, offset);
5652        if (curr < 0) return -1;
5653        ret += curr;
5654        if (curr < len) {
5655          break;
5656        }
5657      }
5658      return ret;
5659    };
5660    function _fd_write(fd, iov, iovcnt, pnum) {
5661      try {
5662        var stream = SYSCALLS.getStreamFromFD(fd);
5663        var num = doWritev(stream, iov, iovcnt);
5664        HEAPU32[pnum >> 2] = num;
5665        return 0;
5666      } catch (e) {
5667        if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;
5668        return e.errno;
5669      }
5670    }
5671    var wasmTableMirror = [];
5672    var wasmTable;
5673    var getWasmTableEntry = (funcPtr) => {
5674      var func = wasmTableMirror[funcPtr];
5675      if (!func) {
5676        if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;
5677        wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);
5678      }
5679      assert(
5680        wasmTable.get(funcPtr) == func,
5681        "JavaScript-side Wasm function table mirror is out of date!"
5682      );
5683      return func;
5684    };
5685    var UTF16Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf-16le") : void 0;
5686    var UTF16ToString = (ptr, maxBytesToRead) => {
5687      assert(ptr % 2 == 0, "Pointer passed to UTF16ToString must be aligned to two bytes!");
5688      var endPtr = ptr;
5689      var idx = endPtr >> 1;
5690      var maxIdx = idx + maxBytesToRead / 2;
5691      while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx;
5692      endPtr = idx << 1;
5693      if (endPtr - ptr > 32 && UTF16Decoder)
5694        return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
5695      var str = "";
5696      for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
5697        var codeUnit = HEAP16[ptr + i * 2 >> 1];
5698        if (codeUnit == 0) break;
5699        str += String.fromCharCode(codeUnit);
5700      }
5701      return str;
5702    };
5703    var uleb128Encode = (n, target) => {
5704      assert(n < 16384);
5705      if (n < 128) {
5706        target.push(n);
5707      } else {
5708        target.push(n % 128 | 128, n >> 7);
5709      }
5710    };
5711    var sigToWasmTypes = (sig) => {
5712      assert(
5713        !sig.includes("j"),
5714        "i64 not permitted in function signatures when WASM_BIGINT is disabled"
5715      );
5716      var typeNames = {
5717        i: "i32",
5718        j: "i64",
5719        f: "f32",
5720        d: "f64",
5721        e: "externref",
5722        p: "i32"
5723      };
5724      var type = {
5725        parameters: [],
5726        results: sig[0] == "v" ? [] : [typeNames[sig[0]]]
5727      };
5728      for (var i = 1; i < sig.length; ++i) {
5729        assert(sig[i] in typeNames, "invalid signature char: " + sig[i]);
5730        type.parameters.push(typeNames[sig[i]]);
5731      }
5732      return type;
5733    };
5734    var generateFuncType = (sig, target) => {
5735      var sigRet = sig.slice(0, 1);
5736      var sigParam = sig.slice(1);
5737      var typeCodes = {
5738        i: 127,
5739        // i32
5740        p: 127,
5741        // i32
5742        j: 126,
5743        // i64
5744        f: 125,
5745        // f32
5746        d: 124,
5747        // f64
5748        e: 111
5749        // externref
5750      };
5751      target.push(
5752        96
5753        /* form: func */
5754      );
5755      uleb128Encode(sigParam.length, target);
5756      for (var i = 0; i < sigParam.length; ++i) {
5757        assert(sigParam[i] in typeCodes, "invalid signature char: " + sigParam[i]);
5758        target.push(typeCodes[sigParam[i]]);
5759      }
5760      if (sigRet == "v") {
5761        target.push(0);
5762      } else {
5763        target.push(1, typeCodes[sigRet]);
5764      }
5765    };
5766    var convertJsFunctionToWasm = (func, sig) => {
5767      assert(
5768        !sig.includes("j"),
5769        "i64 not permitted in function signatures when WASM_BIGINT is disabled"
5770      );
5771      if (typeof WebAssembly.Function == "function") {
5772        return new WebAssembly.Function(sigToWasmTypes(sig), func);
5773      }
5774      var typeSectionBody = [
5775        1
5776        // count: 1
5777      ];
5778      generateFuncType(sig, typeSectionBody);
5779      var bytes = [
5780        0,
5781        97,
5782        115,
5783        109,
5784        // magic ("\\0asm")
5785        1,
5786        0,
5787        0,
5788        0,
5789        // version: 1
5790        1
5791        // Type section code
5792      ];
5793      uleb128Encode(typeSectionBody.length, bytes);
5794      bytes.push(...typeSectionBody);
5795      bytes.push(
5796        2,
5797        7,
5798        // import section
5799        // (import "e" "f" (func 0 (type 0)))
5800        1,
5801        1,
5802        101,
5803        1,
5804        102,
5805        0,
5806        0,
5807        7,
5808        5,
5809        // export section
5810        // (export "f" (func 0 (type 0)))
5811        1,
5812        1,
5813        102,
5814        0,
5815        0
5816      );
5817      var module = new WebAssembly.Module(new Uint8Array(bytes));
5818      var instance = new WebAssembly.Instance(module, { e: { f: func } });
5819      var wrappedFunc = instance.exports["f"];
5820      return wrappedFunc;
5821    };
5822    var updateTableMap = (offset, count) => {
5823      if (functionsInTableMap) {
5824        for (var i = offset; i < offset + count; i++) {
5825          var item = getWasmTableEntry(i);
5826          if (item) {
5827            functionsInTableMap.set(item, i);
5828          }
5829        }
5830      }
5831    };
5832    var functionsInTableMap;
5833    var getFunctionAddress = (func) => {
5834      if (!functionsInTableMap) {
5835        functionsInTableMap = /* @__PURE__ */ new WeakMap();
5836        updateTableMap(0, wasmTable.length);
5837      }
5838      return functionsInTableMap.get(func) || 0;
5839    };
5840    var freeTableIndexes = [];
5841    var getEmptyTableSlot = () => {
5842      if (freeTableIndexes.length) {
5843        return freeTableIndexes.pop();
5844      }
5845      try {
5846        wasmTable.grow(1);
5847      } catch (err2) {
5848        if (!(err2 instanceof RangeError)) {
5849          throw err2;
5850        }
5851        throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";
5852      }
5853      return wasmTable.length - 1;
5854    };
5855    var setWasmTableEntry = (idx, func) => {
5856      wasmTable.set(idx, func);
5857      wasmTableMirror[idx] = wasmTable.get(idx);
5858    };
5859    var addFunction = (func, sig) => {
5860      assert(typeof func != "undefined");
5861      var rtn = getFunctionAddress(func);
5862      if (rtn) {
5863        return rtn;
5864      }
5865      var ret = getEmptyTableSlot();
5866      try {
5867        setWasmTableEntry(ret, func);
5868      } catch (err2) {
5869        if (!(err2 instanceof TypeError)) {
5870          throw err2;
5871        }
5872        assert(typeof sig != "undefined", "Missing signature argument to addFunction: " + func);
5873        var wrapped = convertJsFunctionToWasm(func, sig);
5874        setWasmTableEntry(ret, wrapped);
5875      }
5876      functionsInTableMap.set(func, ret);
5877      return ret;
5878    };
5879    var getCFunc = (ident) => {
5880      var func = Module["_" + ident];
5881      assert(func, "Cannot call unknown function " + ident + ", make sure it is exported");
5882      return func;
5883    };
5884    var writeArrayToMemory = (array, buffer) => {
5885      assert(
5886        array.length >= 0,
5887        "writeArrayToMemory array must have a length (should be an array or typed array)"
5888      );
5889      HEAP8.set(array, buffer);
5890    };
5891    var stackAlloc = (sz) => __emscripten_stack_alloc(sz);
5892    var stringToUTF8OnStack = (str) => {
5893      var size = lengthBytesUTF8(str) + 1;
5894      var ret = stackAlloc(size);
5895      stringToUTF8(str, ret, size);
5896      return ret;
5897    };
5898    var ccall = (ident, returnType, argTypes, args, opts) => {
5899      var toC = {
5900        string: (str) => {
5901          var ret2 = 0;
5902          if (str !== null && str !== void 0 && str !== 0) {
5903            ret2 = stringToUTF8OnStack(str);
5904          }
5905          return ret2;
5906        },
5907        array: (arr) => {
5908          var ret2 = stackAlloc(arr.length);
5909          writeArrayToMemory(arr, ret2);
5910          return ret2;
5911        }
5912      };
5913      function convertReturnValue(ret2) {
5914        if (returnType === "string") {
5915          return UTF8ToString(ret2);
5916        }
5917        if (returnType === "boolean") return Boolean(ret2);
5918        return ret2;
5919      }
5920      var func = getCFunc(ident);
5921      var cArgs = [];
5922      var stack = 0;
5923      assert(returnType !== "array", 'Return type should not be "array".');
5924      if (args) {
5925        for (var i = 0; i < args.length; i++) {
5926          var converter = toC[argTypes[i]];
5927          if (converter) {
5928            if (stack === 0) stack = stackSave();
5929            cArgs[i] = converter(args[i]);
5930          } else {
5931            cArgs[i] = args[i];
5932          }
5933        }
5934      }
5935      var ret = func(...cArgs);
5936      function onDone(ret2) {
5937        if (stack !== 0) stackRestore(stack);
5938        return convertReturnValue(ret2);
5939      }
5940      ret = onDone(ret);
5941      return ret;
5942    };
5943    var cwrap = (ident, returnType, argTypes, opts) => {
5944      return (...args) => ccall(ident, returnType, argTypes, args);
5945    };
5946    var removeFunction = (index) => {
5947      functionsInTableMap.delete(getWasmTableEntry(index));
5948      setWasmTableEntry(index, null);
5949      freeTableIndexes.push(index);
5950    };
5951    var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {
5952      assert(outPtr % 2 == 0, "Pointer passed to stringToUTF16 must be aligned to two bytes!");
5953      assert(
5954        typeof maxBytesToWrite == "number",
5955        "stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"
5956      );
5957      maxBytesToWrite ?? (maxBytesToWrite = 2147483647);
5958      if (maxBytesToWrite < 2) return 0;
5959      maxBytesToWrite -= 2;
5960      var startPtr = outPtr;
5961      var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;
5962      for (var i = 0; i < numCharsToWrite; ++i) {
5963        var codeUnit = str.charCodeAt(i);
5964        HEAP16[outPtr >> 1] = codeUnit;
5965        outPtr += 2;
5966      }
5967      HEAP16[outPtr >> 1] = 0;
5968      return outPtr - startPtr;
5969    };
5970    FS.createPreloadedFile = FS_createPreloadedFile;
5971    FS.staticInit();
5972    function checkIncomingModuleAPI() {
5973      ignoredModuleProp("fetchSettings");
5974    }
5975    var wasmImports = {
5976      /** @export */
5977      __assert_fail: ___assert_fail,
5978      /** @export */
5979      __syscall_fcntl64: ___syscall_fcntl64,
5980      /** @export */
5981      __syscall_fstat64: ___syscall_fstat64,
5982      /** @export */
5983      __syscall_ftruncate64: ___syscall_ftruncate64,
5984      /** @export */
5985      __syscall_getdents64: ___syscall_getdents64,
5986      /** @export */
5987      __syscall_ioctl: ___syscall_ioctl,
5988      /** @export */
5989      __syscall_lstat64: ___syscall_lstat64,
5990      /** @export */
5991      __syscall_newfstatat: ___syscall_newfstatat,
5992      /** @export */
5993      __syscall_openat: ___syscall_openat,
5994      /** @export */
5995      __syscall_rmdir: ___syscall_rmdir,
5996      /** @export */
5997      __syscall_stat64: ___syscall_stat64,
5998      /** @export */
5999      __syscall_unlinkat: ___syscall_unlinkat,
6000      /** @export */
6001      _abort_js: __abort_js,
6002      /** @export */
6003      _emscripten_memcpy_js: __emscripten_memcpy_js,
6004      /** @export */
6005      _emscripten_throw_longjmp: __emscripten_throw_longjmp,
6006      /** @export */
6007      _gmtime_js: __gmtime_js,
6008      /** @export */
6009      _localtime_js: __localtime_js,
6010      /** @export */
6011      _tzset_js: __tzset_js,
6012      /** @export */
6013      emscripten_date_now: _emscripten_date_now,
6014      /** @export */
6015      emscripten_resize_heap: _emscripten_resize_heap,
6016      /** @export */
6017      environ_get: _environ_get,
6018      /** @export */
6019      environ_sizes_get: _environ_sizes_get,
6020      /** @export */
6021      fd_close: _fd_close,
6022      /** @export */
6023      fd_read: _fd_read,
6024      /** @export */
6025      fd_seek: _fd_seek,
6026      /** @export */
6027      fd_sync: _fd_sync,
6028      /** @export */
6029      fd_write: _fd_write,
6030      /** @export */
6031      invoke_ii,
6032      /** @export */
6033      invoke_iii,
6034      /** @export */
6035      invoke_iiii,
6036      /** @export */
6037      invoke_iiiii,
6038      /** @export */
6039      invoke_v,
6040      /** @export */
6041      invoke_vi,
6042      /** @export */
6043      invoke_vii,
6044      /** @export */
6045      invoke_viii,
6046      /** @export */
6047      invoke_viiii,
6048      /** @export */
6049      invoke_viiiiiiiii
6050    };
6051    var wasmExports = createWasm();
6052    Module["_PDFiumExt_Init"] = createExportWrapper("PDFiumExt_Init", 0);
6053    Module["_FPDF_InitLibraryWithConfig"] = createExportWrapper(
6054      "FPDF_InitLibraryWithConfig",
6055      1
6056    );
6057    Module["_PDFiumExt_OpenFileWriter"] = createExportWrapper(
6058      "PDFiumExt_OpenFileWriter",
6059      0
6060    );
6061    Module["_PDFiumExt_GetFileWriterSize"] = createExportWrapper("PDFiumExt_GetFileWriterSize", 1);
6062    Module["_PDFiumExt_GetFileWriterData"] = createExportWrapper("PDFiumExt_GetFileWriterData", 3);
6063    Module["_PDFiumExt_CloseFileWriter"] = createExportWrapper(
6064      "PDFiumExt_CloseFileWriter",
6065      1
6066    );
6067    Module["_PDFiumExt_SaveAsCopy"] = createExportWrapper(
6068      "PDFiumExt_SaveAsCopy",
6069      2
6070    );
6071    Module["_FPDF_SaveAsCopy"] = createExportWrapper("FPDF_SaveAsCopy", 3);
6072    Module["_PDFiumExt_OpenFormFillInfo"] = createExportWrapper(
6073      "PDFiumExt_OpenFormFillInfo",
6074      0
6075    );
6076    Module["_PDFiumExt_CloseFormFillInfo"] = createExportWrapper("PDFiumExt_CloseFormFillInfo", 1);
6077    Module["_PDFiumExt_InitFormFillEnvironment"] = createExportWrapper("PDFiumExt_InitFormFillEnvironment", 2);
6078    Module["_FPDFDOC_InitFormFillEnvironment"] = createExportWrapper("FPDFDOC_InitFormFillEnvironment", 2);
6079    Module["_PDFiumExt_ExitFormFillEnvironment"] = createExportWrapper("PDFiumExt_ExitFormFillEnvironment", 1);
6080    Module["_FPDFDOC_ExitFormFillEnvironment"] = createExportWrapper("FPDFDOC_ExitFormFillEnvironment", 1);
6081    Module["_EPDFNamedDest_SetDest"] = createExportWrapper(
6082      "EPDFNamedDest_SetDest",
6083      3
6084    );
6085    Module["_EPDFNamedDest_Remove"] = createExportWrapper(
6086      "EPDFNamedDest_Remove",
6087      2
6088    );
6089    Module["_EPDFDest_CreateView"] = createExportWrapper(
6090      "EPDFDest_CreateView",
6091      4
6092    );
6093    Module["_EPDFDest_CreateXYZ"] = createExportWrapper(
6094      "EPDFDest_CreateXYZ",
6095      7
6096    );
6097    Module["_EPDFDest_CreateRemoteView"] = createExportWrapper(
6098      "EPDFDest_CreateRemoteView",
6099      5
6100    );
6101    Module["_EPDFDest_CreateRemoteXYZ"] = createExportWrapper(
6102      "EPDFDest_CreateRemoteXYZ",
6103      8
6104    );
6105    Module["_EPDFAction_CreateGoTo"] = createExportWrapper(
6106      "EPDFAction_CreateGoTo",
6107      2
6108    );
6109    Module["_EPDFAction_CreateGoToNamed"] = createExportWrapper(
6110      "EPDFAction_CreateGoToNamed",
6111      2
6112    );
6113    Module["_EPDFAction_CreateLaunch"] = createExportWrapper(
6114      "EPDFAction_CreateLaunch",
6115      2
6116    );
6117    Module["_EPDFAction_CreateRemoteGoToByName"] = createExportWrapper("EPDFAction_CreateRemoteGoToByName", 3);
6118    Module["_EPDFAction_CreateRemoteGoToDest"] = createExportWrapper("EPDFAction_CreateRemoteGoToDest", 3);
6119    Module["_EPDFAction_CreateURI"] = createExportWrapper(
6120      "EPDFAction_CreateURI",
6121      2
6122    );
6123    Module["_EPDFBookmark_Create"] = createExportWrapper(
6124      "EPDFBookmark_Create",
6125      2
6126    );
6127    Module["_EPDFBookmark_Delete"] = createExportWrapper(
6128      "EPDFBookmark_Delete",
6129      2
6130    );
6131    Module["_EPDFBookmark_AppendChild"] = createExportWrapper(
6132      "EPDFBookmark_AppendChild",
6133      3
6134    );
6135    Module["_EPDFBookmark_InsertAfter"] = createExportWrapper(
6136      "EPDFBookmark_InsertAfter",
6137      4
6138    );
6139    Module["_EPDFBookmark_Clear"] = createExportWrapper(
6140      "EPDFBookmark_Clear",
6141      1
6142    );
6143    Module["_EPDFBookmark_SetTitle"] = createExportWrapper(
6144      "EPDFBookmark_SetTitle",
6145      2
6146    );
6147    Module["_EPDFBookmark_SetDest"] = createExportWrapper(
6148      "EPDFBookmark_SetDest",
6149      3
6150    );
6151    Module["_EPDFBookmark_SetAction"] = createExportWrapper(
6152      "EPDFBookmark_SetAction",
6153      3
6154    );
6155    Module["_EPDFBookmark_ClearTarget"] = createExportWrapper(
6156      "EPDFBookmark_ClearTarget",
6157      1
6158    );
6159    Module["_EPDF_PNG_EncodeRGBA"] = createExportWrapper(
6160      "EPDF_PNG_EncodeRGBA",
6161      6
6162    );
6163    Module["_FPDFAnnot_IsSupportedSubtype"] = createExportWrapper("FPDFAnnot_IsSupportedSubtype", 1);
6164    Module["_FPDFPage_CreateAnnot"] = createExportWrapper(
6165      "FPDFPage_CreateAnnot",
6166      2
6167    );
6168    Module["_FPDFPage_GetAnnotCount"] = createExportWrapper(
6169      "FPDFPage_GetAnnotCount",
6170      1
6171    );
6172    Module["_FPDFPage_GetAnnot"] = createExportWrapper(
6173      "FPDFPage_GetAnnot",
6174      2
6175    );
6176    Module["_FPDFPage_GetAnnotIndex"] = createExportWrapper(
6177      "FPDFPage_GetAnnotIndex",
6178      2
6179    );
6180    Module["_FPDFPage_CloseAnnot"] = createExportWrapper(
6181      "FPDFPage_CloseAnnot",
6182      1
6183    );
6184    Module["_FPDFPage_RemoveAnnot"] = createExportWrapper(
6185      "FPDFPage_RemoveAnnot",
6186      2
6187    );
6188    Module["_FPDFAnnot_GetSubtype"] = createExportWrapper(
6189      "FPDFAnnot_GetSubtype",
6190      1
6191    );
6192    Module["_FPDFAnnot_IsObjectSupportedSubtype"] = createExportWrapper("FPDFAnnot_IsObjectSupportedSubtype", 1);
6193    Module["_FPDFAnnot_UpdateObject"] = createExportWrapper(
6194      "FPDFAnnot_UpdateObject",
6195      2
6196    );
6197    Module["_FPDFAnnot_AddInkStroke"] = createExportWrapper(
6198      "FPDFAnnot_AddInkStroke",
6199      3
6200    );
6201    Module["_FPDFAnnot_RemoveInkList"] = createExportWrapper(
6202      "FPDFAnnot_RemoveInkList",
6203      1
6204    );
6205    Module["_FPDFAnnot_AppendObject"] = createExportWrapper(
6206      "FPDFAnnot_AppendObject",
6207      2
6208    );
6209    Module["_FPDFAnnot_GetObjectCount"] = createExportWrapper(
6210      "FPDFAnnot_GetObjectCount",
6211      1
6212    );
6213    Module["_FPDFAnnot_GetObject"] = createExportWrapper(
6214      "FPDFAnnot_GetObject",
6215      2
6216    );
6217    Module["_FPDFAnnot_RemoveObject"] = createExportWrapper(
6218      "FPDFAnnot_RemoveObject",
6219      2
6220    );
6221    Module["_FPDFAnnot_SetColor"] = createExportWrapper(
6222      "FPDFAnnot_SetColor",
6223      6
6224    );
6225    Module["_FPDFAnnot_GetColor"] = createExportWrapper(
6226      "FPDFAnnot_GetColor",
6227      6
6228    );
6229    Module["_FPDFAnnot_HasAttachmentPoints"] = createExportWrapper("FPDFAnnot_HasAttachmentPoints", 1);
6230    Module["_FPDFAnnot_SetAttachmentPoints"] = createExportWrapper("FPDFAnnot_SetAttachmentPoints", 3);
6231    Module["_FPDFAnnot_AppendAttachmentPoints"] = createExportWrapper("FPDFAnnot_AppendAttachmentPoints", 2);
6232    Module["_FPDFAnnot_CountAttachmentPoints"] = createExportWrapper("FPDFAnnot_CountAttachmentPoints", 1);
6233    Module["_FPDFAnnot_GetAttachmentPoints"] = createExportWrapper("FPDFAnnot_GetAttachmentPoints", 3);
6234    Module["_FPDFAnnot_SetRect"] = createExportWrapper(
6235      "FPDFAnnot_SetRect",
6236      2
6237    );
6238    Module["_FPDFAnnot_GetRect"] = createExportWrapper(
6239      "FPDFAnnot_GetRect",
6240      2
6241    );
6242    Module["_FPDFAnnot_GetVertices"] = createExportWrapper(
6243      "FPDFAnnot_GetVertices",
6244      3
6245    );
6246    Module["_FPDFAnnot_GetInkListCount"] = createExportWrapper(
6247      "FPDFAnnot_GetInkListCount",
6248      1
6249    );
6250    Module["_FPDFAnnot_GetInkListPath"] = createExportWrapper(
6251      "FPDFAnnot_GetInkListPath",
6252      4
6253    );
6254    Module["_FPDFAnnot_GetLine"] = createExportWrapper(
6255      "FPDFAnnot_GetLine",
6256      3
6257    );
6258    Module["_FPDFAnnot_SetBorder"] = createExportWrapper(
6259      "FPDFAnnot_SetBorder",
6260      4
6261    );
6262    Module["_FPDFAnnot_GetBorder"] = createExportWrapper(
6263      "FPDFAnnot_GetBorder",
6264      4
6265    );
6266    Module["_FPDFAnnot_HasKey"] = createExportWrapper(
6267      "FPDFAnnot_HasKey",
6268      2
6269    );
6270    Module["_FPDFAnnot_GetValueType"] = createExportWrapper(
6271      "FPDFAnnot_GetValueType",
6272      2
6273    );
6274    Module["_FPDFAnnot_SetStringValue"] = createExportWrapper(
6275      "FPDFAnnot_SetStringValue",
6276      3
6277    );
6278    Module["_FPDFAnnot_GetStringValue"] = createExportWrapper(
6279      "FPDFAnnot_GetStringValue",
6280      4
6281    );
6282    Module["_FPDFAnnot_GetNumberValue"] = createExportWrapper(
6283      "FPDFAnnot_GetNumberValue",
6284      3
6285    );
6286    Module["_EPDFAnnot_SetNumberValue"] = createExportWrapper(
6287      "EPDFAnnot_SetNumberValue",
6288      3
6289    );
6290    Module["_FPDFAnnot_SetAP"] = createExportWrapper("FPDFAnnot_SetAP", 3);
6291    Module["_FPDFAnnot_GetAP"] = createExportWrapper("FPDFAnnot_GetAP", 4);
6292    Module["_FPDFAnnot_GetLinkedAnnot"] = createExportWrapper(
6293      "FPDFAnnot_GetLinkedAnnot",
6294      2
6295    );
6296    Module["_FPDFAnnot_GetFlags"] = createExportWrapper(
6297      "FPDFAnnot_GetFlags",
6298      1
6299    );
6300    Module["_FPDFAnnot_SetFlags"] = createExportWrapper(
6301      "FPDFAnnot_SetFlags",
6302      2
6303    );
6304    Module["_FPDFAnnot_GetFormFieldFlags"] = createExportWrapper("FPDFAnnot_GetFormFieldFlags", 2);
6305    Module["_FPDFAnnot_SetFormFieldFlags"] = createExportWrapper("FPDFAnnot_SetFormFieldFlags", 3);
6306    Module["_FPDFAnnot_GetFormFieldAtPoint"] = createExportWrapper("FPDFAnnot_GetFormFieldAtPoint", 3);
6307    Module["_FPDFAnnot_GetFormFieldName"] = createExportWrapper(
6308      "FPDFAnnot_GetFormFieldName",
6309      4
6310    );
6311    Module["_FPDFAnnot_GetFormFieldType"] = createExportWrapper(
6312      "FPDFAnnot_GetFormFieldType",
6313      2
6314    );
6315    Module["_FPDFAnnot_GetFormAdditionalActionJavaScript"] = createExportWrapper("FPDFAnnot_GetFormAdditionalActionJavaScript", 5);
6316    Module["_FPDFAnnot_GetFormFieldAlternateName"] = createExportWrapper("FPDFAnnot_GetFormFieldAlternateName", 4);
6317    Module["_FPDFAnnot_GetFormFieldValue"] = createExportWrapper("FPDFAnnot_GetFormFieldValue", 4);
6318    Module["_FPDFAnnot_GetOptionCount"] = createExportWrapper(
6319      "FPDFAnnot_GetOptionCount",
6320      2
6321    );
6322    Module["_FPDFAnnot_GetOptionLabel"] = createExportWrapper(
6323      "FPDFAnnot_GetOptionLabel",
6324      5
6325    );
6326    Module["_FPDFAnnot_IsOptionSelected"] = createExportWrapper(
6327      "FPDFAnnot_IsOptionSelected",
6328      3
6329    );
6330    Module["_FPDFAnnot_GetFontSize"] = createExportWrapper(
6331      "FPDFAnnot_GetFontSize",
6332      3
6333    );
6334    Module["_FPDFAnnot_SetFontColor"] = createExportWrapper(
6335      "FPDFAnnot_SetFontColor",
6336      5
6337    );
6338    Module["_FPDFAnnot_GetFontColor"] = createExportWrapper(
6339      "FPDFAnnot_GetFontColor",
6340      5
6341    );
6342    Module["_FPDFAnnot_IsChecked"] = createExportWrapper(
6343      "FPDFAnnot_IsChecked",
6344      2
6345    );
6346    Module["_FPDFAnnot_SetFocusableSubtypes"] = createExportWrapper("FPDFAnnot_SetFocusableSubtypes", 3);
6347    Module["_FPDFAnnot_GetFocusableSubtypesCount"] = createExportWrapper("FPDFAnnot_GetFocusableSubtypesCount", 1);
6348    Module["_FPDFAnnot_GetFocusableSubtypes"] = createExportWrapper("FPDFAnnot_GetFocusableSubtypes", 3);
6349    Module["_FPDFAnnot_GetLink"] = createExportWrapper(
6350      "FPDFAnnot_GetLink",
6351      1
6352    );
6353    Module["_FPDFAnnot_GetFormControlCount"] = createExportWrapper("FPDFAnnot_GetFormControlCount", 2);
6354    Module["_FPDFAnnot_GetFormControlIndex"] = createExportWrapper("FPDFAnnot_GetFormControlIndex", 2);
6355    Module["_FPDFAnnot_GetFormFieldExportValue"] = createExportWrapper("FPDFAnnot_GetFormFieldExportValue", 4);
6356    Module["_FPDFAnnot_SetURI"] = createExportWrapper(
6357      "FPDFAnnot_SetURI",
6358      2
6359    );
6360    Module["_EPDFAnnot_SetAction"] = createExportWrapper(
6361      "EPDFAnnot_SetAction",
6362      2
6363    );
6364    Module["_FPDFAnnot_GetFileAttachment"] = createExportWrapper("FPDFAnnot_GetFileAttachment", 1);
6365    Module["_FPDFAnnot_AddFileAttachment"] = createExportWrapper("FPDFAnnot_AddFileAttachment", 2);
6366    Module["_EPDFAnnot_SetColor"] = createExportWrapper(
6367      "EPDFAnnot_SetColor",
6368      5
6369    );
6370    Module["_EPDFAnnot_GetColor"] = createExportWrapper(
6371      "EPDFAnnot_GetColor",
6372      5
6373    );
6374    Module["_EPDFAnnot_ClearColor"] = createExportWrapper(
6375      "EPDFAnnot_ClearColor",
6376      2
6377    );
6378    Module["_EPDFAnnot_SetOpacity"] = createExportWrapper(
6379      "EPDFAnnot_SetOpacity",
6380      2
6381    );
6382    Module["_EPDFAnnot_GetOpacity"] = createExportWrapper(
6383      "EPDFAnnot_GetOpacity",
6384      2
6385    );
6386    Module["_EPDFAnnot_GetBorderEffect"] = createExportWrapper(
6387      "EPDFAnnot_GetBorderEffect",
6388      2
6389    );
6390    Module["_EPDFAnnot_SetBorderEffect"] = createExportWrapper(
6391      "EPDFAnnot_SetBorderEffect",
6392      2
6393    );
6394    Module["_EPDFAnnot_ClearBorderEffect"] = createExportWrapper("EPDFAnnot_ClearBorderEffect", 1);
6395    Module["_EPDFAnnot_GetRectangleDifferences"] = createExportWrapper("EPDFAnnot_GetRectangleDifferences", 5);
6396    Module["_EPDFAnnot_SetRectangleDifferences"] = createExportWrapper("EPDFAnnot_SetRectangleDifferences", 5);
6397    Module["_EPDFAnnot_ClearRectangleDifferences"] = createExportWrapper("EPDFAnnot_ClearRectangleDifferences", 1);
6398    Module["_EPDFAnnot_GetBorderDashPatternCount"] = createExportWrapper("EPDFAnnot_GetBorderDashPatternCount", 1);
6399    Module["_EPDFAnnot_GetBorderDashPattern"] = createExportWrapper("EPDFAnnot_GetBorderDashPattern", 3);
6400    Module["_EPDFAnnot_SetBorderDashPattern"] = createExportWrapper("EPDFAnnot_SetBorderDashPattern", 3);
6401    Module["_EPDFAnnot_GetBorderStyle"] = createExportWrapper(
6402      "EPDFAnnot_GetBorderStyle",
6403      2
6404    );
6405    Module["_EPDFAnnot_SetBorderStyle"] = createExportWrapper(
6406      "EPDFAnnot_SetBorderStyle",
6407      3
6408    );
6409    Module["_EPDFAnnot_GenerateAppearance"] = createExportWrapper("EPDFAnnot_GenerateAppearance", 1);
6410    Module["_EPDFAnnot_GenerateAppearanceWithBlend"] = createExportWrapper("EPDFAnnot_GenerateAppearanceWithBlend", 2);
6411    Module["_EPDFAnnot_GetBlendMode"] = createExportWrapper(
6412      "EPDFAnnot_GetBlendMode",
6413      1
6414    );
6415    Module["_EPDFAnnot_SetIntent"] = createExportWrapper(
6416      "EPDFAnnot_SetIntent",
6417      2
6418    );
6419    Module["_EPDFAnnot_GetIntent"] = createExportWrapper(
6420      "EPDFAnnot_GetIntent",
6421      3
6422    );
6423    Module["_EPDFAnnot_GetRichContent"] = createExportWrapper(
6424      "EPDFAnnot_GetRichContent",
6425      3
6426    );
6427    Module["_EPDFAnnot_SetLineEndings"] = createExportWrapper(
6428      "EPDFAnnot_SetLineEndings",
6429      3
6430    );
6431    Module["_EPDFAnnot_GetLineEndings"] = createExportWrapper(
6432      "EPDFAnnot_GetLineEndings",
6433      3
6434    );
6435    Module["_EPDFAnnot_SetVertices"] = createExportWrapper(
6436      "EPDFAnnot_SetVertices",
6437      3
6438    );
6439    Module["_EPDFAnnot_SetLine"] = createExportWrapper(
6440      "EPDFAnnot_SetLine",
6441      3
6442    );
6443    Module["_EPDFAnnot_SetDefaultAppearance"] = createExportWrapper("EPDFAnnot_SetDefaultAppearance", 6);
6444    Module["_EPDFAnnot_GetDefaultAppearance"] = createExportWrapper("EPDFAnnot_GetDefaultAppearance", 6);
6445    Module["_EPDFAnnot_SetTextAlignment"] = createExportWrapper(
6446      "EPDFAnnot_SetTextAlignment",
6447      2
6448    );
6449    Module["_EPDFAnnot_GetTextAlignment"] = createExportWrapper(
6450      "EPDFAnnot_GetTextAlignment",
6451      1
6452    );
6453    Module["_EPDFAnnot_SetVerticalAlignment"] = createExportWrapper("EPDFAnnot_SetVerticalAlignment", 2);
6454    Module["_EPDFAnnot_GetVerticalAlignment"] = createExportWrapper("EPDFAnnot_GetVerticalAlignment", 1);
6455    Module["_EPDFPage_GetAnnotByName"] = createExportWrapper(
6456      "EPDFPage_GetAnnotByName",
6457      2
6458    );
6459    Module["_EPDFPage_RemoveAnnotByName"] = createExportWrapper(
6460      "EPDFPage_RemoveAnnotByName",
6461      2
6462    );
6463    Module["_EPDFAnnot_SetLinkedAnnot"] = createExportWrapper(
6464      "EPDFAnnot_SetLinkedAnnot",
6465      3
6466    );
6467    Module["_EPDFPage_GetAnnotCountRaw"] = createExportWrapper(
6468      "EPDFPage_GetAnnotCountRaw",
6469      2
6470    );
6471    Module["_EPDFPage_GetAnnotRaw"] = createExportWrapper(
6472      "EPDFPage_GetAnnotRaw",
6473      3
6474    );
6475    Module["_EPDFPage_RemoveAnnotRaw"] = createExportWrapper(
6476      "EPDFPage_RemoveAnnotRaw",
6477      3
6478    );
6479    Module["_EPDFAnnot_SetName"] = createExportWrapper(
6480      "EPDFAnnot_SetName",
6481      2
6482    );
6483    Module["_EPDFAnnot_GetName"] = createExportWrapper(
6484      "EPDFAnnot_GetName",
6485      1
6486    );
6487    Module["_EPDFAnnot_UpdateAppearanceToRect"] = createExportWrapper("EPDFAnnot_UpdateAppearanceToRect", 2);
6488    Module["_EPDFPage_CreateAnnot"] = createExportWrapper(
6489      "EPDFPage_CreateAnnot",
6490      2
6491    );
6492    Module["_EPDFAnnot_SetRotate"] = createExportWrapper(
6493      "EPDFAnnot_SetRotate",
6494      2
6495    );
6496    Module["_EPDFAnnot_GetRotate"] = createExportWrapper(
6497      "EPDFAnnot_GetRotate",
6498      2
6499    );
6500    Module["_EPDFAnnot_GetReplyType"] = createExportWrapper(
6501      "EPDFAnnot_GetReplyType",
6502      1
6503    );
6504    Module["_EPDFAnnot_SetReplyType"] = createExportWrapper(
6505      "EPDFAnnot_SetReplyType",
6506      2
6507    );
6508    Module["_EPDFAnnot_SetOverlayText"] = createExportWrapper(
6509      "EPDFAnnot_SetOverlayText",
6510      2
6511    );
6512    Module["_EPDFAnnot_GetOverlayText"] = createExportWrapper(
6513      "EPDFAnnot_GetOverlayText",
6514      3
6515    );
6516    Module["_EPDFAnnot_SetOverlayTextRepeat"] = createExportWrapper("EPDFAnnot_SetOverlayTextRepeat", 2);
6517    Module["_EPDFAnnot_GetOverlayTextRepeat"] = createExportWrapper("EPDFAnnot_GetOverlayTextRepeat", 1);
6518    Module["_EPDFAnnot_ApplyRedaction"] = createExportWrapper(
6519      "EPDFAnnot_ApplyRedaction",
6520      2
6521    );
6522    Module["_EPDFPage_ApplyRedactions"] = createExportWrapper(
6523      "EPDFPage_ApplyRedactions",
6524      1
6525    );
6526    Module["_EPDFAnnot_Flatten"] = createExportWrapper(
6527      "EPDFAnnot_Flatten",
6528      2
6529    );
6530    Module["_EPDFAnnot_SetAppearanceFromPage"] = createExportWrapper("EPDFAnnot_SetAppearanceFromPage", 3);
6531    Module["_EPDFAnnot_ExportAppearanceAsDocument"] = createExportWrapper("EPDFAnnot_ExportAppearanceAsDocument", 1);
6532    Module["_EPDFAnnot_ExportMultipleAppearancesAsDocument"] = createExportWrapper("EPDFAnnot_ExportMultipleAppearancesAsDocument", 2);
6533    Module["_EPDFAnnot_SetExtendedRotation"] = createExportWrapper("EPDFAnnot_SetExtendedRotation", 2);
6534    Module["_EPDFAnnot_GetExtendedRotation"] = createExportWrapper("EPDFAnnot_GetExtendedRotation", 2);
6535    Module["_EPDFAnnot_SetUnrotatedRect"] = createExportWrapper(
6536      "EPDFAnnot_SetUnrotatedRect",
6537      2
6538    );
6539    Module["_EPDFAnnot_GetUnrotatedRect"] = createExportWrapper(
6540      "EPDFAnnot_GetUnrotatedRect",
6541      2
6542    );
6543    Module["_EPDFAnnot_GetRect"] = createExportWrapper(
6544      "EPDFAnnot_GetRect",
6545      2
6546    );
6547    Module["_EPDFAnnot_SetAPMatrix"] = createExportWrapper(
6548      "EPDFAnnot_SetAPMatrix",
6549      3
6550    );
6551    Module["_EPDFAnnot_GetAPMatrix"] = createExportWrapper(
6552      "EPDFAnnot_GetAPMatrix",
6553      3
6554    );
6555    Module["_EPDFAnnot_GetAvailableAppearanceModes"] = createExportWrapper("EPDFAnnot_GetAvailableAppearanceModes", 1);
6556    Module["_EPDFAnnot_HasAppearanceStream"] = createExportWrapper("EPDFAnnot_HasAppearanceStream", 2);
6557    Module["_EPDFAnnot_SetMKColor"] = createExportWrapper(
6558      "EPDFAnnot_SetMKColor",
6559      5
6560    );
6561    Module["_EPDFAnnot_GetMKColor"] = createExportWrapper(
6562      "EPDFAnnot_GetMKColor",
6563      5
6564    );
6565    Module["_EPDFAnnot_ClearMKColor"] = createExportWrapper(
6566      "EPDFAnnot_ClearMKColor",
6567      2
6568    );
6569    Module["_EPDFPage_CreateFormField"] = createExportWrapper(
6570      "EPDFPage_CreateFormField",
6571      4
6572    );
6573    Module["_EPDFAnnot_GenerateFormFieldAP"] = createExportWrapper("EPDFAnnot_GenerateFormFieldAP", 1);
6574    Module["_EPDFAnnot_GetButtonExportValue"] = createExportWrapper("EPDFAnnot_GetButtonExportValue", 3);
6575    Module["_EPDFAnnot_GetFormFieldRawValue"] = createExportWrapper("EPDFAnnot_GetFormFieldRawValue", 4);
6576    Module["_EPDFAnnot_SetFormFieldValue"] = createExportWrapper("EPDFAnnot_SetFormFieldValue", 3);
6577    Module["_EPDFAnnot_SetFormFieldName"] = createExportWrapper(
6578      "EPDFAnnot_SetFormFieldName",
6579      3
6580    );
6581    Module["_EPDFAnnot_GetFormFieldObjectNumber"] = createExportWrapper("EPDFAnnot_GetFormFieldObjectNumber", 2);
6582    Module["_EPDFAnnot_ShareFormField"] = createExportWrapper(
6583      "EPDFAnnot_ShareFormField",
6584      3
6585    );
6586    Module["_EPDFAnnot_SetFormFieldOptions"] = createExportWrapper("EPDFAnnot_SetFormFieldOptions", 4);
6587    Module["_FPDFDoc_GetAttachmentCount"] = createExportWrapper(
6588      "FPDFDoc_GetAttachmentCount",
6589      1
6590    );
6591    Module["_FPDFDoc_AddAttachment"] = createExportWrapper(
6592      "FPDFDoc_AddAttachment",
6593      2
6594    );
6595    Module["_FPDFDoc_GetAttachment"] = createExportWrapper(
6596      "FPDFDoc_GetAttachment",
6597      2
6598    );
6599    Module["_FPDFDoc_DeleteAttachment"] = createExportWrapper(
6600      "FPDFDoc_DeleteAttachment",
6601      2
6602    );
6603    Module["_FPDFAttachment_GetName"] = createExportWrapper(
6604      "FPDFAttachment_GetName",
6605      3
6606    );
6607    Module["_FPDFAttachment_HasKey"] = createExportWrapper(
6608      "FPDFAttachment_HasKey",
6609      2
6610    );
6611    Module["_FPDFAttachment_GetValueType"] = createExportWrapper("FPDFAttachment_GetValueType", 2);
6612    Module["_FPDFAttachment_SetStringValue"] = createExportWrapper("FPDFAttachment_SetStringValue", 3);
6613    Module["_FPDFAttachment_GetStringValue"] = createExportWrapper("FPDFAttachment_GetStringValue", 4);
6614    Module["_FPDFAttachment_SetFile"] = createExportWrapper(
6615      "FPDFAttachment_SetFile",
6616      4
6617    );
6618    Module["_FPDFAttachment_GetFile"] = createExportWrapper(
6619      "FPDFAttachment_GetFile",
6620      4
6621    );
6622    Module["_FPDFAttachment_GetSubtype"] = createExportWrapper(
6623      "FPDFAttachment_GetSubtype",
6624      3
6625    );
6626    Module["_EPDFAttachment_SetSubtype"] = createExportWrapper(
6627      "EPDFAttachment_SetSubtype",
6628      2
6629    );
6630    Module["_EPDFAttachment_SetDescription"] = createExportWrapper("EPDFAttachment_SetDescription", 2);
6631    Module["_EPDFAttachment_GetDescription"] = createExportWrapper("EPDFAttachment_GetDescription", 3);
6632    Module["_EPDFAttachment_GetIntegerValue"] = createExportWrapper("EPDFAttachment_GetIntegerValue", 3);
6633    Module["_FPDFCatalog_IsTagged"] = createExportWrapper(
6634      "FPDFCatalog_IsTagged",
6635      1
6636    );
6637    Module["_FPDFCatalog_GetLanguage"] = createExportWrapper(
6638      "FPDFCatalog_GetLanguage",
6639      3
6640    );
6641    Module["_FPDFCatalog_SetLanguage"] = createExportWrapper(
6642      "FPDFCatalog_SetLanguage",
6643      2
6644    );
6645    Module["_EPDFCatalog_GetLanguage"] = createExportWrapper(
6646      "EPDFCatalog_GetLanguage",
6647      3
6648    );
6649    Module["_FPDFAvail_Create"] = createExportWrapper(
6650      "FPDFAvail_Create",
6651      2
6652    );
6653    Module["_FPDFAvail_Destroy"] = createExportWrapper(
6654      "FPDFAvail_Destroy",
6655      1
6656    );
6657    Module["_FPDFAvail_IsDocAvail"] = createExportWrapper(
6658      "FPDFAvail_IsDocAvail",
6659      2
6660    );
6661    Module["_FPDFAvail_GetDocument"] = createExportWrapper(
6662      "FPDFAvail_GetDocument",
6663      2
6664    );
6665    Module["_FPDFAvail_GetFirstPageNum"] = createExportWrapper(
6666      "FPDFAvail_GetFirstPageNum",
6667      1
6668    );
6669    Module["_FPDFAvail_IsPageAvail"] = createExportWrapper(
6670      "FPDFAvail_IsPageAvail",
6671      3
6672    );
6673    Module["_FPDFAvail_IsFormAvail"] = createExportWrapper(
6674      "FPDFAvail_IsFormAvail",
6675      2
6676    );
6677    Module["_FPDFAvail_IsLinearized"] = createExportWrapper(
6678      "FPDFAvail_IsLinearized",
6679      1
6680    );
6681    Module["_FPDFBookmark_GetFirstChild"] = createExportWrapper(
6682      "FPDFBookmark_GetFirstChild",
6683      2
6684    );
6685    Module["_FPDFBookmark_GetNextSibling"] = createExportWrapper("FPDFBookmark_GetNextSibling", 2);
6686    Module["_FPDFBookmark_GetTitle"] = createExportWrapper(
6687      "FPDFBookmark_GetTitle",
6688      3
6689    );
6690    Module["_FPDFBookmark_GetCount"] = createExportWrapper(
6691      "FPDFBookmark_GetCount",
6692      1
6693    );
6694    Module["_FPDFBookmark_Find"] = createExportWrapper(
6695      "FPDFBookmark_Find",
6696      2
6697    );
6698    Module["_FPDFBookmark_GetDest"] = createExportWrapper(
6699      "FPDFBookmark_GetDest",
6700      2
6701    );
6702    Module["_FPDFBookmark_GetAction"] = createExportWrapper(
6703      "FPDFBookmark_GetAction",
6704      1
6705    );
6706    Module["_FPDFAction_GetType"] = createExportWrapper(
6707      "FPDFAction_GetType",
6708      1
6709    );
6710    Module["_FPDFAction_GetDest"] = createExportWrapper(
6711      "FPDFAction_GetDest",
6712      2
6713    );
6714    Module["_FPDFAction_GetFilePath"] = createExportWrapper(
6715      "FPDFAction_GetFilePath",
6716      3
6717    );
6718    Module["_FPDFAction_GetURIPath"] = createExportWrapper(
6719      "FPDFAction_GetURIPath",
6720      4
6721    );
6722    Module["_FPDFDest_GetDestPageIndex"] = createExportWrapper(
6723      "FPDFDest_GetDestPageIndex",
6724      2
6725    );
6726    Module["_FPDFDest_GetView"] = createExportWrapper(
6727      "FPDFDest_GetView",
6728      3
6729    );
6730    Module["_FPDFDest_GetLocationInPage"] = createExportWrapper(
6731      "FPDFDest_GetLocationInPage",
6732      7
6733    );
6734    Module["_FPDFLink_GetLinkAtPoint"] = createExportWrapper(
6735      "FPDFLink_GetLinkAtPoint",
6736      3
6737    );
6738    Module["_FPDFLink_GetLinkZOrderAtPoint"] = createExportWrapper("FPDFLink_GetLinkZOrderAtPoint", 3);
6739    Module["_FPDFLink_GetDest"] = createExportWrapper(
6740      "FPDFLink_GetDest",
6741      2
6742    );
6743    Module["_FPDFLink_GetAction"] = createExportWrapper(
6744      "FPDFLink_GetAction",
6745      1
6746    );
6747    Module["_FPDFLink_Enumerate"] = createExportWrapper(
6748      "FPDFLink_Enumerate",
6749      3
6750    );
6751    Module["_FPDFLink_GetAnnot"] = createExportWrapper(
6752      "FPDFLink_GetAnnot",
6753      2
6754    );
6755    Module["_FPDFLink_GetAnnotRect"] = createExportWrapper(
6756      "FPDFLink_GetAnnotRect",
6757      2
6758    );
6759    Module["_FPDFLink_CountQuadPoints"] = createExportWrapper(
6760      "FPDFLink_CountQuadPoints",
6761      1
6762    );
6763    Module["_FPDFLink_GetQuadPoints"] = createExportWrapper(
6764      "FPDFLink_GetQuadPoints",
6765      3
6766    );
6767    Module["_FPDF_GetPageAAction"] = createExportWrapper(
6768      "FPDF_GetPageAAction",
6769      2
6770    );
6771    Module["_FPDF_GetFileIdentifier"] = createExportWrapper(
6772      "FPDF_GetFileIdentifier",
6773      4
6774    );
6775    Module["_FPDF_GetMetaText"] = createExportWrapper(
6776      "FPDF_GetMetaText",
6777      4
6778    );
6779    Module["_FPDF_GetPageLabel"] = createExportWrapper(
6780      "FPDF_GetPageLabel",
6781      4
6782    );
6783    Module["_EPDF_SetMetaText"] = createExportWrapper(
6784      "EPDF_SetMetaText",
6785      3
6786    );
6787    Module["_EPDF_HasMetaText"] = createExportWrapper(
6788      "EPDF_HasMetaText",
6789      2
6790    );
6791    Module["_EPDF_GetMetaTrapped"] = createExportWrapper(
6792      "EPDF_GetMetaTrapped",
6793      1
6794    );
6795    Module["_EPDF_SetMetaTrapped"] = createExportWrapper(
6796      "EPDF_SetMetaTrapped",
6797      2
6798    );
6799    Module["_EPDF_GetMetaKeyCount"] = createExportWrapper(
6800      "EPDF_GetMetaKeyCount",
6801      2
6802    );
6803    Module["_EPDF_GetMetaKeyName"] = createExportWrapper(
6804      "EPDF_GetMetaKeyName",
6805      5
6806    );
6807    Module["_FPDFPageObj_NewImageObj"] = createExportWrapper(
6808      "FPDFPageObj_NewImageObj",
6809      1
6810    );
6811    Module["_FPDFImageObj_LoadJpegFile"] = createExportWrapper(
6812      "FPDFImageObj_LoadJpegFile",
6813      4
6814    );
6815    Module["_FPDFImageObj_LoadJpegFileInline"] = createExportWrapper("FPDFImageObj_LoadJpegFileInline", 4);
6816    Module["_FPDFImageObj_SetMatrix"] = createExportWrapper(
6817      "FPDFImageObj_SetMatrix",
6818      7
6819    );
6820    Module["_FPDFImageObj_SetBitmap"] = createExportWrapper(
6821      "FPDFImageObj_SetBitmap",
6822      4
6823    );
6824    Module["_FPDFImageObj_GetBitmap"] = createExportWrapper(
6825      "FPDFImageObj_GetBitmap",
6826      1
6827    );
6828    Module["_FPDFImageObj_GetRenderedBitmap"] = createExportWrapper("FPDFImageObj_GetRenderedBitmap", 3);
6829    Module["_FPDFImageObj_GetImageDataDecoded"] = createExportWrapper("FPDFImageObj_GetImageDataDecoded", 3);
6830    Module["_FPDFImageObj_GetImageDataRaw"] = createExportWrapper("FPDFImageObj_GetImageDataRaw", 3);
6831    Module["_FPDFImageObj_GetImageFilterCount"] = createExportWrapper("FPDFImageObj_GetImageFilterCount", 1);
6832    Module["_FPDFImageObj_GetImageFilter"] = createExportWrapper("FPDFImageObj_GetImageFilter", 4);
6833    Module["_FPDFImageObj_GetImageMetadata"] = createExportWrapper("FPDFImageObj_GetImageMetadata", 3);
6834    Module["_FPDFImageObj_GetImagePixelSize"] = createExportWrapper("FPDFImageObj_GetImagePixelSize", 3);
6835    Module["_FPDFImageObj_GetIccProfileDataDecoded"] = createExportWrapper("FPDFImageObj_GetIccProfileDataDecoded", 5);
6836    Module["_EPDFImageObj_SetPng"] = createExportWrapper(
6837      "EPDFImageObj_SetPng",
6838      5
6839    );
6840    Module["_EPDFImageObj_SetJpeg"] = createExportWrapper(
6841      "EPDFImageObj_SetJpeg",
6842      5
6843    );
6844    Module["_FPDF_CreateNewDocument"] = createExportWrapper(
6845      "FPDF_CreateNewDocument",
6846      0
6847    );
6848    Module["_FPDFPage_Delete"] = createExportWrapper("FPDFPage_Delete", 2);
6849    Module["_FPDF_MovePages"] = createExportWrapper("FPDF_MovePages", 4);
6850    Module["_FPDFPage_New"] = createExportWrapper("FPDFPage_New", 4);
6851    Module["_FPDFPage_GetRotation"] = createExportWrapper(
6852      "FPDFPage_GetRotation",
6853      1
6854    );
6855    Module["_FPDFPage_InsertObject"] = createExportWrapper(
6856      "FPDFPage_InsertObject",
6857      2
6858    );
6859    Module["_FPDFPage_InsertObjectAtIndex"] = createExportWrapper("FPDFPage_InsertObjectAtIndex", 3);
6860    Module["_FPDFPage_RemoveObject"] = createExportWrapper(
6861      "FPDFPage_RemoveObject",
6862      2
6863    );
6864    Module["_FPDFPage_CountObjects"] = createExportWrapper(
6865      "FPDFPage_CountObjects",
6866      1
6867    );
6868    Module["_FPDFPage_GetObject"] = createExportWrapper(
6869      "FPDFPage_GetObject",
6870      2
6871    );
6872    Module["_FPDFPage_HasTransparency"] = createExportWrapper(
6873      "FPDFPage_HasTransparency",
6874      1
6875    );
6876    Module["_FPDFPageObj_Destroy"] = createExportWrapper(
6877      "FPDFPageObj_Destroy",
6878      1
6879    );
6880    Module["_FPDFPageObj_GetMarkedContentID"] = createExportWrapper("FPDFPageObj_GetMarkedContentID", 1);
6881    Module["_FPDFPageObj_CountMarks"] = createExportWrapper(
6882      "FPDFPageObj_CountMarks",
6883      1
6884    );
6885    Module["_FPDFPageObj_GetMark"] = createExportWrapper(
6886      "FPDFPageObj_GetMark",
6887      2
6888    );
6889    Module["_FPDFPageObj_AddMark"] = createExportWrapper(
6890      "FPDFPageObj_AddMark",
6891      2
6892    );
6893    Module["_FPDFPageObj_RemoveMark"] = createExportWrapper(
6894      "FPDFPageObj_RemoveMark",
6895      2
6896    );
6897    Module["_FPDFPageObjMark_GetName"] = createExportWrapper(
6898      "FPDFPageObjMark_GetName",
6899      4
6900    );
6901    Module["_FPDFPageObjMark_CountParams"] = createExportWrapper("FPDFPageObjMark_CountParams", 1);
6902    Module["_FPDFPageObjMark_GetParamKey"] = createExportWrapper("FPDFPageObjMark_GetParamKey", 5);
6903    Module["_FPDFPageObjMark_GetParamValueType"] = createExportWrapper("FPDFPageObjMark_GetParamValueType", 2);
6904    Module["_FPDFPageObjMark_GetParamIntValue"] = createExportWrapper("FPDFPageObjMark_GetParamIntValue", 3);
6905    Module["_FPDFPageObjMark_GetParamFloatValue"] = createExportWrapper("FPDFPageObjMark_GetParamFloatValue", 3);
6906    Module["_FPDFPageObjMark_GetParamStringValue"] = createExportWrapper("FPDFPageObjMark_GetParamStringValue", 5);
6907    Module["_FPDFPageObjMark_GetParamBlobValue"] = createExportWrapper("FPDFPageObjMark_GetParamBlobValue", 5);
6908    Module["_FPDFPageObj_HasTransparency"] = createExportWrapper("FPDFPageObj_HasTransparency", 1);
6909    Module["_FPDFPageObjMark_SetIntParam"] = createExportWrapper("FPDFPageObjMark_SetIntParam", 5);
6910    Module["_FPDFPageObjMark_SetFloatParam"] = createExportWrapper("FPDFPageObjMark_SetFloatParam", 5);
6911    Module["_FPDFPageObjMark_SetStringParam"] = createExportWrapper("FPDFPageObjMark_SetStringParam", 5);
6912    Module["_FPDFPageObjMark_SetBlobParam"] = createExportWrapper("FPDFPageObjMark_SetBlobParam", 6);
6913    Module["_FPDFPageObjMark_RemoveParam"] = createExportWrapper("FPDFPageObjMark_RemoveParam", 3);
6914    Module["_FPDFPageObj_GetType"] = createExportWrapper(
6915      "FPDFPageObj_GetType",
6916      1
6917    );
6918    Module["_FPDFPageObj_GetIsActive"] = createExportWrapper(
6919      "FPDFPageObj_GetIsActive",
6920      2
6921    );
6922    Module["_FPDFPageObj_SetIsActive"] = createExportWrapper(
6923      "FPDFPageObj_SetIsActive",
6924      2
6925    );
6926    Module["_FPDFPage_GenerateContent"] = createExportWrapper(
6927      "FPDFPage_GenerateContent",
6928      1
6929    );
6930    Module["_FPDFPageObj_Transform"] = createExportWrapper(
6931      "FPDFPageObj_Transform",
6932      7
6933    );
6934    Module["_FPDFPageObj_TransformF"] = createExportWrapper(
6935      "FPDFPageObj_TransformF",
6936      2
6937    );
6938    Module["_FPDFPageObj_GetMatrix"] = createExportWrapper(
6939      "FPDFPageObj_GetMatrix",
6940      2
6941    );
6942    Module["_FPDFPageObj_SetMatrix"] = createExportWrapper(
6943      "FPDFPageObj_SetMatrix",
6944      2
6945    );
6946    Module["_FPDFPageObj_SetBlendMode"] = createExportWrapper(
6947      "FPDFPageObj_SetBlendMode",
6948      2
6949    );
6950    Module["_FPDFPage_TransformAnnots"] = createExportWrapper(
6951      "FPDFPage_TransformAnnots",
6952      7
6953    );
6954    Module["_FPDFPage_SetRotation"] = createExportWrapper(
6955      "FPDFPage_SetRotation",
6956      2
6957    );
6958    Module["_FPDFPageObj_SetFillColor"] = createExportWrapper(
6959      "FPDFPageObj_SetFillColor",
6960      5
6961    );
6962    Module["_FPDFPageObj_GetFillColor"] = createExportWrapper(
6963      "FPDFPageObj_GetFillColor",
6964      5
6965    );
6966    Module["_FPDFPageObj_GetBounds"] = createExportWrapper(
6967      "FPDFPageObj_GetBounds",
6968      5
6969    );
6970    Module["_FPDFPageObj_GetRotatedBounds"] = createExportWrapper("FPDFPageObj_GetRotatedBounds", 2);
6971    Module["_FPDFPageObj_SetStrokeColor"] = createExportWrapper(
6972      "FPDFPageObj_SetStrokeColor",
6973      5
6974    );
6975    Module["_FPDFPageObj_GetStrokeColor"] = createExportWrapper(
6976      "FPDFPageObj_GetStrokeColor",
6977      5
6978    );
6979    Module["_FPDFPageObj_SetStrokeWidth"] = createExportWrapper(
6980      "FPDFPageObj_SetStrokeWidth",
6981      2
6982    );
6983    Module["_FPDFPageObj_GetStrokeWidth"] = createExportWrapper(
6984      "FPDFPageObj_GetStrokeWidth",
6985      2
6986    );
6987    Module["_FPDFPageObj_GetLineJoin"] = createExportWrapper(
6988      "FPDFPageObj_GetLineJoin",
6989      1
6990    );
6991    Module["_FPDFPageObj_SetLineJoin"] = createExportWrapper(
6992      "FPDFPageObj_SetLineJoin",
6993      2
6994    );
6995    Module["_FPDFPageObj_GetLineCap"] = createExportWrapper(
6996      "FPDFPageObj_GetLineCap",
6997      1
6998    );
6999    Module["_FPDFPageObj_SetLineCap"] = createExportWrapper(
7000      "FPDFPageObj_SetLineCap",
7001      2
7002    );
7003    Module["_FPDFPageObj_GetDashPhase"] = createExportWrapper(
7004      "FPDFPageObj_GetDashPhase",
7005      2
7006    );
7007    Module["_FPDFPageObj_SetDashPhase"] = createExportWrapper(
7008      "FPDFPageObj_SetDashPhase",
7009      2
7010    );
7011    Module["_FPDFPageObj_GetDashCount"] = createExportWrapper(
7012      "FPDFPageObj_GetDashCount",
7013      1
7014    );
7015    Module["_FPDFPageObj_GetDashArray"] = createExportWrapper(
7016      "FPDFPageObj_GetDashArray",
7017      3
7018    );
7019    Module["_FPDFPageObj_SetDashArray"] = createExportWrapper(
7020      "FPDFPageObj_SetDashArray",
7021      4
7022    );
7023    Module["_FPDFFormObj_CountObjects"] = createExportWrapper(
7024      "FPDFFormObj_CountObjects",
7025      1
7026    );
7027    Module["_FPDFFormObj_GetObject"] = createExportWrapper(
7028      "FPDFFormObj_GetObject",
7029      2
7030    );
7031    Module["_FPDFFormObj_RemoveObject"] = createExportWrapper(
7032      "FPDFFormObj_RemoveObject",
7033      2
7034    );
7035    Module["_FPDFPageObj_CreateNewPath"] = createExportWrapper(
7036      "FPDFPageObj_CreateNewPath",
7037      2
7038    );
7039    Module["_FPDFPageObj_CreateNewRect"] = createExportWrapper(
7040      "FPDFPageObj_CreateNewRect",
7041      4
7042    );
7043    Module["_FPDFPath_CountSegments"] = createExportWrapper(
7044      "FPDFPath_CountSegments",
7045      1
7046    );
7047    Module["_FPDFPath_GetPathSegment"] = createExportWrapper(
7048      "FPDFPath_GetPathSegment",
7049      2
7050    );
7051    Module["_FPDFPath_MoveTo"] = createExportWrapper("FPDFPath_MoveTo", 3);
7052    Module["_FPDFPath_LineTo"] = createExportWrapper("FPDFPath_LineTo", 3);
7053    Module["_FPDFPath_BezierTo"] = createExportWrapper(
7054      "FPDFPath_BezierTo",
7055      7
7056    );
7057    Module["_FPDFPath_Close"] = createExportWrapper("FPDFPath_Close", 1);
7058    Module["_FPDFPath_SetDrawMode"] = createExportWrapper(
7059      "FPDFPath_SetDrawMode",
7060      3
7061    );
7062    Module["_FPDFPath_GetDrawMode"] = createExportWrapper(
7063      "FPDFPath_GetDrawMode",
7064      3
7065    );
7066    Module["_FPDFPathSegment_GetPoint"] = createExportWrapper(
7067      "FPDFPathSegment_GetPoint",
7068      3
7069    );
7070    Module["_FPDFPathSegment_GetType"] = createExportWrapper(
7071      "FPDFPathSegment_GetType",
7072      1
7073    );
7074    Module["_FPDFPathSegment_GetClose"] = createExportWrapper(
7075      "FPDFPathSegment_GetClose",
7076      1
7077    );
7078    Module["_FPDFPageObj_NewTextObj"] = createExportWrapper(
7079      "FPDFPageObj_NewTextObj",
7080      3
7081    );
7082    Module["_FPDFText_SetText"] = createExportWrapper(
7083      "FPDFText_SetText",
7084      2
7085    );
7086    Module["_FPDFText_SetCharcodes"] = createExportWrapper(
7087      "FPDFText_SetCharcodes",
7088      3
7089    );
7090    Module["_FPDFText_LoadFont"] = createExportWrapper(
7091      "FPDFText_LoadFont",
7092      5
7093    );
7094    Module["_FPDFText_LoadStandardFont"] = createExportWrapper(
7095      "FPDFText_LoadStandardFont",
7096      2
7097    );
7098    Module["_FPDFText_LoadCidType2Font"] = createExportWrapper(
7099      "FPDFText_LoadCidType2Font",
7100      6
7101    );
7102    Module["_FPDFTextObj_GetFontSize"] = createExportWrapper(
7103      "FPDFTextObj_GetFontSize",
7104      2
7105    );
7106    Module["_FPDFTextObj_GetText"] = createExportWrapper(
7107      "FPDFTextObj_GetText",
7108      4
7109    );
7110    Module["_FPDFTextObj_GetRenderedBitmap"] = createExportWrapper("FPDFTextObj_GetRenderedBitmap", 4);
7111    Module["_FPDFFont_Close"] = createExportWrapper("FPDFFont_Close", 1);
7112    Module["_FPDFPageObj_CreateTextObj"] = createExportWrapper(
7113      "FPDFPageObj_CreateTextObj",
7114      3
7115    );
7116    Module["_FPDFTextObj_GetTextRenderMode"] = createExportWrapper("FPDFTextObj_GetTextRenderMode", 1);
7117    Module["_FPDFTextObj_SetTextRenderMode"] = createExportWrapper("FPDFTextObj_SetTextRenderMode", 2);
7118    Module["_FPDFTextObj_GetFont"] = createExportWrapper(
7119      "FPDFTextObj_GetFont",
7120      1
7121    );
7122    Module["_FPDFFont_GetBaseFontName"] = createExportWrapper(
7123      "FPDFFont_GetBaseFontName",
7124      3
7125    );
7126    Module["_FPDFFont_GetFamilyName"] = createExportWrapper(
7127      "FPDFFont_GetFamilyName",
7128      3
7129    );
7130    Module["_FPDFFont_GetFontData"] = createExportWrapper(
7131      "FPDFFont_GetFontData",
7132      4
7133    );
7134    Module["_FPDFFont_GetIsEmbedded"] = createExportWrapper(
7135      "FPDFFont_GetIsEmbedded",
7136      1
7137    );
7138    Module["_FPDFFont_GetFlags"] = createExportWrapper(
7139      "FPDFFont_GetFlags",
7140      1
7141    );
7142    Module["_FPDFFont_GetWeight"] = createExportWrapper(
7143      "FPDFFont_GetWeight",
7144      1
7145    );
7146    Module["_FPDFFont_GetItalicAngle"] = createExportWrapper(
7147      "FPDFFont_GetItalicAngle",
7148      2
7149    );
7150    Module["_FPDFFont_GetAscent"] = createExportWrapper(
7151      "FPDFFont_GetAscent",
7152      3
7153    );
7154    Module["_FPDFFont_GetDescent"] = createExportWrapper(
7155      "FPDFFont_GetDescent",
7156      3
7157    );
7158    Module["_FPDFFont_GetGlyphWidth"] = createExportWrapper(
7159      "FPDFFont_GetGlyphWidth",
7160      4
7161    );
7162    Module["_FPDFFont_GetGlyphPath"] = createExportWrapper(
7163      "FPDFFont_GetGlyphPath",
7164      3
7165    );
7166    Module["_FPDFGlyphPath_CountGlyphSegments"] = createExportWrapper("FPDFGlyphPath_CountGlyphSegments", 1);
7167    Module["_FPDFGlyphPath_GetGlyphPathSegment"] = createExportWrapper("FPDFGlyphPath_GetGlyphPathSegment", 2);
7168    Module["_EPDFText_RedactInRect"] = createExportWrapper(
7169      "EPDFText_RedactInRect",
7170      4
7171    );
7172    Module["_EPDFText_RedactInQuads"] = createExportWrapper(
7173      "EPDFText_RedactInQuads",
7174      5
7175    );
7176    Module["_FPDFDoc_GetPageMode"] = createExportWrapper(
7177      "FPDFDoc_GetPageMode",
7178      1
7179    );
7180    Module["_FPDFPage_Flatten"] = createExportWrapper(
7181      "FPDFPage_Flatten",
7182      2
7183    );
7184    Module["_FPDFPage_HasFormFieldAtPoint"] = createExportWrapper("FPDFPage_HasFormFieldAtPoint", 4);
7185    Module["_FPDFPage_FormFieldZOrderAtPoint"] = createExportWrapper("FPDFPage_FormFieldZOrderAtPoint", 4);
7186    Module["_malloc"] = createExportWrapper("malloc", 1);
7187    Module["_free"] = createExportWrapper("free", 1);
7188    Module["_FORM_OnMouseMove"] = createExportWrapper(
7189      "FORM_OnMouseMove",
7190      5
7191    );
7192    Module["_FORM_OnMouseWheel"] = createExportWrapper(
7193      "FORM_OnMouseWheel",
7194      6
7195    );
7196    Module["_FORM_OnFocus"] = createExportWrapper("FORM_OnFocus", 5);
7197    Module["_FORM_OnLButtonDown"] = createExportWrapper(
7198      "FORM_OnLButtonDown",
7199      5
7200    );
7201    Module["_FORM_OnLButtonUp"] = createExportWrapper(
7202      "FORM_OnLButtonUp",
7203      5
7204    );
7205    Module["_FORM_OnLButtonDoubleClick"] = createExportWrapper(
7206      "FORM_OnLButtonDoubleClick",
7207      5
7208    );
7209    Module["_FORM_OnRButtonDown"] = createExportWrapper(
7210      "FORM_OnRButtonDown",
7211      5
7212    );
7213    Module["_FORM_OnRButtonUp"] = createExportWrapper(
7214      "FORM_OnRButtonUp",
7215      5
7216    );
7217    Module["_FORM_OnKeyDown"] = createExportWrapper("FORM_OnKeyDown", 4);
7218    Module["_FORM_OnKeyUp"] = createExportWrapper("FORM_OnKeyUp", 4);
7219    Module["_FORM_OnChar"] = createExportWrapper("FORM_OnChar", 4);
7220    Module["_FORM_GetFocusedText"] = createExportWrapper(
7221      "FORM_GetFocusedText",
7222      4
7223    );
7224    Module["_FORM_GetSelectedText"] = createExportWrapper(
7225      "FORM_GetSelectedText",
7226      4
7227    );
7228    Module["_FORM_ReplaceAndKeepSelection"] = createExportWrapper("FORM_ReplaceAndKeepSelection", 3);
7229    Module["_FORM_ReplaceSelection"] = createExportWrapper(
7230      "FORM_ReplaceSelection",
7231      3
7232    );
7233    Module["_FORM_SelectAllText"] = createExportWrapper(
7234      "FORM_SelectAllText",
7235      2
7236    );
7237    Module["_FORM_CanUndo"] = createExportWrapper("FORM_CanUndo", 2);
7238    Module["_FORM_CanRedo"] = createExportWrapper("FORM_CanRedo", 2);
7239    Module["_FORM_Undo"] = createExportWrapper("FORM_Undo", 2);
7240    Module["_FORM_Redo"] = createExportWrapper("FORM_Redo", 2);
7241    Module["_FORM_ForceToKillFocus"] = createExportWrapper(
7242      "FORM_ForceToKillFocus",
7243      1
7244    );
7245    Module["_FORM_GetFocusedAnnot"] = createExportWrapper(
7246      "FORM_GetFocusedAnnot",
7247      3
7248    );
7249    Module["_FORM_SetFocusedAnnot"] = createExportWrapper(
7250      "FORM_SetFocusedAnnot",
7251      2
7252    );
7253    Module["_FPDF_FFLDraw"] = createExportWrapper("FPDF_FFLDraw", 9);
7254    Module["_FPDF_SetFormFieldHighlightColor"] = createExportWrapper("FPDF_SetFormFieldHighlightColor", 3);
7255    Module["_FPDF_SetFormFieldHighlightAlpha"] = createExportWrapper("FPDF_SetFormFieldHighlightAlpha", 2);
7256    Module["_FPDF_RemoveFormFieldHighlight"] = createExportWrapper("FPDF_RemoveFormFieldHighlight", 1);
7257    Module["_FORM_OnAfterLoadPage"] = createExportWrapper(
7258      "FORM_OnAfterLoadPage",
7259      2
7260    );
7261    Module["_FORM_OnBeforeClosePage"] = createExportWrapper(
7262      "FORM_OnBeforeClosePage",
7263      2
7264    );
7265    Module["_FORM_DoDocumentJSAction"] = createExportWrapper(
7266      "FORM_DoDocumentJSAction",
7267      1
7268    );
7269    Module["_FORM_DoDocumentOpenAction"] = createExportWrapper(
7270      "FORM_DoDocumentOpenAction",
7271      1
7272    );
7273    Module["_FORM_DoDocumentAAction"] = createExportWrapper(
7274      "FORM_DoDocumentAAction",
7275      2
7276    );
7277    Module["_FORM_DoPageAAction"] = createExportWrapper(
7278      "FORM_DoPageAAction",
7279      3
7280    );
7281    Module["_FORM_SetIndexSelected"] = createExportWrapper(
7282      "FORM_SetIndexSelected",
7283      4
7284    );
7285    Module["_FORM_IsIndexSelected"] = createExportWrapper(
7286      "FORM_IsIndexSelected",
7287      3
7288    );
7289    Module["_FPDFDoc_GetJavaScriptActionCount"] = createExportWrapper("FPDFDoc_GetJavaScriptActionCount", 1);
7290    Module["_FPDFDoc_GetJavaScriptAction"] = createExportWrapper("FPDFDoc_GetJavaScriptAction", 2);
7291    Module["_FPDFDoc_CloseJavaScriptAction"] = createExportWrapper("FPDFDoc_CloseJavaScriptAction", 1);
7292    Module["_FPDFJavaScriptAction_GetName"] = createExportWrapper("FPDFJavaScriptAction_GetName", 3);
7293    Module["_FPDFJavaScriptAction_GetScript"] = createExportWrapper("FPDFJavaScriptAction_GetScript", 3);
7294    Module["_FPDF_ImportPagesByIndex"] = createExportWrapper(
7295      "FPDF_ImportPagesByIndex",
7296      5
7297    );
7298    Module["_FPDF_ImportPages"] = createExportWrapper(
7299      "FPDF_ImportPages",
7300      4
7301    );
7302    Module["_FPDF_ImportNPagesToOne"] = createExportWrapper(
7303      "FPDF_ImportNPagesToOne",
7304      5
7305    );
7306    Module["_FPDF_NewXObjectFromPage"] = createExportWrapper(
7307      "FPDF_NewXObjectFromPage",
7308      3
7309    );
7310    Module["_FPDF_CloseXObject"] = createExportWrapper(
7311      "FPDF_CloseXObject",
7312      1
7313    );
7314    Module["_FPDF_NewFormObjectFromXObject"] = createExportWrapper("FPDF_NewFormObjectFromXObject", 1);
7315    Module["_FPDF_CopyViewerPreferences"] = createExportWrapper(
7316      "FPDF_CopyViewerPreferences",
7317      2
7318    );
7319    Module["_FPDF_RenderPageBitmapWithColorScheme_Start"] = createExportWrapper("FPDF_RenderPageBitmapWithColorScheme_Start", 10);
7320    Module["_FPDF_RenderPageBitmap_Start"] = createExportWrapper("FPDF_RenderPageBitmap_Start", 9);
7321    Module["_FPDF_RenderPage_Continue"] = createExportWrapper(
7322      "FPDF_RenderPage_Continue",
7323      2
7324    );
7325    Module["_FPDF_RenderPage_Close"] = createExportWrapper(
7326      "FPDF_RenderPage_Close",
7327      1
7328    );
7329    Module["_FPDF_SaveWithVersion"] = createExportWrapper(
7330      "FPDF_SaveWithVersion",
7331      4
7332    );
7333    Module["_FPDFText_GetCharIndexFromTextIndex"] = createExportWrapper("FPDFText_GetCharIndexFromTextIndex", 2);
7334    Module["_FPDFText_GetTextIndexFromCharIndex"] = createExportWrapper("FPDFText_GetTextIndexFromCharIndex", 2);
7335    Module["_FPDF_GetSignatureCount"] = createExportWrapper(
7336      "FPDF_GetSignatureCount",
7337      1
7338    );
7339    Module["_FPDF_GetSignatureObject"] = createExportWrapper(
7340      "FPDF_GetSignatureObject",
7341      2
7342    );
7343    Module["_FPDFSignatureObj_GetContents"] = createExportWrapper("FPDFSignatureObj_GetContents", 3);
7344    Module["_FPDFSignatureObj_GetByteRange"] = createExportWrapper("FPDFSignatureObj_GetByteRange", 3);
7345    Module["_FPDFSignatureObj_GetSubFilter"] = createExportWrapper("FPDFSignatureObj_GetSubFilter", 3);
7346    Module["_FPDFSignatureObj_GetReason"] = createExportWrapper(
7347      "FPDFSignatureObj_GetReason",
7348      3
7349    );
7350    Module["_FPDFSignatureObj_GetTime"] = createExportWrapper(
7351      "FPDFSignatureObj_GetTime",
7352      3
7353    );
7354    Module["_FPDFSignatureObj_GetDocMDPPermission"] = createExportWrapper("FPDFSignatureObj_GetDocMDPPermission", 1);
7355    Module["_FPDF_StructTree_GetForPage"] = createExportWrapper(
7356      "FPDF_StructTree_GetForPage",
7357      1
7358    );
7359    Module["_FPDF_StructTree_Close"] = createExportWrapper(
7360      "FPDF_StructTree_Close",
7361      1
7362    );
7363    Module["_FPDF_StructTree_CountChildren"] = createExportWrapper("FPDF_StructTree_CountChildren", 1);
7364    Module["_FPDF_StructTree_GetChildAtIndex"] = createExportWrapper("FPDF_StructTree_GetChildAtIndex", 2);
7365    Module["_FPDF_StructElement_GetAltText"] = createExportWrapper("FPDF_StructElement_GetAltText", 3);
7366    Module["_FPDF_StructElement_GetActualText"] = createExportWrapper("FPDF_StructElement_GetActualText", 3);
7367    Module["_FPDF_StructElement_GetID"] = createExportWrapper(
7368      "FPDF_StructElement_GetID",
7369      3
7370    );
7371    Module["_FPDF_StructElement_GetLang"] = createExportWrapper(
7372      "FPDF_StructElement_GetLang",
7373      3
7374    );
7375    Module["_FPDF_StructElement_GetAttributeCount"] = createExportWrapper("FPDF_StructElement_GetAttributeCount", 1);
7376    Module["_FPDF_StructElement_GetAttributeAtIndex"] = createExportWrapper("FPDF_StructElement_GetAttributeAtIndex", 2);
7377    Module["_FPDF_StructElement_GetStringAttribute"] = createExportWrapper("FPDF_StructElement_GetStringAttribute", 4);
7378    Module["_FPDF_StructElement_GetMarkedContentID"] = createExportWrapper("FPDF_StructElement_GetMarkedContentID", 1);
7379    Module["_FPDF_StructElement_GetType"] = createExportWrapper(
7380      "FPDF_StructElement_GetType",
7381      3
7382    );
7383    Module["_FPDF_StructElement_GetObjType"] = createExportWrapper("FPDF_StructElement_GetObjType", 3);
7384    Module["_FPDF_StructElement_GetTitle"] = createExportWrapper("FPDF_StructElement_GetTitle", 3);
7385    Module["_FPDF_StructElement_CountChildren"] = createExportWrapper("FPDF_StructElement_CountChildren", 1);
7386    Module["_FPDF_StructElement_GetChildAtIndex"] = createExportWrapper("FPDF_StructElement_GetChildAtIndex", 2);
7387    Module["_FPDF_StructElement_GetChildMarkedContentID"] = createExportWrapper("FPDF_StructElement_GetChildMarkedContentID", 2);
7388    Module["_FPDF_StructElement_GetParent"] = createExportWrapper("FPDF_StructElement_GetParent", 1);
7389    Module["_FPDF_StructElement_Attr_GetCount"] = createExportWrapper("FPDF_StructElement_Attr_GetCount", 1);
7390    Module["_FPDF_StructElement_Attr_GetName"] = createExportWrapper("FPDF_StructElement_Attr_GetName", 5);
7391    Module["_FPDF_StructElement_Attr_GetValue"] = createExportWrapper("FPDF_StructElement_Attr_GetValue", 2);
7392    Module["_FPDF_StructElement_Attr_GetType"] = createExportWrapper("FPDF_StructElement_Attr_GetType", 1);
7393    Module["_FPDF_StructElement_Attr_GetBooleanValue"] = createExportWrapper("FPDF_StructElement_Attr_GetBooleanValue", 2);
7394    Module["_FPDF_StructElement_Attr_GetNumberValue"] = createExportWrapper("FPDF_StructElement_Attr_GetNumberValue", 2);
7395    Module["_FPDF_StructElement_Attr_GetStringValue"] = createExportWrapper("FPDF_StructElement_Attr_GetStringValue", 4);
7396    Module["_FPDF_StructElement_Attr_GetBlobValue"] = createExportWrapper("FPDF_StructElement_Attr_GetBlobValue", 4);
7397    Module["_FPDF_StructElement_Attr_CountChildren"] = createExportWrapper("FPDF_StructElement_Attr_CountChildren", 1);
7398    Module["_FPDF_StructElement_Attr_GetChildAtIndex"] = createExportWrapper("FPDF_StructElement_Attr_GetChildAtIndex", 2);
7399    Module["_FPDF_StructElement_GetMarkedContentIdCount"] = createExportWrapper("FPDF_StructElement_GetMarkedContentIdCount", 1);
7400    Module["_FPDF_StructElement_GetMarkedContentIdAtIndex"] = createExportWrapper("FPDF_StructElement_GetMarkedContentIdAtIndex", 2);
7401    Module["_FPDF_AddInstalledFont"] = createExportWrapper(
7402      "FPDF_AddInstalledFont",
7403      3
7404    );
7405    Module["_FPDF_SetSystemFontInfo"] = createExportWrapper(
7406      "FPDF_SetSystemFontInfo",
7407      1
7408    );
7409    Module["_FPDF_GetDefaultTTFMap"] = createExportWrapper(
7410      "FPDF_GetDefaultTTFMap",
7411      0
7412    );
7413    Module["_FPDF_GetDefaultTTFMapCount"] = createExportWrapper(
7414      "FPDF_GetDefaultTTFMapCount",
7415      0
7416    );
7417    Module["_FPDF_GetDefaultTTFMapEntry"] = createExportWrapper(
7418      "FPDF_GetDefaultTTFMapEntry",
7419      1
7420    );
7421    Module["_FPDF_GetDefaultSystemFontInfo"] = createExportWrapper("FPDF_GetDefaultSystemFontInfo", 0);
7422    Module["_FPDF_FreeDefaultSystemFontInfo"] = createExportWrapper("FPDF_FreeDefaultSystemFontInfo", 1);
7423    Module["_FPDFText_LoadPage"] = createExportWrapper(
7424      "FPDFText_LoadPage",
7425      1
7426    );
7427    Module["_FPDFText_ClosePage"] = createExportWrapper(
7428      "FPDFText_ClosePage",
7429      1
7430    );
7431    Module["_FPDFText_CountChars"] = createExportWrapper(
7432      "FPDFText_CountChars",
7433      1
7434    );
7435    Module["_FPDFText_GetUnicode"] = createExportWrapper(
7436      "FPDFText_GetUnicode",
7437      2
7438    );
7439    Module["_FPDFText_GetTextObject"] = createExportWrapper(
7440      "FPDFText_GetTextObject",
7441      2
7442    );
7443    Module["_FPDFText_IsGenerated"] = createExportWrapper(
7444      "FPDFText_IsGenerated",
7445      2
7446    );
7447    Module["_FPDFText_IsHyphen"] = createExportWrapper(
7448      "FPDFText_IsHyphen",
7449      2
7450    );
7451    Module["_FPDFText_HasUnicodeMapError"] = createExportWrapper("FPDFText_HasUnicodeMapError", 2);
7452    Module["_FPDFText_GetFontSize"] = createExportWrapper(
7453      "FPDFText_GetFontSize",
7454      2
7455    );
7456    Module["_FPDFText_GetFontInfo"] = createExportWrapper(
7457      "FPDFText_GetFontInfo",
7458      5
7459    );
7460    Module["_FPDFText_GetFontWeight"] = createExportWrapper(
7461      "FPDFText_GetFontWeight",
7462      2
7463    );
7464    Module["_FPDFText_GetFillColor"] = createExportWrapper(
7465      "FPDFText_GetFillColor",
7466      6
7467    );
7468    Module["_FPDFText_GetStrokeColor"] = createExportWrapper(
7469      "FPDFText_GetStrokeColor",
7470      6
7471    );
7472    Module["_FPDFText_GetCharAngle"] = createExportWrapper(
7473      "FPDFText_GetCharAngle",
7474      2
7475    );
7476    Module["_FPDFText_GetCharBox"] = createExportWrapper(
7477      "FPDFText_GetCharBox",
7478      6
7479    );
7480    Module["_FPDFText_GetLooseCharBox"] = createExportWrapper(
7481      "FPDFText_GetLooseCharBox",
7482      3
7483    );
7484    Module["_FPDFText_GetMatrix"] = createExportWrapper(
7485      "FPDFText_GetMatrix",
7486      3
7487    );
7488    Module["_FPDFText_GetCharOrigin"] = createExportWrapper(
7489      "FPDFText_GetCharOrigin",
7490      4
7491    );
7492    Module["_FPDFText_GetCharIndexAtPos"] = createExportWrapper(
7493      "FPDFText_GetCharIndexAtPos",
7494      5
7495    );
7496    Module["_FPDFText_GetText"] = createExportWrapper(
7497      "FPDFText_GetText",
7498      4
7499    );
7500    Module["_FPDFText_CountRects"] = createExportWrapper(
7501      "FPDFText_CountRects",
7502      3
7503    );
7504    Module["_FPDFText_GetRect"] = createExportWrapper(
7505      "FPDFText_GetRect",
7506      6
7507    );
7508    Module["_FPDFText_GetBoundedText"] = createExportWrapper(
7509      "FPDFText_GetBoundedText",
7510      7
7511    );
7512    Module["_FPDFText_FindStart"] = createExportWrapper(
7513      "FPDFText_FindStart",
7514      4
7515    );
7516    Module["_FPDFText_FindNext"] = createExportWrapper(
7517      "FPDFText_FindNext",
7518      1
7519    );
7520    Module["_FPDFText_FindPrev"] = createExportWrapper(
7521      "FPDFText_FindPrev",
7522      1
7523    );
7524    Module["_FPDFText_GetSchResultIndex"] = createExportWrapper(
7525      "FPDFText_GetSchResultIndex",
7526      1
7527    );
7528    Module["_FPDFText_GetSchCount"] = createExportWrapper(
7529      "FPDFText_GetSchCount",
7530      1
7531    );
7532    Module["_FPDFText_FindClose"] = createExportWrapper(
7533      "FPDFText_FindClose",
7534      1
7535    );
7536    Module["_FPDFLink_LoadWebLinks"] = createExportWrapper(
7537      "FPDFLink_LoadWebLinks",
7538      1
7539    );
7540    Module["_FPDFLink_CountWebLinks"] = createExportWrapper(
7541      "FPDFLink_CountWebLinks",
7542      1
7543    );
7544    Module["_FPDFLink_GetURL"] = createExportWrapper("FPDFLink_GetURL", 4);
7545    Module["_FPDFLink_CountRects"] = createExportWrapper(
7546      "FPDFLink_CountRects",
7547      2
7548    );
7549    Module["_FPDFLink_GetRect"] = createExportWrapper(
7550      "FPDFLink_GetRect",
7551      7
7552    );
7553    Module["_FPDFLink_GetTextRange"] = createExportWrapper(
7554      "FPDFLink_GetTextRange",
7555      4
7556    );
7557    Module["_FPDFLink_CloseWebLinks"] = createExportWrapper(
7558      "FPDFLink_CloseWebLinks",
7559      1
7560    );
7561    Module["_FPDFPage_GetDecodedThumbnailData"] = createExportWrapper("FPDFPage_GetDecodedThumbnailData", 3);
7562    Module["_FPDFPage_GetRawThumbnailData"] = createExportWrapper("FPDFPage_GetRawThumbnailData", 3);
7563    Module["_FPDFPage_GetThumbnailAsBitmap"] = createExportWrapper("FPDFPage_GetThumbnailAsBitmap", 1);
7564    Module["_FPDFPage_SetMediaBox"] = createExportWrapper(
7565      "FPDFPage_SetMediaBox",
7566      5
7567    );
7568    Module["_FPDFPage_SetCropBox"] = createExportWrapper(
7569      "FPDFPage_SetCropBox",
7570      5
7571    );
7572    Module["_FPDFPage_SetBleedBox"] = createExportWrapper(
7573      "FPDFPage_SetBleedBox",
7574      5
7575    );
7576    Module["_FPDFPage_SetTrimBox"] = createExportWrapper(
7577      "FPDFPage_SetTrimBox",
7578      5
7579    );
7580    Module["_FPDFPage_SetArtBox"] = createExportWrapper(
7581      "FPDFPage_SetArtBox",
7582      5
7583    );
7584    Module["_FPDFPage_GetMediaBox"] = createExportWrapper(
7585      "FPDFPage_GetMediaBox",
7586      5
7587    );
7588    Module["_FPDFPage_GetCropBox"] = createExportWrapper(
7589      "FPDFPage_GetCropBox",
7590      5
7591    );
7592    Module["_FPDFPage_GetBleedBox"] = createExportWrapper(
7593      "FPDFPage_GetBleedBox",
7594      5
7595    );
7596    Module["_FPDFPage_GetTrimBox"] = createExportWrapper(
7597      "FPDFPage_GetTrimBox",
7598      5
7599    );
7600    Module["_FPDFPage_GetArtBox"] = createExportWrapper(
7601      "FPDFPage_GetArtBox",
7602      5
7603    );
7604    Module["_FPDFPage_TransFormWithClip"] = createExportWrapper(
7605      "FPDFPage_TransFormWithClip",
7606      3
7607    );
7608    Module["_FPDFPageObj_TransformClipPath"] = createExportWrapper("FPDFPageObj_TransformClipPath", 7);
7609    Module["_FPDFPageObj_GetClipPath"] = createExportWrapper(
7610      "FPDFPageObj_GetClipPath",
7611      1
7612    );
7613    Module["_FPDFClipPath_CountPaths"] = createExportWrapper(
7614      "FPDFClipPath_CountPaths",
7615      1
7616    );
7617    Module["_FPDFClipPath_CountPathSegments"] = createExportWrapper("FPDFClipPath_CountPathSegments", 2);
7618    Module["_FPDFClipPath_GetPathSegment"] = createExportWrapper("FPDFClipPath_GetPathSegment", 3);
7619    Module["_FPDF_CreateClipPath"] = createExportWrapper(
7620      "FPDF_CreateClipPath",
7621      4
7622    );
7623    Module["_FPDF_DestroyClipPath"] = createExportWrapper(
7624      "FPDF_DestroyClipPath",
7625      1
7626    );
7627    Module["_FPDFPage_InsertClipPath"] = createExportWrapper(
7628      "FPDFPage_InsertClipPath",
7629      2
7630    );
7631    Module["_FPDF_InitLibrary"] = createExportWrapper(
7632      "FPDF_InitLibrary",
7633      0
7634    );
7635    Module["_FPDF_DestroyLibrary"] = createExportWrapper(
7636      "FPDF_DestroyLibrary",
7637      0
7638    );
vendor: 15,565 bytes, lines 7639-8126
7639    Module["_FPDF_SetSandBoxPolicy"] = createExportWrapper(
7640      "FPDF_SetSandBoxPolicy",
7641      2
7642    );
7643    Module["_FPDF_LoadDocument"] = createExportWrapper(
7644      "FPDF_LoadDocument",
7645      2
7646    );
7647    Module["_FPDF_GetFormType"] = createExportWrapper(
7648      "FPDF_GetFormType",
7649      1
7650    );
7651    Module["_FPDF_LoadXFA"] = createExportWrapper("FPDF_LoadXFA", 1);
7652    Module["_FPDF_LoadMemDocument"] = createExportWrapper(
7653      "FPDF_LoadMemDocument",
7654      3
7655    );
7656    Module["_FPDF_LoadMemDocument64"] = createExportWrapper(
7657      "FPDF_LoadMemDocument64",
7658      3
7659    );
7660    Module["_FPDF_LoadCustomDocument"] = createExportWrapper(
7661      "FPDF_LoadCustomDocument",
7662      2
7663    );
7664    Module["_FPDF_GetFileVersion"] = createExportWrapper(
7665      "FPDF_GetFileVersion",
7666      2
7667    );
7668    Module["_FPDF_DocumentHasValidCrossReferenceTable"] = createExportWrapper("FPDF_DocumentHasValidCrossReferenceTable", 1);
7669    Module["_FPDF_GetDocPermissions"] = createExportWrapper(
7670      "FPDF_GetDocPermissions",
7671      1
7672    );
7673    Module["_FPDF_GetDocUserPermissions"] = createExportWrapper(
7674      "FPDF_GetDocUserPermissions",
7675      1
7676    );
7677    Module["_FPDF_GetSecurityHandlerRevision"] = createExportWrapper("FPDF_GetSecurityHandlerRevision", 1);
7678    Module["_EPDF_SetEncryption"] = createExportWrapper(
7679      "EPDF_SetEncryption",
7680      4
7681    );
7682    Module["_EPDF_RemoveEncryption"] = createExportWrapper(
7683      "EPDF_RemoveEncryption",
7684      1
7685    );
7686    Module["_EPDF_UnlockOwnerPermissions"] = createExportWrapper("EPDF_UnlockOwnerPermissions", 2);
7687    Module["_EPDF_IsEncrypted"] = createExportWrapper(
7688      "EPDF_IsEncrypted",
7689      1
7690    );
7691    Module["_EPDF_IsOwnerUnlocked"] = createExportWrapper(
7692      "EPDF_IsOwnerUnlocked",
7693      1
7694    );
7695    Module["_FPDF_GetPageCount"] = createExportWrapper(
7696      "FPDF_GetPageCount",
7697      1
7698    );
7699    Module["_FPDF_LoadPage"] = createExportWrapper("FPDF_LoadPage", 2);
7700    Module["_FPDF_GetPageWidthF"] = createExportWrapper(
7701      "FPDF_GetPageWidthF",
7702      1
7703    );
7704    Module["_FPDF_GetPageWidth"] = createExportWrapper(
7705      "FPDF_GetPageWidth",
7706      1
7707    );
7708    Module["_FPDF_GetPageHeightF"] = createExportWrapper(
7709      "FPDF_GetPageHeightF",
7710      1
7711    );
7712    Module["_FPDF_GetPageHeight"] = createExportWrapper(
7713      "FPDF_GetPageHeight",
7714      1
7715    );
7716    Module["_FPDF_GetPageBoundingBox"] = createExportWrapper(
7717      "FPDF_GetPageBoundingBox",
7718      2
7719    );
7720    Module["_FPDF_RenderPageBitmap"] = createExportWrapper(
7721      "FPDF_RenderPageBitmap",
7722      8
7723    );
7724    Module["_FPDF_RenderPageBitmapWithMatrix"] = createExportWrapper("FPDF_RenderPageBitmapWithMatrix", 5);
7725    Module["_EPDF_RenderAnnotBitmap"] = createExportWrapper(
7726      "EPDF_RenderAnnotBitmap",
7727      6
7728    );
7729    Module["_EPDF_RenderAnnotBitmapUnrotated"] = createExportWrapper("EPDF_RenderAnnotBitmapUnrotated", 6);
7730    Module["_FPDF_ClosePage"] = createExportWrapper("FPDF_ClosePage", 1);
7731    Module["_FPDF_CloseDocument"] = createExportWrapper(
7732      "FPDF_CloseDocument",
7733      1
7734    );
7735    Module["_FPDF_GetLastError"] = createExportWrapper(
7736      "FPDF_GetLastError",
7737      0
7738    );
7739    Module["_FPDF_DeviceToPage"] = createExportWrapper(
7740      "FPDF_DeviceToPage",
7741      10
7742    );
7743    Module["_FPDF_PageToDevice"] = createExportWrapper(
7744      "FPDF_PageToDevice",
7745      10
7746    );
7747    Module["_FPDFBitmap_Create"] = createExportWrapper(
7748      "FPDFBitmap_Create",
7749      3
7750    );
7751    Module["_FPDFBitmap_CreateEx"] = createExportWrapper(
7752      "FPDFBitmap_CreateEx",
7753      5
7754    );
7755    Module["_FPDFBitmap_GetFormat"] = createExportWrapper(
7756      "FPDFBitmap_GetFormat",
7757      1
7758    );
7759    Module["_FPDFBitmap_FillRect"] = createExportWrapper(
7760      "FPDFBitmap_FillRect",
7761      6
7762    );
7763    Module["_FPDFBitmap_GetBuffer"] = createExportWrapper(
7764      "FPDFBitmap_GetBuffer",
7765      1
7766    );
7767    Module["_FPDFBitmap_GetWidth"] = createExportWrapper(
7768      "FPDFBitmap_GetWidth",
7769      1
7770    );
7771    Module["_FPDFBitmap_GetHeight"] = createExportWrapper(
7772      "FPDFBitmap_GetHeight",
7773      1
7774    );
7775    Module["_FPDFBitmap_GetStride"] = createExportWrapper(
7776      "FPDFBitmap_GetStride",
7777      1
7778    );
7779    Module["_FPDFBitmap_Destroy"] = createExportWrapper(
7780      "FPDFBitmap_Destroy",
7781      1
7782    );
7783    Module["_FPDF_GetPageSizeByIndexF"] = createExportWrapper(
7784      "FPDF_GetPageSizeByIndexF",
7785      3
7786    );
7787    Module["_EPDF_GetPageRotationByIndex"] = createExportWrapper("EPDF_GetPageRotationByIndex", 2);
7788    Module["_EPDF_GetPageSizeByIndexNormalized"] = createExportWrapper("EPDF_GetPageSizeByIndexNormalized", 3);
7789    Module["_EPDF_LoadPageNormalized"] = createExportWrapper(
7790      "EPDF_LoadPageNormalized",
7791      3
7792    );
7793    Module["_FPDF_GetPageSizeByIndex"] = createExportWrapper(
7794      "FPDF_GetPageSizeByIndex",
7795      4
7796    );
7797    Module["_FPDF_VIEWERREF_GetPrintScaling"] = createExportWrapper("FPDF_VIEWERREF_GetPrintScaling", 1);
7798    Module["_FPDF_VIEWERREF_GetNumCopies"] = createExportWrapper("FPDF_VIEWERREF_GetNumCopies", 1);
7799    Module["_FPDF_VIEWERREF_GetPrintPageRange"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRange", 1);
7800    Module["_FPDF_VIEWERREF_GetPrintPageRangeCount"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRangeCount", 1);
7801    Module["_FPDF_VIEWERREF_GetPrintPageRangeElement"] = createExportWrapper("FPDF_VIEWERREF_GetPrintPageRangeElement", 2);
7802    Module["_FPDF_VIEWERREF_GetDuplex"] = createExportWrapper(
7803      "FPDF_VIEWERREF_GetDuplex",
7804      1
7805    );
7806    Module["_FPDF_VIEWERREF_GetName"] = createExportWrapper(
7807      "FPDF_VIEWERREF_GetName",
7808      4
7809    );
7810    Module["_FPDF_CountNamedDests"] = createExportWrapper(
7811      "FPDF_CountNamedDests",
7812      1
7813    );
7814    Module["_FPDF_GetNamedDestByName"] = createExportWrapper(
7815      "FPDF_GetNamedDestByName",
7816      2
7817    );
7818    Module["_FPDF_GetNamedDest"] = createExportWrapper(
7819      "FPDF_GetNamedDest",
7820      4
7821    );
7822    Module["_FPDF_GetXFAPacketCount"] = createExportWrapper(
7823      "FPDF_GetXFAPacketCount",
7824      1
7825    );
7826    Module["_FPDF_GetXFAPacketName"] = createExportWrapper(
7827      "FPDF_GetXFAPacketName",
7828      4
7829    );
7830    Module["_FPDF_GetXFAPacketContent"] = createExportWrapper(
7831      "FPDF_GetXFAPacketContent",
7832      5
7833    );
7834    Module["_FPDF_GetTrailerEnds"] = createExportWrapper(
7835      "FPDF_GetTrailerEnds",
7836      3
7837    );
7838    var _strerror = createExportWrapper("strerror", 1);
7839    var _fflush = createExportWrapper("fflush", 1);
7840    var _emscripten_builtin_memalign = createExportWrapper("emscripten_builtin_memalign", 2);
7841    var _setThrew = createExportWrapper("setThrew", 2);
7842    var _emscripten_stack_init = () => (_emscripten_stack_init = wasmExports["emscripten_stack_init"])();
7843    var _emscripten_stack_get_end = () => (_emscripten_stack_get_end = wasmExports["emscripten_stack_get_end"])();
7844    var __emscripten_stack_restore = (a0) => (__emscripten_stack_restore = wasmExports["_emscripten_stack_restore"])(a0);
7845    var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"])(a0);
7846    var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"])();
7847    Module["dynCall_j"] = createExportWrapper("dynCall_j", 1);
7848    Module["dynCall_ji"] = createExportWrapper("dynCall_ji", 2);
7849    Module["dynCall_iiij"] = createExportWrapper("dynCall_iiij", 5);
7850    Module["dynCall_jji"] = createExportWrapper("dynCall_jji", 4);
7851    Module["dynCall_iji"] = createExportWrapper("dynCall_iji", 4);
7852    Module["dynCall_viijii"] = createExportWrapper("dynCall_viijii", 7);
7853    Module["dynCall_jij"] = createExportWrapper("dynCall_jij", 4);
7854    Module["dynCall_iij"] = createExportWrapper("dynCall_iij", 4);
7855    Module["dynCall_iiji"] = createExportWrapper("dynCall_iiji", 5);
7856    Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji", 5);
7857    Module["dynCall_iiiiij"] = createExportWrapper("dynCall_iiiiij", 7);
7858    Module["dynCall_iiiiijj"] = createExportWrapper("dynCall_iiiiijj", 9);
7859    Module["dynCall_iiiiiijj"] = createExportWrapper(
7860      "dynCall_iiiiiijj",
7861      10
7862    );
7863    Module["dynCall_viji"] = createExportWrapper("dynCall_viji", 5);
7864    function invoke_viii(index, a1, a2, a3) {
7865      var sp = stackSave();
7866      try {
7867        getWasmTableEntry(index)(a1, a2, a3);
7868      } catch (e) {
7869        stackRestore(sp);
7870        if (e !== e + 0) throw e;
7871        _setThrew(1, 0);
7872      }
7873    }
7874    function invoke_ii(index, a1) {
7875      var sp = stackSave();
7876      try {
7877        return getWasmTableEntry(index)(a1);
7878      } catch (e) {
7879        stackRestore(sp);
7880        if (e !== e + 0) throw e;
7881        _setThrew(1, 0);
7882      }
7883    }
7884    function invoke_iii(index, a1, a2) {
7885      var sp = stackSave();
7886      try {
7887        return getWasmTableEntry(index)(a1, a2);
7888      } catch (e) {
7889        stackRestore(sp);
7890        if (e !== e + 0) throw e;
7891        _setThrew(1, 0);
7892      }
7893    }
7894    function invoke_iiii(index, a1, a2, a3) {
7895      var sp = stackSave();
7896      try {
7897        return getWasmTableEntry(index)(a1, a2, a3);
7898      } catch (e) {
7899        stackRestore(sp);
7900        if (e !== e + 0) throw e;
7901        _setThrew(1, 0);
7902      }
7903    }
7904    function invoke_iiiii(index, a1, a2, a3, a4) {
7905      var sp = stackSave();
7906      try {
7907        return getWasmTableEntry(index)(a1, a2, a3, a4);
7908      } catch (e) {
7909        stackRestore(sp);
7910        if (e !== e + 0) throw e;
7911        _setThrew(1, 0);
7912      }
7913    }
7914    function invoke_vii(index, a1, a2) {
7915      var sp = stackSave();
7916      try {
7917        getWasmTableEntry(index)(a1, a2);
7918      } catch (e) {
7919        stackRestore(sp);
7920        if (e !== e + 0) throw e;
7921        _setThrew(1, 0);
7922      }
7923    }
7924    function invoke_vi(index, a1) {
7925      var sp = stackSave();
7926      try {
7927        getWasmTableEntry(index)(a1);
7928      } catch (e) {
7929        stackRestore(sp);
7930        if (e !== e + 0) throw e;
7931        _setThrew(1, 0);
7932      }
7933    }
7934    function invoke_v(index) {
7935      var sp = stackSave();
7936      try {
7937        getWasmTableEntry(index)();
7938      } catch (e) {
7939        stackRestore(sp);
7940        if (e !== e + 0) throw e;
7941        _setThrew(1, 0);
7942      }
7943    }
7944    function invoke_viiii(index, a1, a2, a3, a4) {
7945      var sp = stackSave();
7946      try {
7947        getWasmTableEntry(index)(a1, a2, a3, a4);
7948      } catch (e) {
7949        stackRestore(sp);
7950        if (e !== e + 0) throw e;
7951        _setThrew(1, 0);
7952      }
7953    }
7954    function invoke_viiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
7955      var sp = stackSave();
7956      try {
7957        getWasmTableEntry(index)(a1, a2, a3, a4, a5, a6, a7, a8, a9);
7958      } catch (e) {
7959        stackRestore(sp);
7960        if (e !== e + 0) throw e;
7961        _setThrew(1, 0);
7962      }
7963    }
7964    Module["wasmExports"] = wasmExports;
7965    Module["ccall"] = ccall;
7966    Module["cwrap"] = cwrap;
7967    Module["addFunction"] = addFunction;
7968    Module["removeFunction"] = removeFunction;
7969    Module["setValue"] = setValue;
7970    Module["getValue"] = getValue;
7971    Module["UTF8ToString"] = UTF8ToString;
7972    Module["stringToUTF8"] = stringToUTF8;
7973    Module["UTF16ToString"] = UTF16ToString;
7974    Module["stringToUTF16"] = stringToUTF16;
7975    var missingLibrarySymbols = [
7976      "writeI53ToI64",
7977      "writeI53ToI64Clamped",
7978      "writeI53ToI64Signaling",
7979      "writeI53ToU64Clamped",
7980      "writeI53ToU64Signaling",
7981      "readI53FromI64",
7982      "readI53FromU64",
7983      "convertI32PairToI53",
7984      "convertU32PairToI53",
7985      "getTempRet0",
7986      "setTempRet0",
7987      "exitJS",
7988      "inetPton4",
7989      "inetNtop4",
7990      "inetPton6",
7991      "inetNtop6",
7992      "readSockaddr",
7993      "writeSockaddr",
7994      "emscriptenLog",
7995      "readEmAsmArgs",
7996      "jstoi_q",
7997      "listenOnce",
7998      "autoResumeAudioContext",
7999      "dynCallLegacy",
8000      "getDynCaller",
8001      "dynCall",
8002      "handleException",
8003      "keepRuntimeAlive",
8004      "runtimeKeepalivePush",
8005      "runtimeKeepalivePop",
8006      "callUserCallback",
8007      "maybeExit",
8008      "asmjsMangle",
8009      "HandleAllocator",
8010      "getNativeTypeSize",
8011      "STACK_SIZE",
8012      "STACK_ALIGN",
8013      "POINTER_SIZE",
8014      "ASSERTIONS",
8015      "reallyNegative",
8016      "unSign",
8017      "strLen",
8018      "reSign",
8019      "formatString",
8020      "intArrayToString",
8021      "AsciiToString",
8022      "lengthBytesUTF16",
8023      "UTF32ToString",
8024      "stringToUTF32",
8025      "lengthBytesUTF32",
8026      "stringToNewUTF8",
8027      "registerKeyEventCallback",
8028      "maybeCStringToJsString",
8029      "findEventTarget",
8030      "getBoundingClientRect",
8031      "fillMouseEventData",
8032      "registerMouseEventCallback",
8033      "registerWheelEventCallback",
8034      "registerUiEventCallback",
8035      "registerFocusEventCallback",
8036      "fillDeviceOrientationEventData",
8037      "registerDeviceOrientationEventCallback",
8038      "fillDeviceMotionEventData",
8039      "registerDeviceMotionEventCallback",
8040      "screenOrientation",
8041      "fillOrientationChangeEventData",
8042      "registerOrientationChangeEventCallback",
8043      "fillFullscreenChangeEventData",
8044      "registerFullscreenChangeEventCallback",
8045      "JSEvents_requestFullscreen",
8046      "JSEvents_resizeCanvasForFullscreen",
8047      "registerRestoreOldStyle",
8048      "hideEverythingExceptGivenElement",
8049      "restoreHiddenElements",
8050      "setLetterbox",
8051      "softFullscreenResizeWebGLRenderTarget",
8052      "doRequestFullscreen",
8053      "fillPointerlockChangeEventData",
8054      "registerPointerlockChangeEventCallback",
8055      "registerPointerlockErrorEventCallback",
8056      "requestPointerLock",
8057      "fillVisibilityChangeEventData",
8058      "registerVisibilityChangeEventCallback",
8059      "registerTouchEventCallback",
8060      "fillGamepadEventData",
8061      "registerGamepadEventCallback",
8062      "registerBeforeUnloadEventCallback",
8063      "fillBatteryEventData",
8064      "battery",
8065      "registerBatteryEventCallback",
8066      "setCanvasElementSize",
8067      "getCanvasElementSize",
8068      "jsStackTrace",
8069      "getCallstack",
8070      "convertPCtoSourceLocation",
8071      "checkWasiClock",
8072      "wasiRightsToMuslOFlags",
8073      "wasiOFlagsToMuslOFlags",
8074      "createDyncallWrapper",
8075      "safeSetTimeout",
8076      "setImmediateWrapped",
8077      "clearImmediateWrapped",
8078      "polyfillSetImmediate",
8079      "registerPostMainLoop",
8080      "registerPreMainLoop",
8081      "getPromise",
8082      "makePromise",
8083      "idsToPromises",
8084      "makePromiseCallback",
8085      "ExceptionInfo",
8086      "findMatchingCatch",
8087      "Browser_asyncPrepareDataCounter",
8088      "safeRequestAnimationFrame",
8089      "arraySum",
8090      "addDays",
8091      "getSocketFromFD",
8092      "getSocketAddress",
8093      "FS_unlink",
8094      "FS_mkdirTree",
8095      "_setNetworkCallback",
8096      "heapObjectForWebGLType",
8097      "toTypedArrayIndex",
8098      "webgl_enable_ANGLE_instanced_arrays",
8099      "webgl_enable_OES_vertex_array_object",
8100      "webgl_enable_WEBGL_draw_buffers",
8101      "webgl_enable_WEBGL_multi_draw",
8102      "webgl_enable_EXT_polygon_offset_clamp",
8103      "webgl_enable_EXT_clip_control",
8104      "webgl_enable_WEBGL_polygon_mode",
8105      "emscriptenWebGLGet",
8106      "computeUnpackAlignedImageSize",
8107      "colorChannelsInGlTextureFormat",
8108      "emscriptenWebGLGetTexPixelData",
8109      "emscriptenWebGLGetUniform",
8110      "webglGetUniformLocation",
8111      "webglPrepareUniformLocationsBeforeFirstUse",
8112      "webglGetLeftBracePos",
8113      "emscriptenWebGLGetVertexAttrib",
8114      "__glGetActiveAttribOrUniform",
8115      "writeGLArray",
8116      "registerWebGlEventCallback",
8117      "runAndAbortIfError",
8118      "ALLOC_NORMAL",
8119      "ALLOC_STACK",
8120      "allocate",
8121      "writeStringToMemory",
8122      "writeAsciiToMemory",
8123      "setErrNo",
8124      "demangle",
8125      "stackTrace"
8126    ];
8127    missingLibrarySymbols.forEach(missingLibrarySymbol);
8128    var unexportedSymbols = [
8129      "run",
8130      "addOnPreRun",
8131      "addOnInit",
8132      "addOnPreMain",
8133      "addOnExit",
8134      "addOnPostRun",
8135      "addRunDependency",
8136      "removeRunDependency",
8137      "out",
8138      "err",
8139      "callMain",
8140      "abort",
8141      "wasmMemory",
8142      "writeStackCookie",
8143      "checkStackCookie",
8144      "convertI32PairToI53Checked",
8145      "stackSave",
8146      "stackRestore",
8147      "stackAlloc",
8148      "ptrToString",
8149      "zeroMemory",
8150      "getHeapMax",
8151      "growMemory",
8152      "ENV",
8153      "ERRNO_CODES",
8154      "strError",
8155      "DNS",
8156      "Protocols",
8157      "Sockets",
8158      "initRandomFill",
8159      "randomFill",
8160      "timers",
8161      "warnOnce",
8162      "readEmAsmArgsArray",
8163      "jstoi_s",
8164      "getExecutableName",
8165      "asyncLoad",
8166      "alignMemory",
8167      "mmapAlloc",
8168      "wasmTable",
8169      "noExitRuntime",
8170      "getCFunc",
8171      "uleb128Encode",
8172      "sigToWasmTypes",
8173      "generateFuncType",
8174      "convertJsFunctionToWasm",
8175      "freeTableIndexes",
8176      "functionsInTableMap",
8177      "getEmptyTableSlot",
8178      "updateTableMap",
8179      "getFunctionAddress",
8180      "PATH",
8181      "PATH_FS",
8182      "UTF8Decoder",
8183      "UTF8ArrayToString",
8184      "stringToUTF8Array",
8185      "lengthBytesUTF8",
8186      "intArrayFromString",
8187      "stringToAscii",
8188      "UTF16Decoder",
8189      "stringToUTF8OnStack",
8190      "writeArrayToMemory",
8191      "JSEvents",
8192      "specialHTMLTargets",
8193      "findCanvasEventTarget",
8194      "currentFullscreenStrategy",
8195      "restoreOldWindowedStyle",
8196      "UNWIND_CACHE",
8197      "ExitStatus",
8198      "getEnvStrings",
8199      "doReadv",
8200      "doWritev",
8201      "promiseMap",
8202      "uncaughtExceptionCount",
8203      "exceptionLast",
8204      "exceptionCaught",
8205      "Browser",
8206      "getPreloadedImageData__data",
8207      "wget",
8208      "MONTH_DAYS_REGULAR",
8209      "MONTH_DAYS_LEAP",
8210      "MONTH_DAYS_REGULAR_CUMULATIVE",
8211      "MONTH_DAYS_LEAP_CUMULATIVE",
8212      "isLeapYear",
8213      "ydayFromDate",
8214      "SYSCALLS",
8215      "preloadPlugins",
8216      "FS_createPreloadedFile",
8217      "FS_modeStringToFlags",
8218      "FS_getMode",
8219      "FS_stdin_getChar_buffer",
8220      "FS_stdin_getChar",
8221      "FS_createPath",
8222      "FS_createDevice",
8223      "FS_readFile",
8224      "FS",
8225      "FS_createDataFile",
8226      "FS_createLazyFile",
8227      "MEMFS",
8228      "TTY",
8229      "PIPEFS",
8230      "SOCKFS",
8231      "tempFixedLengthArray",
8232      "miniTempWebGLFloatBuffers",
8233      "miniTempWebGLIntBuffers",
8234      "GL",
8235      "AL",
8236      "GLUT",
8237      "EGL",
8238      "GLEW",
8239      "IDBStore",
8240      "SDL",
8241      "SDL_gfx",
8242      "allocateUTF8",
8243      "allocateUTF8OnStack",
8244      "print",
8245      "printErr"
8246    ];
8247    unexportedSymbols.forEach(unexportedRuntimeSymbol);
8248    var calledRun;
8249    var calledPrerun;
8250    dependenciesFulfilled = function runCaller() {
8251      if (!calledRun) run();
8252      if (!calledRun) dependenciesFulfilled = runCaller;
8253    };
8254    function stackCheckInit() {
8255      _emscripten_stack_init();
8256      writeStackCookie();
8257    }
8258    function run() {
8259      if (runDependencies > 0) {
8260        return;
8261      }
8262      stackCheckInit();
8263      if (!calledPrerun) {
8264        calledPrerun = 1;
8265        preRun();
8266        if (runDependencies > 0) {
8267          return;
8268        }
8269      }
8270      function doRun() {
8271        var _a;
8272        if (calledRun) return;
8273        calledRun = 1;
8274        Module["calledRun"] = 1;
8275        if (ABORT) return;
8276        initRuntime();
8277        readyPromiseResolve(Module);
8278        (_a = Module["onRuntimeInitialized"]) == null ? void 0 : _a.call(Module);
8279        assert(
8280          !Module["_main"],
8281          'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'
8282        );
8283        postRun();
8284      }
8285      if (Module["setStatus"]) {
8286        Module["setStatus"]("Running...");
8287        setTimeout(() => {
8288          setTimeout(() => Module["setStatus"](""), 1);
8289          doRun();
8290        }, 1);
8291      } else {
8292        doRun();
8293      }
8294      checkStackCookie();
8295    }
8296    if (Module["preInit"]) {
8297      if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]];
8298      while (Module["preInit"].length > 0) {
8299        Module["preInit"].pop()();
8300      }
8301    }
8302    run();
8303    moduleRtn = readyPromise;
8304    for (const prop of Object.keys(Module)) {
8305      if (!(prop in moduleArg)) {
8306        Object.defineProperty(moduleArg, prop, {
8307          configurable: true,
8308          get() {
8309            abort(
8310              \`Access to module property ('\${prop}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.\`
8311            );
8312          }
8313        });
8314      }
8315    }
8316    return moduleRtn;
8317  };
8318})();
8319const functions = {
8320  EPDF_GetMetaKeyCount: [["number", "boolean"], "number"],
8321  EPDF_GetMetaKeyName: [
8322    ["number", "number", "boolean", "number", "number"],
8323    "number"
8324  ],
8325  EPDF_GetMetaTrapped: [["number"], "number"],
8326  EPDF_GetPageRotationByIndex: [["number", "number"], "number"],
8327  EPDF_GetPageSizeByIndexNormalized: [["number", "number", "number"], "boolean"],
8328  EPDF_HasMetaText: [["number", "string"], "boolean"],
8329  EPDF_IsEncrypted: [["number"], "boolean"],
vendor: 16,384 bytes, lines 8330-8721
8330  EPDF_IsOwnerUnlocked: [["number"], "boolean"],
8331  EPDF_LoadPageNormalized: [["number", "number", "number"], "number"],
8332  EPDF_PNG_EncodeRGBA: [
8333    ["number", "number", "number", "number", "number", "number"],
8334    "number"
8335  ],
8336  EPDF_RemoveEncryption: [["number"], "boolean"],
8337  EPDF_RenderAnnotBitmap: [
8338    ["number", "number", "number", "number", "number", "number"],
8339    "boolean"
8340  ],
8341  EPDF_RenderAnnotBitmapUnrotated: [
8342    ["number", "number", "number", "number", "number", "number"],
8343    "boolean"
8344  ],
8345  EPDF_SetEncryption: [["number", "string", "string", "number"], "boolean"],
8346  EPDF_SetMetaText: [["number", "string", "number"], "boolean"],
8347  EPDF_SetMetaTrapped: [["number", "number"], "boolean"],
8348  EPDF_UnlockOwnerPermissions: [["number", "string"], "boolean"],
8349  EPDFAction_CreateGoTo: [["number", "number"], "number"],
8350  EPDFAction_CreateGoToNamed: [["number", "string"], "number"],
8351  EPDFAction_CreateLaunch: [["number", "number"], "number"],
8352  EPDFAction_CreateRemoteGoToByName: [["number", "number", "number"], "number"],
8353  EPDFAction_CreateRemoteGoToDest: [["number", "number", "number"], "number"],
8354  EPDFAction_CreateURI: [["number", "string"], "number"],
8355  EPDFAnnot_ApplyRedaction: [["number", "number"], "boolean"],
8356  EPDFAnnot_ClearBorderEffect: [["number"], "boolean"],
8357  EPDFAnnot_ClearColor: [["number", "number"], "boolean"],
8358  EPDFAnnot_ClearMKColor: [["number", "number"], "boolean"],
8359  EPDFAnnot_ClearRectangleDifferences: [["number"], "boolean"],
8360  EPDFAnnot_ExportAppearanceAsDocument: [["number"], "number"],
8361  EPDFAnnot_ExportMultipleAppearancesAsDocument: [["number", "number"], "number"],
8362  EPDFAnnot_Flatten: [["number", "number"], "boolean"],
8363  EPDFAnnot_GenerateAppearance: [["number"], "boolean"],
8364  EPDFAnnot_GenerateAppearanceWithBlend: [["number", "number"], "boolean"],
8365  EPDFAnnot_GenerateFormFieldAP: [["number"], "boolean"],
8366  EPDFAnnot_GetAPMatrix: [["number", "number", "number"], "boolean"],
8367  EPDFAnnot_GetAvailableAppearanceModes: [["number"], "number"],
8368  EPDFAnnot_GetBlendMode: [["number"], "number"],
8369  EPDFAnnot_GetBorderDashPattern: [["number", "number", "number"], "boolean"],
8370  EPDFAnnot_GetBorderDashPatternCount: [["number"], "number"],
8371  EPDFAnnot_GetBorderEffect: [["number", "number"], "boolean"],
8372  EPDFAnnot_GetBorderStyle: [["number", "number"], "number"],
8373  EPDFAnnot_GetButtonExportValue: [["number", "number", "number"], "number"],
8374  EPDFAnnot_GetColor: [
8375    ["number", "number", "number", "number", "number"],
8376    "boolean"
8377  ],
8378  EPDFAnnot_GetDefaultAppearance: [
8379    ["number", "number", "number", "number", "number", "number"],
8380    "boolean"
8381  ],
8382  EPDFAnnot_GetExtendedRotation: [["number", "number"], "boolean"],
8383  EPDFAnnot_GetFormFieldObjectNumber: [["number", "number"], "number"],
8384  EPDFAnnot_GetFormFieldRawValue: [
8385    ["number", "number", "number", "number"],
8386    "number"
8387  ],
8388  EPDFAnnot_GetIntent: [["number", "number", "number"], "number"],
8389  EPDFAnnot_GetLineEndings: [["number", "number", "number"], "boolean"],
8390  EPDFAnnot_GetMKColor: [
8391    ["number", "number", "number", "number", "number"],
8392    "boolean"
8393  ],
8394  EPDFAnnot_GetName: [["number"], "number"],
8395  EPDFAnnot_GetOpacity: [["number", "number"], "boolean"],
8396  EPDFAnnot_GetOverlayText: [["number", "number", "number"], "number"],
8397  EPDFAnnot_GetOverlayTextRepeat: [["number"], "boolean"],
8398  EPDFAnnot_GetRect: [["number", "number"], "boolean"],
8399  EPDFAnnot_GetRectangleDifferences: [
8400    ["number", "number", "number", "number", "number"],
8401    "boolean"
8402  ],
8403  EPDFAnnot_GetReplyType: [["number"], "number"],
8404  EPDFAnnot_GetRichContent: [["number", "number", "number"], "number"],
8405  EPDFAnnot_GetRotate: [["number", "number"], "boolean"],
8406  EPDFAnnot_GetTextAlignment: [["number"], "number"],
8407  EPDFAnnot_GetUnrotatedRect: [["number", "number"], "boolean"],
8408  EPDFAnnot_GetVerticalAlignment: [["number"], "number"],
8409  EPDFAnnot_HasAppearanceStream: [["number", "number"], "boolean"],
8410  EPDFAnnot_SetAction: [["number", "number"], "boolean"],
8411  EPDFAnnot_SetAPMatrix: [["number", "number", "number"], "boolean"],
8412  EPDFAnnot_SetAppearanceFromPage: [["number", "number", "number"], "boolean"],
8413  EPDFAnnot_SetBorderDashPattern: [["number", "number", "number"], "boolean"],
8414  EPDFAnnot_SetBorderEffect: [["number", "number"], "boolean"],
8415  EPDFAnnot_SetBorderStyle: [["number", "number", "number"], "boolean"],
8416  EPDFAnnot_SetColor: [
8417    ["number", "number", "number", "number", "number"],
8418    "boolean"
8419  ],
8420  EPDFAnnot_SetDefaultAppearance: [
8421    ["number", "number", "number", "number", "number", "number"],
8422    "boolean"
8423  ],
8424  EPDFAnnot_SetExtendedRotation: [["number", "number"], "boolean"],
8425  EPDFAnnot_SetFormFieldName: [["number", "number", "number"], "boolean"],
8426  EPDFAnnot_SetFormFieldOptions: [
8427    ["number", "number", "number", "number"],
8428    "boolean"
8429  ],
8430  EPDFAnnot_SetFormFieldValue: [["number", "number", "number"], "boolean"],
8431  EPDFAnnot_SetIntent: [["number", "string"], "boolean"],
8432  EPDFAnnot_SetLine: [["number", "number", "number"], "boolean"],
8433  EPDFAnnot_SetLineEndings: [["number", "number", "number"], "boolean"],
8434  EPDFAnnot_SetLinkedAnnot: [["number", "string", "number"], "boolean"],
8435  EPDFAnnot_SetMKColor: [
8436    ["number", "number", "number", "number", "number"],
8437    "boolean"
8438  ],
8439  EPDFAnnot_SetName: [["number", "number"], "boolean"],
8440  EPDFAnnot_SetNumberValue: [["number", "string", "number"], "boolean"],
8441  EPDFAnnot_SetOpacity: [["number", "number"], "boolean"],
8442  EPDFAnnot_SetOverlayText: [["number", "number"], "boolean"],
8443  EPDFAnnot_SetOverlayTextRepeat: [["number", "boolean"], "boolean"],
8444  EPDFAnnot_SetRectangleDifferences: [
8445    ["number", "number", "number", "number", "number"],
8446    "boolean"
8447  ],
8448  EPDFAnnot_SetReplyType: [["number", "number"], "boolean"],
8449  EPDFAnnot_SetRotate: [["number", "number"], "boolean"],
8450  EPDFAnnot_SetTextAlignment: [["number", "number"], "boolean"],
8451  EPDFAnnot_SetUnrotatedRect: [["number", "number"], "boolean"],
8452  EPDFAnnot_SetVerticalAlignment: [["number", "number"], "boolean"],
8453  EPDFAnnot_SetVertices: [["number", "number", "number"], "boolean"],
8454  EPDFAnnot_ShareFormField: [["number", "number", "number"], "boolean"],
8455  EPDFAnnot_UpdateAppearanceToRect: [["number", "number"], "boolean"],
8456  EPDFAttachment_GetDescription: [["number", "number", "number"], "number"],
8457  EPDFAttachment_GetIntegerValue: [["number", "string", "number"], "boolean"],
8458  EPDFAttachment_SetDescription: [["number", "number"], "boolean"],
8459  EPDFAttachment_SetSubtype: [["number", "string"], "boolean"],
8460  EPDFBookmark_AppendChild: [["number", "number", "number"], "number"],
8461  EPDFBookmark_Clear: [["number"], "boolean"],
8462  EPDFBookmark_ClearTarget: [["number"], "boolean"],
8463  EPDFBookmark_Create: [["number", "number"], "number"],
8464  EPDFBookmark_Delete: [["number", "number"], "boolean"],
8465  EPDFBookmark_InsertAfter: [["number", "number", "number", "number"], "number"],
8466  EPDFBookmark_SetAction: [["number", "number", "number"], "boolean"],
8467  EPDFBookmark_SetDest: [["number", "number", "number"], "boolean"],
8468  EPDFBookmark_SetTitle: [["number", "number"], "boolean"],
8469  EPDFCatalog_GetLanguage: [["number", "number", "number"], "number"],
8470  EPDFDest_CreateRemoteView: [
8471    ["number", "number", "number", "number", "number"],
8472    "number"
8473  ],
8474  EPDFDest_CreateRemoteXYZ: [
8475    ["number", "number", "boolean", "number", "boolean", "number", "boolean", "number"],
8476    "number"
8477  ],
8478  EPDFDest_CreateView: [["number", "number", "number", "number"], "number"],
8479  EPDFDest_CreateXYZ: [
8480    ["number", "boolean", "number", "boolean", "number", "boolean", "number"],
8481    "number"
8482  ],
8483  EPDFImageObj_SetJpeg: [
8484    ["number", "number", "number", "number", "number"],
8485    "boolean"
8486  ],
8487  EPDFImageObj_SetPng: [
8488    ["number", "number", "number", "number", "number"],
8489    "boolean"
8490  ],
8491  EPDFNamedDest_Remove: [["number", "string"], "boolean"],
8492  EPDFNamedDest_SetDest: [["number", "string", "number"], "boolean"],
8493  EPDFPage_ApplyRedactions: [["number"], "boolean"],
8494  EPDFPage_CreateAnnot: [["number", "number"], "number"],
8495  EPDFPage_CreateFormField: [["number", "number", "number", "number"], "number"],
8496  EPDFPage_GetAnnotByName: [["number", "number"], "number"],
8497  EPDFPage_GetAnnotCountRaw: [["number", "number"], "number"],
8498  EPDFPage_GetAnnotRaw: [["number", "number", "number"], "number"],
8499  EPDFPage_RemoveAnnotByName: [["number", "number"], "boolean"],
8500  EPDFPage_RemoveAnnotRaw: [["number", "number", "number"], "boolean"],
8501  EPDFText_RedactInQuads: [
8502    ["number", "number", "number", "boolean", "boolean"],
8503    "boolean"
8504  ],
8505  EPDFText_RedactInRect: [["number", "number", "boolean", "boolean"], "boolean"],
8506  FORM_CanRedo: [["number", "number"], "boolean"],
8507  FORM_CanUndo: [["number", "number"], "boolean"],
8508  FORM_DoDocumentAAction: [["number", "number"], null],
8509  FORM_DoDocumentJSAction: [["number"], null],
8510  FORM_DoDocumentOpenAction: [["number"], null],
8511  FORM_DoPageAAction: [["number", "number", "number"], null],
8512  FORM_ForceToKillFocus: [["number"], "boolean"],
8513  FORM_GetFocusedAnnot: [["number", "number", "number"], "boolean"],
8514  FORM_GetFocusedText: [["number", "number", "number", "number"], "number"],
8515  FORM_GetSelectedText: [["number", "number", "number", "number"], "number"],
8516  FORM_IsIndexSelected: [["number", "number", "number"], "boolean"],
8517  FORM_OnAfterLoadPage: [["number", "number"], null],
8518  FORM_OnBeforeClosePage: [["number", "number"], null],
8519  FORM_OnChar: [["number", "number", "number", "number"], "boolean"],
8520  FORM_OnFocus: [["number", "number", "number", "number", "number"], "boolean"],
8521  FORM_OnKeyDown: [["number", "number", "number", "number"], "boolean"],
8522  FORM_OnKeyUp: [["number", "number", "number", "number"], "boolean"],
8523  FORM_OnLButtonDoubleClick: [
8524    ["number", "number", "number", "number", "number"],
8525    "boolean"
8526  ],
8527  FORM_OnLButtonDown: [
8528    ["number", "number", "number", "number", "number"],
8529    "boolean"
8530  ],
8531  FORM_OnLButtonUp: [
8532    ["number", "number", "number", "number", "number"],
8533    "boolean"
8534  ],
8535  FORM_OnMouseMove: [
8536    ["number", "number", "number", "number", "number"],
8537    "boolean"
8538  ],
8539  FORM_OnMouseWheel: [
8540    ["number", "number", "number", "number", "number", "number"],
8541    "boolean"
8542  ],
8543  FORM_OnRButtonDown: [
8544    ["number", "number", "number", "number", "number"],
8545    "boolean"
8546  ],
8547  FORM_OnRButtonUp: [
8548    ["number", "number", "number", "number", "number"],
8549    "boolean"
8550  ],
8551  FORM_Redo: [["number", "number"], "boolean"],
8552  FORM_ReplaceAndKeepSelection: [["number", "number", "number"], null],
8553  FORM_ReplaceSelection: [["number", "number", "number"], null],
8554  FORM_SelectAllText: [["number", "number"], "boolean"],
8555  FORM_SetFocusedAnnot: [["number", "number"], "boolean"],
8556  FORM_SetIndexSelected: [["number", "number", "number", "boolean"], "boolean"],
8557  FORM_Undo: [["number", "number"], "boolean"],
8558  FPDF_AddInstalledFont: [["number", "number", "number"], null],
8559  FPDF_CloseDocument: [["number"], null],
8560  FPDF_ClosePage: [["number"], null],
8561  FPDF_CloseXObject: [["number"], null],
8562  FPDF_CopyViewerPreferences: [["number", "number"], "boolean"],
8563  FPDF_CountNamedDests: [["number"], "number"],
8564  FPDF_CreateClipPath: [["number", "number", "number", "number"], "number"],
8565  FPDF_CreateNewDocument: [[], "number"],
8566  FPDF_DestroyClipPath: [["number"], null],
8567  FPDF_DestroyLibrary: [[], null],
8568  FPDF_DeviceToPage: [
8569    [
8570      "number",
8571      "number",
8572      "number",
8573      "number",
8574      "number",
8575      "number",
8576      "number",
8577      "number",
8578      "number",
8579      "number"
8580    ],
8581    "boolean"
8582  ],
8583  FPDF_DocumentHasValidCrossReferenceTable: [["number"], "boolean"],
8584  FPDF_FFLDraw: [
8585    [
8586      "number",
8587      "number",
8588      "number",
8589      "number",
8590      "number",
8591      "number",
8592      "number",
8593      "number",
8594      "number"
8595    ],
8596    null
8597  ],
8598  FPDF_FreeDefaultSystemFontInfo: [["number"], null],
8599  FPDF_GetDefaultSystemFontInfo: [[], "number"],
8600  FPDF_GetDefaultTTFMap: [[], "number"],
8601  FPDF_GetDefaultTTFMapCount: [[], "number"],
8602  FPDF_GetDefaultTTFMapEntry: [["number"], "number"],
8603  FPDF_GetDocPermissions: [["number"], "number"],
8604  FPDF_GetDocUserPermissions: [["number"], "number"],
8605  FPDF_GetFileIdentifier: [["number", "number", "number", "number"], "number"],
8606  FPDF_GetFileVersion: [["number", "number"], "boolean"],
8607  FPDF_GetFormType: [["number"], "number"],
8608  FPDF_GetLastError: [[], "number"],
8609  FPDF_GetMetaText: [["number", "string", "number", "number"], "number"],
8610  FPDF_GetNamedDest: [["number", "number", "number", "number"], "number"],
8611  FPDF_GetNamedDestByName: [["number", "string"], "number"],
8612  FPDF_GetPageAAction: [["number", "number"], "number"],
8613  FPDF_GetPageBoundingBox: [["number", "number"], "boolean"],
8614  FPDF_GetPageCount: [["number"], "number"],
8615  FPDF_GetPageHeight: [["number"], "number"],
8616  FPDF_GetPageHeightF: [["number"], "number"],
8617  FPDF_GetPageLabel: [["number", "number", "number", "number"], "number"],
8618  FPDF_GetPageSizeByIndex: [["number", "number", "number", "number"], "number"],
8619  FPDF_GetPageSizeByIndexF: [["number", "number", "number"], "boolean"],
8620  FPDF_GetPageWidth: [["number"], "number"],
8621  FPDF_GetPageWidthF: [["number"], "number"],
8622  FPDF_GetSecurityHandlerRevision: [["number"], "number"],
8623  FPDF_GetSignatureCount: [["number"], "number"],
8624  FPDF_GetSignatureObject: [["number", "number"], "number"],
8625  FPDF_GetTrailerEnds: [["number", "number", "number"], "number"],
8626  FPDF_GetXFAPacketContent: [
8627    ["number", "number", "number", "number", "number"],
8628    "boolean"
8629  ],
8630  FPDF_GetXFAPacketCount: [["number"], "number"],
8631  FPDF_GetXFAPacketName: [["number", "number", "number", "number"], "number"],
8632  FPDF_ImportNPagesToOne: [
8633    ["number", "number", "number", "number", "number"],
8634    "number"
8635  ],
8636  FPDF_ImportPages: [["number", "number", "string", "number"], "boolean"],
8637  FPDF_ImportPagesByIndex: [
8638    ["number", "number", "number", "number", "number"],
8639    "boolean"
8640  ],
8641  FPDF_InitLibrary: [[], null],
8642  FPDF_InitLibraryWithConfig: [["number"], null],
8643  FPDF_LoadCustomDocument: [["number", "string"], "number"],
8644  FPDF_LoadDocument: [["number", "string"], "number"],
8645  FPDF_LoadMemDocument: [["number", "number", "string"], "number"],
8646  FPDF_LoadMemDocument64: [["number", "number", "string"], "number"],
8647  FPDF_LoadPage: [["number", "number"], "number"],
8648  FPDF_LoadXFA: [["number"], "boolean"],
8649  FPDF_MovePages: [["number", "number", "number", "number"], "boolean"],
8650  FPDF_NewFormObjectFromXObject: [["number"], "number"],
8651  FPDF_NewXObjectFromPage: [["number", "number", "number"], "number"],
8652  FPDF_PageToDevice: [
8653    [
8654      "number",
8655      "number",
8656      "number",
8657      "number",
8658      "number",
8659      "number",
8660      "number",
8661      "number",
8662      "number",
8663      "number"
8664    ],
8665    "boolean"
8666  ],
8667  FPDF_RemoveFormFieldHighlight: [["number"], null],
8668  FPDF_RenderPage_Close: [["number"], null],
8669  FPDF_RenderPage_Continue: [["number", "number"], "number"],
8670  FPDF_RenderPageBitmap: [
8671    ["number", "number", "number", "number", "number", "number", "number", "number"],
8672    null
8673  ],
8674  FPDF_RenderPageBitmap_Start: [
8675    [
8676      "number",
8677      "number",
8678      "number",
8679      "number",
8680      "number",
8681      "number",
8682      "number",
8683      "number",
8684      "number"
8685    ],
8686    "number"
8687  ],
8688  FPDF_RenderPageBitmapWithColorScheme_Start: [
8689    [
8690      "number",
8691      "number",
8692      "number",
8693      "number",
8694      "number",
8695      "number",
8696      "number",
8697      "number",
8698      "number",
8699      "number"
8700    ],
8701    "number"
8702  ],
8703  FPDF_RenderPageBitmapWithMatrix: [
8704    ["number", "number", "number", "number", "number"],
8705    null
8706  ],
8707  FPDF_SaveAsCopy: [["number", "number", "number"], "boolean"],
8708  FPDF_SaveWithVersion: [["number", "number", "number", "number"], "boolean"],
8709  FPDF_SetFormFieldHighlightAlpha: [["number", "number"], null],
8710  FPDF_SetFormFieldHighlightColor: [["number", "number", "number"], null],
8711  FPDF_SetSandBoxPolicy: [["number", "boolean"], null],
8712  FPDF_SetSystemFontInfo: [["number"], null],
8713  FPDF_StructElement_Attr_CountChildren: [["number"], "number"],
8714  FPDF_StructElement_Attr_GetBlobValue: [
8715    ["number", "number", "number", "number"],
8716    "boolean"
8717  ],
8718  FPDF_StructElement_Attr_GetBooleanValue: [["number", "number"], "boolean"],
8719  FPDF_StructElement_Attr_GetChildAtIndex: [["number", "number"], "number"],
8720  FPDF_StructElement_Attr_GetCount: [["number"], "number"],
8721  FPDF_Str
8721uctElement_Attr_GetName: [
8722    ["number", "number", "number", "number", "number"],
8723    "boolean"
8724  ],
8725  FPDF_StructElement_Attr_GetNumberValue: [["number", "number"], "boolean"],
8726  FPDF_StructElement_Attr_GetStringValue: [
8727    ["number", "number", "number", "number"],
8728    "boolean"
8729  ],
8730  FPDF_StructElement_Attr_GetType: [["number"], "number"],
8731  FPDF_StructElement_Attr_GetValue: [["number", "string"], "number"],
8732  FPDF_StructElement_CountChildren: [["number"], "number"],
8733  FPDF_StructElement_GetActualText: [["number", "number", "number"], "number"],
8734  FPDF_StructElement_GetAltText: [["number", "number", "number"], "number"],
8735  FPDF_StructElement_GetAttributeAtIndex: [["number", "number"], "number"],
8736  FPDF_StructElement_GetAttributeCount: [["number"], "number"],
8737  FPDF_StructElement_GetChildAtIndex: [["number", "number"], "number"],
8738  FPDF_StructElement_GetChildMarkedContentID: [["number", "number"], "number"],
8739  FPDF_StructElement_GetID: [["number", "number", "number"], "number"],
8740  FPDF_StructElement_GetLang: [["number", "number", "number"], "number"],
8741  FPDF_StructElement_GetMarkedContentID: [["number"], "number"],
8742  FPDF_StructElement_GetMarkedContentIdAtIndex: [["number", "number"], "number"],
8743  FPDF_StructElement_GetMarkedContentIdCount: [["number"], "number"],
8744  FPDF_StructElement_GetObjType: [["number", "number", "number"], "number"],
8745  FPDF_StructElement_GetParent: [["number"], "number"],
8746  FPDF_StructElement_GetStringAttribute: [
8747    ["number", "string", "number", "number"],
8748    "number"
8749  ],
8750  FPDF_StructElement_GetTitle: [["number", "number", "number"], "number"],
8751  FPDF_StructElement_GetType: [["number", "number", "number"], "number"],
8752  FPDF_StructTree_Close: [["number"], null],
8753  FPDF_StructTree_CountChildren: [["number"], "number"],
8754  FPDF_StructTree_GetChildAtIndex: [["number", "number"], "number"],
8755  FPDF_StructTree_GetForPage: [["number"], "number"],
8756  FPDF_VIEWERREF_GetDuplex: [["number"], "number"],
8757  FPDF_VIEWERREF_GetName: [["number", "string", "number", "number"], "number"],
8758  FPDF_VIEWERREF_GetNumCopies: [["number"], "number"],
8759  FPDF_VIEWERREF_GetPrintPageRange: [["number"], "number"],
8760  FPDF_VIEWERREF_GetPrintPageRangeCount: [["number"], "number"],
8761  FPDF_VIEWERREF_GetPrintPageRangeElement: [["number", "number"], "number"],
8762  FPDF_VIEWERREF_GetPrintScaling: [["number"], "boolean"],
8763  FPDFAction_GetDest: [["number", "number"], "number"],
8764  FPDFAction_GetFilePath: [["number", "number", "number"], "number"],
8765  FPDFAction_GetType: [["number"], "number"],
8766  FPDFAction_GetURIPath: [["number", "number", "number", "number"], "number"],
8767  FPDFAnnot_AddFileAttachment: [["number", "number"], "number"],
8768  FPDFAnnot_AddInkStroke: [["number", "number", "number"], "number"],
8769  FPDFAnnot_AppendAttachmentPoints: [["number", "number"], "boolean"],
8770  FPDFAnnot_AppendObject: [["number", "number"], "boolean"],
8771  FPDFAnnot_CountAttachmentPoints: [["number"], "number"],
8772  FPDFAnnot_GetAP: [["number", "number", "number", "number"], "number"],
8773  FPDFAnnot_GetAttachmentPoints: [["number", "number", "number"], "boolean"],
8774  FPDFAnnot_GetBorder: [["number", "number", "number", "number"], "boolean"],
8775  FPDFAnnot_GetColor: [
8776    ["number", "number", "number", "number", "number", "number"],
8777    "boolean"
8778  ],
8779  FPDFAnnot_GetFileAttachment: [["number"], "number"],
8780  FPDFAnnot_GetFlags: [["number"], "number"],
8781  FPDFAnnot_GetFocusableSubtypes: [["number", "number", "number"], "boolean"],
8782  FPDFAnnot_GetFocusableSubtypesCount: [["number"], "number"],
8783  FPDFAnnot_GetFontColor: [
8784    ["number", "number", "number", "number", "number"],
8785    "boolean"
8786  ],
8787  FPDFAnnot_GetFontSize: [["number", "number", "number"], "boolean"],
8788  FPDFAnnot_GetFormAdditionalActionJavaScript: [
8789    ["number", "number", "number", "number", "number"],
8790    "number"
8791  ],
8792  FPDFAnnot_GetFormControlCount: [["number", "number"], "number"],
8793  FPDFAnnot_GetFormControlIndex: [["number", "number"], "number"],
8794  FPDFAnnot_GetFormFieldAlternateName: [
8795    ["number", "number", "number", "number"],
8796    "number"
8797  ],
8798  FPDFAnnot_GetFormFieldAtPoint: [["number", "number", "number"], "number"],
8799  FPDFAnnot_GetFormFieldExportValue: [
8800    ["number", "number", "number", "number"],
8801    "number"
8802  ],
8803  FPDFAnnot_GetFormFieldFlags: [["number", "number"], "number"],
8804  FPDFAnnot_GetFormFieldName: [
8805    ["number", "number", "number", "number"],
8806    "number"
8807  ],
8808  FPDFAnnot_GetFormFieldType: [["number", "number"], "number"],
8809  FPDFAnnot_GetFormFieldValue: [
8810    ["number", "number", "number", "number"],
8811    "number"
8812  ],
8813  FPDFAnnot_GetInkListCount: [["number"], "number"],
8814  FPDFAnnot_GetInkListPath: [["number", "number", "number", "number"], "number"],
8815  FPDFAnnot_GetLine: [["number", "number", "number"], "boolean"],
8816  FPDFAnnot_GetLink: [["number"], "number"],
8817  FPDFAnnot_GetLinkedAnnot: [["number", "string"], "number"],
8818  FPDFAnnot_GetNumberValue: [["number", "string", "number"], "boolean"],
8819  FPDFAnnot_GetObject: [["number", "number"], "number"],
8820  FPDFAnnot_GetObjectCount: [["number"], "number"],
8821  FPDFAnnot_GetOptionCount: [["number", "number"], "number"],
8822  FPDFAnnot_GetOptionLabel: [
8823    ["number", "number", "number", "number", "number"],
8824    "number"
8825  ],
8826  FPDFAnnot_GetRect: [["number", "number"], "boolean"],
8827  FPDFAnnot_GetStringValue: [["number", "string", "number", "number"], "number"],
8828  FPDFAnnot_GetSubtype: [["number"], "number"],
8829  FPDFAnnot_GetValueType: [["number", "string"], "number"],
8830  FPDFAnnot_GetVertices: [["number", "number", "number"], "number"],
8831  FPDFAnnot_HasAttachmentPoints: [["number"], "boolean"],
8832  FPDFAnnot_HasKey: [["number", "string"], "boolean"],
8833  FPDFAnnot_IsChecked: [["number", "number"], "boolean"],
8834  FPDFAnnot_IsObjectSupportedSubtype: [["number"], "boolean"],
8835  FPDFAnnot_IsOptionSelected: [["number", "number", "number"], "boolean"],
8836  FPDFAnnot_IsSupportedSubtype: [["number"], "boolean"],
8837  FPDFAnnot_RemoveInkList: [["number"], "boolean"],
8838  FPDFAnnot_RemoveObject: [["number", "number"], "boolean"],
8839  FPDFAnnot_SetAP: [["number", "number", "number"], "boolean"],
8840  FPDFAnnot_SetAttachmentPoints: [["number", "number", "number"], "boolean"],
8841  FPDFAnnot_SetBorder: [["number", "number", "number", "number"], "boolean"],
8842  FPDFAnnot_SetColor: [
8843    ["number", "number", "number", "number", "number", "number"],
8844    "boolean"
8845  ],
8846  FPDFAnnot_SetFlags: [["number", "number"], "boolean"],
8847  FPDFAnnot_SetFocusableSubtypes: [["number", "number", "number"], "boolean"],
8848  FPDFAnnot_SetFontColor: [
8849    ["number", "number", "number", "number", "number"],
8850    "boolean"
8851  ],
8852  FPDFAnnot_SetFormFieldFlags: [["number", "number", "number"], "boolean"],
8853  FPDFAnnot_SetRect: [["number", "number"], "boolean"],
8854  FPDFAnnot_SetStringValue: [["number", "string", "number"], "boolean"],
8855  FPDFAnnot_SetURI: [["number", "number"], "boolean"],
8856  FPDFAnnot_UpdateObject: [["number", "number"], "boolean"],
8857  FPDFAttachment_GetFile: [["number", "number", "number", "number"], "boolean"],
8858  FPDFAttachment_GetName: [["number", "number", "number"], "number"],
8859  FPDFAttachment_GetStringValue: [
8860    ["number", "string", "number", "number"],
8861    "number"
8862  ],
8863  FPDFAttachment_GetSubtype: [["number", "number", "number"], "number"],
8864  FPDFAttachment_GetValueType: [["number", "string"], "number"],
8865  FPDFAttachment_HasKey: [["number", "string"], "boolean"],
8866  FPDFAttachment_SetFile: [["number", "number", "number", "number"], "boolean"],
8867  FPDFAttachment_SetStringValue: [["number", "string", "number"], "boolean"],
8868  FPDFAvail_Create: [["number", "number"], "number"],
8869  FPDFAvail_Destroy: [["number"], null],
8870  FPDFAvail_GetDocument: [["number", "string"], "number"],
8871  FPDFAvail_GetFirstPageNum: [["number"], "number"],
8872  FPDFAvail_IsDocAvail: [["number", "number"], "number"],
8873  FPDFAvail_IsFormAvail: [["number", "number"], "number"],
8874  FPDFAvail_IsLinearized: [["number"], "number"],
8875  FPDFAvail_IsPageAvail: [["number", "number", "number"], "number"],
8876  FPDFBitmap_Create: [["number", "number", "number"], "number"],
8877  FPDFBitmap_CreateEx: [
8878    ["number", "number", "number", "number", "number"],
8879    "number"
8880  ],
8881  FPDFBitmap_Destroy: [["number"], null],
8882  FPDFBitmap_FillRect: [
8883    ["number", "number", "number", "number", "number", "number"],
8884    "boolean"
8885  ],
8886  FPDFBitmap_GetBuffer: [["number"], "number"],
8887  FPDFBitmap_GetFormat: [["number"], "number"],
8888  FPDFBitmap_GetHeight: [["number"], "number"],
8889  FPDFBitmap_GetStride: [["number"], "number"],
8890  FPDFBitmap_GetWidth: [["number"], "number"],
8891  FPDFBookmark_Find: [["number", "number"], "number"],
8892  FPDFBookmark_GetAction: [["number"], "number"],
8893  FPDFBookmark_GetCount: [["number"], "number"],
8894  FPDFBookmark_GetDest: [["number", "number"], "number"],
8895  FPDFBookmark_GetFirstChild: [["number", "number"], "number"],
8896  FPDFBookmark_GetNextSibling: [["number", "number"], "number"],
8897  FPDFBookmark_GetTitle: [["number", "number", "number"], "number"],
8898  FPDFCatalog_GetLanguage: [["number", "number", "number"], "number"],
8899  FPDFCatalog_IsTagged: [["number"], "boolean"],
8900  FPDFCatalog_SetLanguage: [["number", "number"], "boolean"],
8901  FPDFClipPath_CountPaths: [["number"], "number"],
8902  FPDFClipPath_CountPathSegments: [["number", "number"], "number"],
8903  FPDFClipPath_GetPathSegment: [["number", "number", "number"], "number"],
8904  FPDFDest_GetDestPageIndex: [["number", "number"], "number"],
8905  FPDFDest_GetLocationInPage: [
8906    ["number", "number", "number", "number", "number", "number", "number"],
8907    "boolean"
8908  ],
8909  FPDFDest_GetView: [["number", "number", "number"], "number"],
8910  FPDFDoc_AddAttachment: [["number", "number"], "number"],
8911  FPDFDoc_CloseJavaScriptAction: [["number"], null],
8912  FPDFDoc_DeleteAttachment: [["number", "number"], "boolean"],
8913  FPDFDOC_ExitFormFillEnvironment: [["number"], null],
8914  FPDFDoc_GetAttachment: [["number", "number"], "number"],
8915  FPDFDoc_GetAttachmentCount: [["number"], "number"],
8916  FPDFDoc_GetJavaScriptAction: [["number", "number"], "number"],
8917  FPDFDoc_GetJavaScriptActionCount: [["number"], "number"],
8918  FPDFDoc_GetPageMode: [["number"], "number"],
8919  FPDFDOC_InitFormFillEnvironment: [["number", "number"], "number"],
8920  FPDFFont_Close: [["number"], null],
8921  FPDFFont_GetAscent: [["number", "number", "number"], "boolean"],
8922  FPDFFont_GetBaseFontName: [["number", "number", "number"], "number"],
8923  FPDFFont_GetDescent: [["number", "number", "number"], "boolean"],
8924  FPDFFont_GetFamilyName: [["number", "number", "number"], "number"],
8925  FPDFFont_GetFlags: [["number"], "number"],
8926  FPDFFont_GetFontData: [["number", "number", "number", "number"], "boolean"],
8927  FPDFFont_GetGlyphPath: [["number", "number", "number"], "number"],
8928  FPDFFont_GetGlyphWidth: [["number", "number", "number", "number"], "boolean"],
8929  FPDFFont_GetIsEmbedded: [["number"], "number"],
8930  FPDFFont_GetItalicAngle: [["number", "number"], "boolean"],
8931  FPDFFont_GetWeight: [["number"], "number"],
8932  FPDFFormObj_CountObjects: [["number"], "number"],
8933  FPDFFormObj_GetObject: [["number", "number"], "number"],
8934  FPDFFormObj_RemoveObject: [["number", "number"], "boolean"],
8935  FPDFGlyphPath_CountGlyphSegments: [["number"], "number"],
8936  FPDFGlyphPath_GetGlyphPathSegment: [["number", "number"], "number"],
8937  FPDFImageObj_GetBitmap: [["number"], "number"],
8938  FPDFImageObj_GetIccProfileDataDecoded: [
8939    ["number", "number", "number", "number", "number"],
8940    "boolean"
8941  ],
8942  FPDFImageObj_GetImageDataDecoded: [["number", "number", "number"], "number"],
8943  FPDFImageObj_GetImageDataRaw: [["number", "number", "number"], "number"],
8944  FPDFImageObj_GetImageFilter: [
8945    ["number", "number", "number", "number"],
8946    "number"
8947  ],
8948  FPDFImageObj_GetImageFilterCount: [["number"], "number"],
8949  FPDFImageObj_GetImageMetadata: [["number", "number", "number"], "boolean"],
8950  FPDFImageObj_GetImagePixelSize: [["number", "number", "number"], "boolean"],
8951  FPDFImageObj_GetRenderedBitmap: [["number", "number", "number"], "number"],
8952  FPDFImageObj_LoadJpegFile: [
8953    ["number", "number", "number", "number"],
8954    "boolean"
8955  ],
8956  FPDFImageObj_LoadJpegFileInline: [
8957    ["number", "number", "number", "number"],
8958    "boolean"
8959  ],
8960  FPDFImageObj_SetBitmap: [["number", "number", "number", "number"], "boolean"],
vendor: 9,163 bytes, lines 8961-9168
8961  FPDFImageObj_SetMatrix: [
8962    ["number", "number", "number", "number", "number", "number", "number"],
8963    "boolean"
8964  ],
8965  FPDFJavaScriptAction_GetName: [["number", "number", "number"], "number"],
8966  FPDFJavaScriptAction_GetScript: [["number", "number", "number"], "number"],
8967  FPDFLink_CloseWebLinks: [["number"], null],
8968  FPDFLink_CountQuadPoints: [["number"], "number"],
8969  FPDFLink_CountRects: [["number", "number"], "number"],
8970  FPDFLink_CountWebLinks: [["number"], "number"],
8971  FPDFLink_Enumerate: [["number", "number", "number"], "boolean"],
8972  FPDFLink_GetAction: [["number"], "number"],
8973  FPDFLink_GetAnnot: [["number", "number"], "number"],
8974  FPDFLink_GetAnnotRect: [["number", "number"], "boolean"],
8975  FPDFLink_GetDest: [["number", "number"], "number"],
8976  FPDFLink_GetLinkAtPoint: [["number", "number", "number"], "number"],
8977  FPDFLink_GetLinkZOrderAtPoint: [["number", "number", "number"], "number"],
8978  FPDFLink_GetQuadPoints: [["number", "number", "number"], "boolean"],
8979  FPDFLink_GetRect: [
8980    ["number", "number", "number", "number", "number", "number", "number"],
8981    "boolean"
8982  ],
8983  FPDFLink_GetTextRange: [["number", "number", "number", "number"], "boolean"],
8984  FPDFLink_GetURL: [["number", "number", "number", "number"], "number"],
8985  FPDFLink_LoadWebLinks: [["number"], "number"],
8986  FPDFPage_CloseAnnot: [["number"], null],
8987  FPDFPage_CountObjects: [["number"], "number"],
8988  FPDFPage_CreateAnnot: [["number", "number"], "number"],
8989  FPDFPage_Delete: [["number", "number"], null],
8990  FPDFPage_Flatten: [["number", "number"], "number"],
8991  FPDFPage_FormFieldZOrderAtPoint: [
8992    ["number", "number", "number", "number"],
8993    "number"
8994  ],
8995  FPDFPage_GenerateContent: [["number"], "boolean"],
8996  FPDFPage_GetAnnot: [["number", "number"], "number"],
8997  FPDFPage_GetAnnotCount: [["number"], "number"],
8998  FPDFPage_GetAnnotIndex: [["number", "number"], "number"],
8999  FPDFPage_GetArtBox: [
9000    ["number", "number", "number", "number", "number"],
9001    "boolean"
9002  ],
9003  FPDFPage_GetBleedBox: [
9004    ["number", "number", "number", "number", "number"],
9005    "boolean"
9006  ],
9007  FPDFPage_GetCropBox: [
9008    ["number", "number", "number", "number", "number"],
9009    "boolean"
9010  ],
9011  FPDFPage_GetDecodedThumbnailData: [["number", "number", "number"], "number"],
9012  FPDFPage_GetMediaBox: [
9013    ["number", "number", "number", "number", "number"],
9014    "boolean"
9015  ],
9016  FPDFPage_GetObject: [["number", "number"], "number"],
9017  FPDFPage_GetRawThumbnailData: [["number", "number", "number"], "number"],
9018  FPDFPage_GetRotation: [["number"], "number"],
9019  FPDFPage_GetThumbnailAsBitmap: [["number"], "number"],
9020  FPDFPage_GetTrimBox: [
9021    ["number", "number", "number", "number", "number"],
9022    "boolean"
9023  ],
9024  FPDFPage_HasFormFieldAtPoint: [
9025    ["number", "number", "number", "number"],
9026    "number"
9027  ],
9028  FPDFPage_HasTransparency: [["number"], "boolean"],
9029  FPDFPage_InsertClipPath: [["number", "number"], null],
9030  FPDFPage_InsertObject: [["number", "number"], null],
9031  FPDFPage_InsertObjectAtIndex: [["number", "number", "number"], "boolean"],
9032  FPDFPage_New: [["number", "number", "number", "number"], "number"],
9033  FPDFPage_RemoveAnnot: [["number", "number"], "boolean"],
9034  FPDFPage_RemoveObject: [["number", "number"], "boolean"],
9035  FPDFPage_SetArtBox: [["number", "number", "number", "number", "number"], null],
9036  FPDFPage_SetBleedBox: [
9037    ["number", "number", "number", "number", "number"],
9038    null
9039  ],
9040  FPDFPage_SetCropBox: [["number", "number", "number", "number", "number"], null],
9041  FPDFPage_SetMediaBox: [
9042    ["number", "number", "number", "number", "number"],
9043    null
9044  ],
9045  FPDFPage_SetRotation: [["number", "number"], null],
9046  FPDFPage_SetTrimBox: [["number", "number", "number", "number", "number"], null],
9047  FPDFPage_TransformAnnots: [
9048    ["number", "number", "number", "number", "number", "number", "number"],
9049    null
9050  ],
9051  FPDFPage_TransFormWithClip: [["number", "number", "number"], "boolean"],
9052  FPDFPageObj_AddMark: [["number", "string"], "number"],
9053  FPDFPageObj_CountMarks: [["number"], "number"],
9054  FPDFPageObj_CreateNewPath: [["number", "number"], "number"],
9055  FPDFPageObj_CreateNewRect: [["number", "number", "number", "number"], "number"],
9056  FPDFPageObj_CreateTextObj: [["number", "number", "number"], "number"],
9057  FPDFPageObj_Destroy: [["number"], null],
9058  FPDFPageObj_GetBounds: [
9059    ["number", "number", "number", "number", "number"],
9060    "boolean"
9061  ],
9062  FPDFPageObj_GetClipPath: [["number"], "number"],
9063  FPDFPageObj_GetDashArray: [["number", "number", "number"], "boolean"],
9064  FPDFPageObj_GetDashCount: [["number"], "number"],
9065  FPDFPageObj_GetDashPhase: [["number", "number"], "boolean"],
9066  FPDFPageObj_GetFillColor: [
9067    ["number", "number", "number", "number", "number"],
9068    "boolean"
9069  ],
9070  FPDFPageObj_GetIsActive: [["number", "number"], "boolean"],
9071  FPDFPageObj_GetLineCap: [["number"], "number"],
9072  FPDFPageObj_GetLineJoin: [["number"], "number"],
9073  FPDFPageObj_GetMark: [["number", "number"], "number"],
9074  FPDFPageObj_GetMarkedContentID: [["number"], "number"],
9075  FPDFPageObj_GetMatrix: [["number", "number"], "boolean"],
9076  FPDFPageObj_GetRotatedBounds: [["number", "number"], "boolean"],
9077  FPDFPageObj_GetStrokeColor: [
9078    ["number", "number", "number", "number", "number"],
9079    "boolean"
9080  ],
9081  FPDFPageObj_GetStrokeWidth: [["number", "number"], "boolean"],
9082  FPDFPageObj_GetType: [["number"], "number"],
9083  FPDFPageObj_HasTransparency: [["number"], "boolean"],
9084  FPDFPageObj_NewImageObj: [["number"], "number"],
9085  FPDFPageObj_NewTextObj: [["number", "string", "number"], "number"],
9086  FPDFPageObj_RemoveMark: [["number", "number"], "boolean"],
9087  FPDFPageObj_SetBlendMode: [["number", "string"], null],
9088  FPDFPageObj_SetDashArray: [["number", "number", "number", "number"], "boolean"],
9089  FPDFPageObj_SetDashPhase: [["number", "number"], "boolean"],
9090  FPDFPageObj_SetFillColor: [
9091    ["number", "number", "number", "number", "number"],
9092    "boolean"
9093  ],
9094  FPDFPageObj_SetIsActive: [["number", "boolean"], "boolean"],
9095  FPDFPageObj_SetLineCap: [["number", "number"], "boolean"],
9096  FPDFPageObj_SetLineJoin: [["number", "number"], "boolean"],
9097  FPDFPageObj_SetMatrix: [["number", "number"], "boolean"],
9098  FPDFPageObj_SetStrokeColor: [
9099    ["number", "number", "number", "number", "number"],
9100    "boolean"
9101  ],
9102  FPDFPageObj_SetStrokeWidth: [["number", "number"], "boolean"],
9103  FPDFPageObj_Transform: [
9104    ["number", "number", "number", "number", "number", "number", "number"],
9105    null
9106  ],
9107  FPDFPageObj_TransformClipPath: [
9108    ["number", "number", "number", "number", "number", "number", "number"],
9109    null
9110  ],
9111  FPDFPageObj_TransformF: [["number", "number"], "boolean"],
9112  FPDFPageObjMark_CountParams: [["number"], "number"],
9113  FPDFPageObjMark_GetName: [["number", "number", "number", "number"], "boolean"],
9114  FPDFPageObjMark_GetParamBlobValue: [
9115    ["number", "string", "number", "number", "number"],
9116    "boolean"
9117  ],
9118  FPDFPageObjMark_GetParamFloatValue: [["number", "string", "number"], "boolean"],
9119  FPDFPageObjMark_GetParamIntValue: [["number", "string", "number"], "boolean"],
9120  FPDFPageObjMark_GetParamKey: [
9121    ["number", "number", "number", "number", "number"],
9122    "boolean"
9123  ],
9124  FPDFPageObjMark_GetParamStringValue: [
9125    ["number", "string", "number", "number", "number"],
9126    "boolean"
9127  ],
9128  FPDFPageObjMark_GetParamValueType: [["number", "string"], "number"],
9129  FPDFPageObjMark_RemoveParam: [["number", "number", "string"], "boolean"],
9130  FPDFPageObjMark_SetBlobParam: [
9131    ["number", "number", "number", "string", "number", "number"],
9132    "boolean"
9133  ],
9134  FPDFPageObjMark_SetFloatParam: [
9135    ["number", "number", "number", "string", "number"],
9136    "boolean"
9137  ],
9138  FPDFPageObjMark_SetIntParam: [
9139    ["number", "number", "number", "string", "number"],
9140    "boolean"
9141  ],
9142  FPDFPageObjMark_SetStringParam: [
9143    ["number", "number", "number", "string", "string"],
9144    "boolean"
9145  ],
9146  FPDFPath_BezierTo: [
9147    ["number", "number", "number", "number", "number", "number", "number"],
9148    "boolean"
9149  ],
9150  FPDFPath_Close: [["number"], "boolean"],
9151  FPDFPath_CountSegments: [["number"], "number"],
9152  FPDFPath_GetDrawMode: [["number", "number", "number"], "boolean"],
9153  FPDFPath_GetPathSegment: [["number", "number"], "number"],
9154  FPDFPath_LineTo: [["number", "number", "number"], "boolean"],
9155  FPDFPath_MoveTo: [["number", "number", "number"], "boolean"],
9156  FPDFPath_SetDrawMode: [["number", "number", "boolean"], "boolean"],
9157  FPDFPathSegment_GetClose: [["number"], "boolean"],
9158  FPDFPathSegment_GetPoint: [["number", "number", "number"], "boolean"],
9159  FPDFPathSegment_GetType: [["number"], "number"],
9160  FPDFSignatureObj_GetByteRange: [["number", "number", "number"], "number"],
9161  FPDFSignatureObj_GetContents: [["number", "number", "number"], "number"],
9162  FPDFSignatureObj_GetDocMDPPermission: [["number"], "number"],
9163  FPDFSignatureObj_GetReason: [["number", "number", "number"], "number"],
9164  FPDFSignatureObj_GetSubFilter: [["number", "number", "number"], "number"],
9165  FPDFSignatureObj_GetTime: [["number", "number", "number"], "number"],
9166  FPDFText_ClosePage: [["number"], null],
9167  FPDFText_CountChars: [["number"], "number"],
9168  FPDFText_CountRects: [["number", "number", "number"], "number"],
9169  FPDFText_FindClose: [["number"], null],
9170  FPDFText_FindNext: [["number"], "boolean"],
9171  FPDFText_FindPrev: [["number"], "boolean"],
9172  FPDFText_FindStart: [["number", "number", "number", "number"], "number"],
9173  FPDFText_GetBoundedText: [
9174    ["number", "number", "number", "number", "number", "number", "number"],
9175    "number"
9176  ],
9177  FPDFText_GetCharAngle: [["number", "number"], "number"],
9178  FPDFText_GetCharBox: [
9179    ["number", "number", "number", "number", "number", "number"],
9180    "boolean"
9181  ],
9182  FPDFText_GetCharIndexAtPos: [
9183    ["number", "number", "number", "number", "number"],
9184    "number"
9185  ],
9186  FPDFText_GetCharIndexFromTextIndex: [["number", "number"], "number"],
9187  FPDFText_GetCharOrigin: [["number", "number", "number", "number"], "boolean"],
9188  FPDFText_GetFillColor: [
9189    ["number", "number", "number", "number", "number", "number"],
9190    "boolean"
9191  ],
9192  FPDFText_GetFontInfo: [
9193    ["number", "number", "number", "number", "number"],
9194    "number"
9195  ],
9196  FPDFText_GetFontSize: [["number", "number"], "number"],
9197  FPDFText_GetFontWeight: [["number", "number"], "number"],
9198  FPDFText_GetLooseCharBox: [["number", "number", "number"], "boolean"],
9199  FPDFText_GetMatrix: [["number", "number", "number"], "boolean"],
9200  FPDFText_GetRect: [
9201    ["number", "number", "number", "number", "number", "number"],
9202    "boolean"
9203  ],
9204  FPDFText_GetSchCount: [["number"], "number"],
9205  FPDFText_GetSchResultIndex: [["number"], "number"],
9206  FPDFText_GetStrokeColor: [
9207    ["number", "number", "number", "number", "number", "number"],
9208    "boolean"
9209  ],
9210  FPDFText_GetText: [["number", "number", "number", "number"], "number"],
9211  FPDFText_GetTextIndexFromCharIndex: [["number", "number"], "number"],
9212  FPDFText_GetTextObject: [["number", "number"], "number"],
9213  FPDFText_GetUnicode: [["number", "number"], "number"],
9214  FPDFText_HasUnicodeMapError: [["number", "number"], "number"],
9215  FPDFText_IsGenerated: [["number", "number"], "number"],
9216  FPDFText_IsHyphen: [["number", "number"], "number"],
9217  FPDFText_LoadCidType2Font: [
9218    ["number", "number", "number", "string", "number", "number"],
9219    "number"
9220  ],
9221  FPDFText_LoadFont: [
9222    ["number", "number", "number", "number", "boolean"],
9223    "number"
9224  ],
9225  FPDFText_LoadPage: [["number"], "number"],
9226  FPDFText_LoadStandardFont: [["number", "string"], "number"],
9227  FPDFText_SetCharcodes: [["number", "number", "number"], "boolean"],
9228  FPDFText_SetText: [["number", "number"], "boolean"],
9229  FPDFTextObj_GetFont: [["number"], "number"],
9230  FPDFTextObj_GetFontSize: [["number", "number"], "boolean"],
9231  FPDFTextObj_GetRenderedBitmap: [
9232    ["number", "number", "number", "number"],
9233    "number"
9234  ],
9235  FPDFTextObj_GetText: [["number", "number", "number", "number"], "number"],
9236  FPDFTextObj_GetTextRenderMode: [["number"], "number"],
9237  FPDFTextObj_SetTextRenderMode: [["number", "number"], "boolean"],
9238  PDFiumExt_CloseFileWriter: [["number"], null],
9239  PDFiumExt_CloseFormFillInfo: [["number"], null],
9240  PDFiumExt_ExitFormFillEnvironment: [["number"], null],
9241  PDFiumExt_GetFileWriterData: [["number", "number", "number"], "number"],
9242  PDFiumExt_GetFileWriterSize: [["number"], "number"],
9243  PDFiumExt_Init: [[], null],
9244  PDFiumExt_InitFormFillEnvironment: [["number", "number"], "number"],
9245  PDFiumExt_OpenFileWriter: [[], "number"],
9246  PDFiumExt_OpenFormFillInfo: [[], "number"],
9247  PDFiumExt_SaveAsCopy: [["number", "number"], "number"]
9248};
9249async function createWrappedModule(pdfium) {
9250  const module = {
9251    pdfium
9252  };
9253  for (const key in functions) {
9254    const ident = key;
9255    const args = functions[ident][0];
9256    const ret = functions[ident][1];
9257    module[ident] = pdfium.cwrap(key, ret, args);
9258  }
9259  return module;
9260}
9261async function init(moduleOverrides) {
9262  const pdfium = await createPdfium(moduleOverrides);
9263  return createWrappedModule(pdfium);
9264}
9265function readString(wasmModule, readChars, parseChars, defaultLength = 100) {
9266  let buffer = wasmModule.wasmExports.malloc(defaultLength);
9267  for (let i = 0; i < defaultLength; i++) {
9268    wasmModule.HEAP8[buffer + i] = 0;
9269  }
9270  const actualLength = readChars(buffer, defaultLength);
9271  let str;
9272  if (actualLength > defaultLength) {
9273    wasmModule.wasmExports.free(buffer);
9274    buffer = wasmModule.wasmExports.malloc(actualLength);
9275    for (let i = 0; i < actualLength; i++) {
9276      wasmModule.HEAP8[buffer + i] = 0;
9277    }
9278    readChars(buffer, actualLength);
9279    str = parseChars(buffer);
9280  } else {
9281    str = parseChars(buffer);
9282  }
9283  wasmModule.wasmExports.free(buffer);
9284  return str;
9285}
9286function readArrayBuffer(wasmModule, readChars) {
9287  const bufferSize = readChars(0, 0);
9288  const bufferPtr = wasmModule.wasmExports.malloc(bufferSize);
9289  readChars(bufferPtr, bufferSize);
9290  const arrayBuffer = new ArrayBuffer(bufferSize);
9291  const view = new DataView(arrayBuffer);
9292  for (let i = 0; i < bufferSize; i++) {
9293    view.setInt8(i, wasmModule.getValue(bufferPtr + i, "i8"));
9294  }
9295  wasmModule.wasmExports.free(bufferPtr);
9296  return arrayBuffer;
9297}
9298const RESERVED_INFO_KEYS = /* @__PURE__ */ new Set([
9299  "Title",
9300  "Author",
9301  "Subject",
9302  "Keywords",
9303  "Producer",
9304  "Creator",
9305  "CreationDate",
9306  "ModDate",
9307  "Trapped"
9308]);
9309function isValidCustomKey(key) {
9310  if (!key || key.length > 127) return false;
9311  if (RESERVED_INFO_KEYS.has(key)) return false;
9312  if (key[0] === "/") return false;
9313  for (let i = 0; i < key.length; i++) {
9314    const c = key.charCodeAt(i);
9315    if (c < 32 || c > 126) return false;
9316  }
9317  return true;
9318}
9319function computeFormDrawParams(matrix, rect, pageSize, rotation) {
9320  const rectLeft = rect.origin.x;
9321  const rectBottom = rect.origin.y;
9322  const rectRight = rectLeft + rect.size.width;
9323  const rectTop = rectBottom + rect.size.height;
9324  const pageWidth = pageSize.width;
9325  const pageHeight = pageSize.height;
9326  const scaleX = Math.hypot(matrix.a, matrix.b);
9327  const scaleY = Math.hypot(matrix.c, matrix.d);
9328  const swap2 = (rotation & 1) === 1;
9329  const formsWidth = swap2 ? Math.max(1, Math.round(pageHeight * scaleX)) : Math.max(1, Math.round(pageWidth * scaleX));
9330  const formsHeight = swap2 ? Math.max(1, Math.round(pageWidth * scaleY)) : Math.max(1, Math.round(pageHeight * scaleY));
9331  let startX;
9332  let startY;
9333  switch (rotation) {
9334    case Rotation.Degree0:
9335      startX = -Math.round(rectLeft * scaleX);
9336      startY = -Math.round(rectBottom * scaleY);
9337      break;
9338    case Rotation.Degree90:
9339      startX = Math.round((rectTop - pageHeight) * scaleX);
9340      startY = -Math.round(rectLeft * scaleY);
9341      break;
9342    case Rotation.Degree180:
9343      startX = Math.round((rectRight - pageWidth) * scaleX);
9344      startY = Math.round((rectTop - pageHeight) * scaleY);
9345      break;
9346    case Rotation.Degree270:
9347      startX = -Math.round(rectBottom * scaleX);
9348      startY = Math.round((rectRight - pageWidth) * scaleY);
9349      break;
9350    default:
9351      startX = -Math.round(rectLeft * scaleX);
9352      startY = -Math.round(rectBottom * scaleY);
9353      break;
9354  }
9355  return { startX, startY, formsWidth, formsHeight, scaleX, scaleY };
9356}
9357const WasmPointer = (ptr) => ptr;
9358const DEFAULT_CONFIG = {
9359  pageTtl: 5e3,
9360  // 5 seconds
9361  maxPagesPerDocument: 10,
9362  normalizeRotation: false
9363};
9364class PdfCache {
9365  constructor(pdfium, memoryManager, config = {}) {
9366    this.pdfium = pdfium;
9367    this.memoryManager = memoryManager;
9368    this.docs = /* @__PURE__ */ new Map();
9369    this.config = { ...DEFAULT_CONFIG, ...config };
9370  }
9371  /** Open (or re-use) a document */
9372  setDocument(id, filePtr, docPtr, normalizeRotation = false) {
9373    let ctx = this.docs.get(id);
9374    if (!ctx) {
9375      const docConfig = { ...this.config, normalizeRotation };
9376      ctx = new DocumentContext(filePtr, docPtr, this.pdfium, this.memoryManager, docConfig);
9377      this.docs.set(id, ctx);
9378    }
9379  }
9380  /** Retrieve the DocumentContext for a given PdfDocumentObject */
9381  getContext(docId) {
9382    return this.docs.get(docId);
9383  }
9384  /** Close & fully release a document and all its pages */
9385  closeDocument(docId) {
9386    const ctx = this.docs.get(docId);
9387    if (!ctx) return false;
9388    this.docs.delete(docId);
9389    ctx.dispose();
9390    return true;
9391  }
9392  /** Close all documents */
9393  closeAllDocuments() {
9394    for (const ctx of this.docs.values()) {
9395      ctx.dispose();
9396    }
9397    this.docs.clear();
9398  }
9399  /** Update cache configuration for all existing documents */
9400  updateConfig(newConfig) {
9401    Object.assign(this.config, newConfig);
9402    for (const ctx of this.docs.values()) {
9403      ctx.updateConfig(this.config);
9404    }
9405  }
9406  /** Get current cache statistics */
9407  getCacheStats() {
9408    const pagesByDocument = {};
9409    let totalPages = 0;
9410    for (const [docId, ctx] of this.docs.entries()) {
9411      const pageCount = ctx.getCacheSize();
9412      pagesByDocument[docId] = pageCount;
9413      totalPages += pageCount;
9414    }
9415    return {
9416      documents: this.docs.size,
9417      totalPages,
9418      pagesByDocument
9419    };
9420  }
9421}
9422class DocumentContext {
9423  constructor(filePtr, docPtr, pdfium, memoryManager, config) {
9424    this.filePtr = filePtr;
9425    this.docPtr = docPtr;
9426    this.memoryManager = memoryManager;
9427    this.disposed = false;
9428    this.normalizeRotation = config.normalizeRotation;
9429    this.pageCache = new PageCache(pdfium, docPtr, config);
9430  }
9431  /** Main accessor for pages */
9432  acquirePage(pageIdx) {
9433    return this.pageCache.acquire(pageIdx);
9434  }
9435  /** Scoped accessor for one-off / bulk operations */
9436  borrowPage(pageIdx, fn) {
9437    return this.pageCache.borrowPage(pageIdx, fn);
9438  }
9439  /** Update cache configuration */
9440  updateConfig(config) {
9441    this.pageCache.updateConfig(config);
9442  }
9443  /** Get number of pages currently in cache */
9444  getCacheSize() {
9445    return this.pageCache.size();
9446  }
9447  /** Tear down all pages + this document */
9448  dispose() {
9449    if (this.disposed) return;
9450    this.disposed = true;
9451    this.pageCache.forceReleaseAll();
9452    this.pageCache.pdf.FPDF_CloseDocument(this.docPtr);
9453    this.memoryManager.free(WasmPointer(this.filePtr));
9454  }
9455}
9456class PageCache {
9457  constructor(pdf, docPtr, config) {
9458    this.pdf = pdf;
9459    this.docPtr = docPtr;
9460    this.cache = /* @__PURE__ */ new Map();
9461    this.accessOrder = [];
9462    this.config = config;
9463  }
9464  acquire(pageIdx) {
9465    let ctx = this.cache.get(pageIdx);
9466    if (!ctx) {
9467      this.evictIfNeeded();
9468      let pagePtr;
9469      if (this.config.normalizeRotation) {
9470        pagePtr = this.pdf.EPDF_LoadPageNormalized(this.docPtr, pageIdx, 0);
9471      } else {
9472        pagePtr = this.pdf.FPDF_LoadPage(this.docPtr, pageIdx);
9473      }
9474      ctx = new PageContext(this.pdf, this.docPtr, pageIdx, pagePtr, this.config.pageTtl, () => {
9475        this.cache.delete(pageIdx);
9476        this.removeFromAccessOrder(pageIdx);
9477      });
9478      this.cache.set(pageIdx, ctx);
9479    }
9480    this.updateAccessOrder(pageIdx);
9481    ctx.clearExpiryTimer();
9482    ctx.bumpRefCount();
9483    return ctx;
9484  }
9485  /** Helper: run a function "scoped" to a page.
9486   *    – if the page was already cached  → .release() (keeps TTL logic)
9487   *    – if the page was loaded just now → .disposeImmediate() (free right away)
9488   */
9489  borrowPage(pageIdx, fn) {
9490    const existed = this.cache.has(pageIdx);
9491    const ctx = this.acquire(pageIdx);
9492    try {
9493      return fn(ctx);
9494    } finally {
9495      existed ? ctx.release() : ctx.disposeImmediate();
9496    }
9497  }
9498  forceReleaseAll() {
9499    for (const ctx of this.cache.values()) {
9500      ctx.disposeImmediate();
9501    }
9502    this.cache.clear();
9503    this.accessOrder.length = 0;
9504  }
9505  /** Update cache configuration */
9506  updateConfig(config) {
9507    this.config = config;
9508    for (const ctx of this.cache.values()) {
9509      ctx.updateTtl(config.pageTtl);
9510    }
9511    this.evictIfNeeded();
9512  }
9513  /** Get current cache size */
9514  size() {
9515    return this.cache.size;
9516  }
9517  /** Evict least recently used pages if cache exceeds max size */
9518  evictIfNeeded() {
9519    while (this.cache.size >= this.config.maxPagesPerDocument) {
9520      const lruPageIdx = this.accessOrder[0];
9521      if (lruPageIdx !== void 0) {
9522        const ctx = this.cache.get(lruPageIdx);
9523        if (ctx) {
9524          if (ctx.getRefCount() === 0) {
9525            ctx.disposeImmediate();
9526          } else {
9527            break;
9528          }
9529        } else {
9530          this.removeFromAccessOrder(lruPageIdx);
9531        }
9532      } else {
9533        break;
9534      }
9535    }
9536  }
9537  /** Update the access order for LRU tracking */
9538  updateAccessOrder(pageIdx) {
9539    this.removeFromAccessOrder(pageIdx);
9540    this.accessOrder.push(pageIdx);
9541  }
9542  /** Remove a page from the access order array */
9543  removeFromAccessOrder(pageIdx) {
9544    const index = this.accessOrder.indexOf(pageIdx);
9545    if (index > -1) {
9546      this.accessOrder.splice(index, 1);
9547    }
9548  }
9549}
9550class PageContext {
9551  constructor(pdf, docPtr, pageIdx, pagePtr, ttl, onFinalDispose) {
9552    this.pdf = pdf;
9553    this.docPtr = docPtr;
9554    this.pageIdx = pageIdx;
9555    this.pagePtr = pagePtr;
9556    this.onFinalDispose = onFinalDispose;
9557    this.refCount = 0;
9558    this.disposed = false;
9559    this.ttl = ttl;
9560  }
9561  /** Called by PageCache.acquire() */
9562  bumpRefCount() {
9563    if (this.disposed) throw new Error("Context already disposed");
9564    this.refCount++;
9565  }
9566  /** Get current reference count */
9567  getRefCount() {
9568    return this.refCount;
9569  }
9570  /** Called by PageCache.acquire() */
9571  clearExpiryTimer() {
9572    if (this.expiryTimer) {
9573      clearTimeout(this.expiryTimer);
9574      this.expiryTimer = void 0;
9575    }
9576  }
9577  /** Update TTL configuration */
9578  updateTtl(newTtl) {
9579    this.ttl = newTtl;
9580    if (this.expiryTimer && this.refCount === 0) {
9581      this.clearExpiryTimer();
9582      this.expiryTimer = setTimeout(() => this.disposeImmediate(), this.ttl);
9583    }
9584  }
9585  /** Called by PageCache.release() internally */
9586  release() {
9587    if (this.disposed) return;
9588    this.refCount--;
9589    if (this.refCount === 0) {
9590      this.expiryTimer = setTimeout(() => this.disposeImmediate(), this.ttl);
9591    }
9592  }
9593  /** Tear down _all_ sub-pointers & the page. */
9594  disposeImmediate() {
9595    if (this.disposed) return;
9596    this.disposed = true;
9597    this.clearExpiryTimer();
9598    if (this.textPagePtr !== void 0) {
9599      this.pdf.FPDFText_ClosePage(this.textPagePtr);
9600    }
9601    this.pdf.FPDF_ClosePage(this.pagePtr);
9602    this.onFinalDispose();
9603  }
9604  // ── public helpers ──
9605  /** Always safe: opens (once) and returns the text-page ptr. */
9606  getTextPage() {
9607    this.ensureAlive();
9608    if (this.textPagePtr === void 0) {
9609      this.textPagePtr = this.pdf.FPDFText_LoadPage(this.pagePtr);
9610    }
9611    return this.textPagePtr;
9612  }
9613  /**
9614   * Safely execute \`fn\` with an annotation pointer.
9615   * Pointer is ALWAYS closed afterwards.
9616   */
9617  withAnnotation(annotIdx, fn) {
9618    this.ensureAlive();
9619    const annotPtr = this.pdf.FPDFPage_GetAnnot(this.pagePtr, annotIdx);
9620    try {
9621      return fn(annotPtr);
9622    } finally {
9623      this.pdf.FPDFPage_CloseAnnot(annotPtr);
9624    }
9625  }
9626  /**
9627   * Safely execute \`fn\` with a fresh form-fill handle.
9628   * Handle is ALWAYS torn down afterwards — no caching, no stale state.
9629   */
9630  withFormHandle(fn) {
9631    this.ensureAlive();
9632    const formInfoPtr = this.pdf.PDFiumExt_OpenFormFillInfo();
9633    const formHandle = this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr, formInfoPtr);
9634    this.pdf.FORM_OnAfterLoadPage(this.pagePtr, formHandle);
9635    try {
9636      return fn(formHandle);
9637    } finally {
9638      this.pdf.FORM_OnBeforeClosePage(this.pagePtr, formHandle);
9639      this.pdf.PDFiumExt_ExitFormFillEnvironment(formHandle);
9640      this.pdf.PDFiumExt_CloseFormFillInfo(formInfoPtr);
9641    }
9642  }
9643  ensureAlive() {
9644    if (this.disposed) throw new Error("PageContext already disposed");
9645  }
9646}
9647const MEMORY_LIMITS = {
9648  /** Maximum total memory that can be allocated (2GB) */
9649  MAX_TOTAL_MEMORY: 2 * 1024 * 1024 * 1024
9650};
9651const LIMITS = {
9652  MEMORY: MEMORY_LIMITS
9653};
9654const LOG_SOURCE$3 = "PDFiumEngine";
9655const LOG_CATEGORY$3 = "MemoryManager";
9656class MemoryManager {
9657  constructor(pdfiumModule, logger) {
9658    this.pdfiumModule = pdfiumModule;
9659    this.logger = logger;
9660    this.allocations = /* @__PURE__ */ new Map();
9661    this.totalAllocated = 0;
9662  }
9663  /**
9664   * Allocate memory with tracking and validation
9665   */
9666  malloc(size) {
9667    if (this.totalAllocated + size > LIMITS.MEMORY.MAX_TOTAL_MEMORY) {
9668      throw new Error(
9669        \`Total memory usage would exceed limit: \${this.totalAllocated + size} > \${LIMITS.MEMORY.MAX_TOTAL_MEMORY}\`
9670      );
9671    }
9672    const ptr = this.pdfiumModule.pdfium.wasmExports.malloc(size);
9673    if (!ptr) {
9674      throw new Error(\`Failed to allocate \${size} bytes\`);
9675    }
9676    const allocation = {
9677      ptr: WasmPointer(ptr),
9678      size,
9679      timestamp: Date.now(),
9680      stack: this.logger.isEnabled("debug") ? new Error().stack : void 0
9681    };
9682    this.allocations.set(ptr, allocation);
9683    this.totalAllocated += size;
9684    return WasmPointer(ptr);
9685  }
9686  /**
9687   * Free memory with validation
9688   */
9689  free(ptr) {
9690    const allocation = this.allocations.get(ptr);
9691    if (!allocation) {
9692      this.logger.warn(LOG_SOURCE$3, LOG_CATEGORY$3, \`Freeing untracked pointer: \${ptr}\`);
9693    } else {
9694      this.totalAllocated -= allocation.size;
9695      this.allocations.delete(ptr);
9696    }
9697    this.pdfiumModule.pdfium.wasmExports.free(ptr);
9698  }
9699  /**
9700   * Get memory statistics
9701   */
9702  getStats() {
9703    return {
9704      totalAllocated: this.totalAllocated,
9705      allocationCount: this.allocations.size,
9706      allocations: this.logger.isEnabled("debug") ? Array.from(this.allocations.values()) : []
9707    };
9708  }
9709  /**
9710   * Check for memory leaks
9711   */
9712  checkLeaks() {
9713    if (this.allocations.size > 0) {
9714      this.logger.warn(
9715        LOG_SOURCE$3,
9716        LOG_CATEGORY$3,
9717        \`Potential memory leak: \${this.allocations.size} unfreed allocations\`
9718      );
9719      for (const [ptr, alloc] of this.allocations) {
9720        this.logger.warn(LOG_SOURCE$3, LOG_CATEGORY$3, \`  - \${ptr}: \${alloc.size} bytes\`, alloc.stack);
9721      }
9722    }
9723  }
9724}
9725const SYSFONTINFO_SIZE = 36;
9726const OFFSET_VERSION = 0;
9727const OFFSET_RELEASE = 4;
9728const OFFSET_ENUMFONTS = 8;
9729const OFFSET_MAPFONT = 12;
9730const OFFSET_GETFONT = 16;
9731const OFFSET_GETFONTDATA = 20;
9732const OFFSET_GETFACENAME = 24;
9733const OFFSET_GETFONTCHARSET = 28;
9734const OFFSET_DELETEFONT = 32;
9735const LOG_SOURCE$2 = "pdfium";
9736const LOG_CATEGORY$2 = "font-fallback";
9737class FontFallbackManager {
9738  constructor(config, logger = new NoopLogger()) {
9739    this.fontHandles = /* @__PURE__ */ new Map();
9740    this.fontCache = /* @__PURE__ */ new Map();
9741    this.nextHandleId = 1;
9742    this.module = null;
9743    this.enabled = false;
9744    this.structPtr = 0;
9745    this.releaseFnPtr = 0;
9746    this.enumFontsFnPtr = 0;
9747    this.mapFontFnPtr = 0;
9748    this.getFontFnPtr = 0;
9749    this.getFontDataFnPtr = 0;
9750    this.getFaceNameFnPtr = 0;
9751    this.getFontCharsetFnPtr = 0;
9752    this.deleteFontFnPtr = 0;
9753    this.fontConfig = config;
9754    this.logger = logger;
9755  }
9756  /**
9757   * Initialize the font fallback system and attach to PDFium module
9758   */
9759  initialize(module) {
9760    if (this.enabled) {
9761      this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, "Font fallback already initialized");
9762      return;
9763    }
9764    this.module = module;
9765    const pdfium = module.pdfium;
9766    if (typeof pdfium.addFunction !== "function") {
9767      this.logger.error(
9768        LOG_SOURCE$2,
9769        LOG_CATEGORY$2,
9770        "addFunction not available. Make sure WASM is compiled with -sALLOW_TABLE_GROWTH"
9771      );
9772      return;
9773    }
9774    try {
9775      this.structPtr = pdfium.wasmExports.malloc(SYSFONTINFO_SIZE);
9776      if (!this.structPtr) {
9777        throw new Error("Failed to allocate FPDF_SYSFONTINFO struct");
9778      }
9779      for (let i = 0; i < SYSFONTINFO_SIZE; i++) {
9780        pdfium.setValue(this.structPtr + i, 0, "i8");
9781      }
9782      this.releaseFnPtr = pdfium.addFunction((_pThis) => {
9783      }, "vi");
9784      this.enumFontsFnPtr = pdfium.addFunction((_pThis, _pMapper) => {
9785      }, "vii");
9786      this.mapFontFnPtr = pdfium.addFunction(
9787        (_pThis, weight, bItalic, charset, pitchFamily, facePtr, bExactPtr) => {
9788          const face = facePtr ? pdfium.UTF8ToString(facePtr) : "";
9789          const handle = this.mapFont(weight, bItalic, charset, pitchFamily, face);
9790          if (bExactPtr) {
9791            pdfium.setValue(bExactPtr, 0, "i32");
9792          }
9793          return handle;
9794        },
9795        "iiiiiiii"
9796      );
9797      this.getFontFnPtr = pdfium.addFunction((_pThis, facePtr) => {
9798        const face = facePtr ? pdfium.UTF8ToString(facePtr) : "";
9799        return this.mapFont(400, 0, 0, 0, face);
9800      }, "iii");
9801      this.getFontDataFnPtr = pdfium.addFunction(
9802        (_pThis, hFont, table, buffer, bufSize) => {
9803          return this.getFontData(hFont, table, buffer, bufSize);
9804        },
9805        "iiiiii"
9806      );
9807      this.getFaceNameFnPtr = pdfium.addFunction(
9808        (_pThis, _hFont, _buffer, _bufSize) => {
9809          return 0;
9810        },
9811        "iiiii"
9812      );
9813      this.getFontCharsetFnPtr = pdfium.addFunction((_pThis, hFont) => {
9814        const handle = this.fontHandles.get(hFont);
9815        return (handle == null ? void 0 : handle.charset) ?? 0;
9816      }, "iii");
9817      this.deleteFontFnPtr = pdfium.addFunction((_pThis, hFont) => {
9818        this.deleteFont(hFont);
9819      }, "vii");
9820      pdfium.setValue(this.structPtr + OFFSET_VERSION, 1, "i32");
9821      pdfium.setValue(this.structPtr + OFFSET_RELEASE, this.releaseFnPtr, "i32");
9822      pdfium.setValue(this.structPtr + OFFSET_ENUMFONTS, this.enumFontsFnPtr, "i32");
9823      pdfium.setValue(this.structPtr + OFFSET_MAPFONT, this.mapFontFnPtr, "i32");
9824      pdfium.setValue(this.structPtr + OFFSET_GETFONT, this.getFontFnPtr, "i32");
9825      pdfium.setValue(this.structPtr + OFFSET_GETFONTDATA, this.getFontDataFnPtr, "i32");
9826      pdfium.setValue(this.structPtr + OFFSET_GETFACENAME, this.getFaceNameFnPtr, "i32");
9827      pdfium.setValue(this.structPtr + OFFSET_GETFONTCHARSET, this.getFontCharsetFnPtr, "i32");
9828      pdfium.setValue(this.structPtr + OFFSET_DELETEFONT, this.deleteFontFnPtr, "i32");
9829      module.FPDF_SetSystemFontInfo(this.structPtr);
9830      this.enabled = true;
9831      this.logger.info(
9832        LOG_SOURCE$2,
9833        LOG_CATEGORY$2,
9834        "Font fallback system initialized (pure TypeScript)",
9835        Object.keys(this.fontConfig.fonts)
9836      );
9837    } catch (error) {
9838      this.logger.error(LOG_SOURCE$2, LOG_CATEGORY$2, "Failed to initialize font fallback", error);
9839      this.cleanup();
9840      throw error;
9841    }
9842  }
9843  /**
9844   * Disable the font fallback system and clean up resources
9845   */
9846  disable() {
9847    if (!this.enabled || !this.module) {
9848      return;
9849    }
9850    this.module.FPDF_SetSystemFontInfo(0);
9851    this.cleanup();
9852    this.enabled = false;
9853    this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, "Font fallback system disabled");
9854  }
9855  /**
9856   * Clean up allocated resources
9857   */
9858  cleanup() {
9859    if (!this.module) return;
9860    const pdfium = this.module.pdfium;
9861    if (this.structPtr) {
9862      pdfium.wasmExports.free(this.structPtr);
9863      this.structPtr = 0;
9864    }
9865    const removeIfExists = (ptr) => {
9866      if (ptr && typeof pdfium.removeFunction === "function") {
9867        try {
9868          pdfium.removeFunction(ptr);
9869        } catch {
9870        }
9871      }
9872    };
9873    removeIfExists(this.releaseFnPtr);
9874    removeIfExists(this.enumFontsFnPtr);
9875    removeIfExists(this.mapFontFnPtr);
9876    removeIfExists(this.getFontFnPtr);
9877    removeIfExists(this.getFontDataFnPtr);
9878    removeIfExists(this.getFaceNameFnPtr);
9879    removeIfExists(this.getFontCharsetFnPtr);
9880    removeIfExists(this.deleteFontFnPtr);
9881    this.releaseFnPtr = 0;
9882    this.enumFontsFnPtr = 0;
9883    this.mapFontFnPtr = 0;
9884    this.getFontFnPtr = 0;
9885    this.getFontDataFnPtr = 0;
9886    this.getFaceNameFnPtr = 0;
9887    this.getFontCharsetFnPtr = 0;
9888    this.deleteFontFnPtr = 0;
9889  }
9890  /**
9891   * Check if font fallback is enabled
9892   */
9893  isEnabled() {
9894    return this.enabled;
9895  }
9896  /**
9897   * Get statistics about font loading
9898   */
9899  getStats() {
9900    return {
9901      handleCount: this.fontHandles.size,
9902      cacheSize: this.fontCache.size,
9903      cachedUrls: Array.from(this.fontCache.keys())
9904    };
9905  }
9906  /**
9907   * Pre-load fonts for specific charsets (optional optimization)
9908   * This can be called to warm the cache before rendering
9909   */
9910  async preloadFonts(charsets) {
9911    const urls = charsets.map((charset) => this.getFontUrlForCharset(charset)).filter((url) => url !== null);
9912    const uniqueUrls = [...new Set(urls)];
9913    await Promise.all(
9914      uniqueUrls.map(async (url) => {
9915        if (!this.fontCache.has(url)) {
9916          try {
9917            const data = await this.fetchFontAsync(url);
9918            if (data) {
9919              this.fontCache.set(url, data);
9920              this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, \`Pre-loaded font: \${url}\`);
9921            }
9922          } catch (error) {
9923            this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, \`Failed to pre-load font: \${url}\`, error);
9924          }
9925        }
9926      })
9927    );
9928  }
9929  // ============================================================================
9930  // PDFium Callback Implementations
9931  // ============================================================================
9932  /**
9933   * MapFont - called by PDFium when it needs a font
9934   */
9935  mapFont(weight, bItalic, charset, pitchFamily, face) {
9936    const italic = bItalic !== 0;
9937    this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, "MapFont called", {
9938      weight,
9939      italic,
9940      charset,
9941      pitchFamily,
9942      face
9943    });
9944    const result = this.findBestFontMatch(charset, weight, italic);
9945    if (!result) {
9946      this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, \`No font configured for charset \${charset}\`);
9947      return 0;
9948    }
9949    const handle = {
9950      id: this.nextHandleId++,
9951      charset,
9952      weight,
9953      italic,
9954      url: result.url,
9955      data: null
9956    };
9957    this.fontHandles.set(handle.id, handle);
9958    this.logger.debug(
9959      LOG_SOURCE$2,
9960      LOG_CATEGORY$2,
9961      \`Created font handle \${handle.id} for \${result.url} (requested: weight=\${weight}, italic=\${italic}, matched: weight=\${result.matchedWeight}, italic=\${result.matchedItalic})\`
9962    );
9963    return handle.id;
9964  }
9965  /**
9966   * GetFontData - called by PDFium to get font bytes
9967   */
9968  getFontData(fontHandle, table, bufferPtr, bufSize) {
9969    const handle = this.fontHandles.get(fontHandle);
9970    if (!handle) {
9971      this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, \`Unknown font handle: \${fontHandle}\`);
9972      return 0;
9973    }
9974    if (!handle.data) {
9975      if (this.fontCache.has(handle.url)) {
9976        handle.data = this.fontCache.get(handle.url);
9977      } else {
9978        handle.data = this.fetchFontSync(handle.url);
9979        if (handle.data) {
9980          this.fontCache.set(handle.url, handle.data);
9981        }
9982      }
9983    }
9984    if (!handle.data) {
9985      this.logger.warn(LOG_SOURCE$2, LOG_CATEGORY$2, \`Failed to load font: \${handle.url}\`);
9986      return 0;
9987    }
9988    const fontData = handle.data;
9989    if (table !== 0) {
9990      this.logger.debug(
9991        LOG_SOURCE$2,
9992        LOG_CATEGORY$2,
9993        \`Table \${table} requested - returning 0 to request whole file\`
9994      );
9995      return 0;
9996    }
9997    if (bufferPtr === 0 || bufSize < fontData.length) {
9998      return fontData.length;
9999    }
10000    if (this.module) {
10001      const heap = this.module.pdfium.HEAPU8;
10002      heap.set(fontData, bufferPtr);
10003      this.logger.debug(
10004        LOG_SOURCE$2,
10005        LOG_CATEGORY$2,
10006        \`Copied \${fontData.length} bytes to buffer for handle \${fontHandle}\`
10007      );
10008    }
10009    return fontData.length;
10010  }
10011  /**
10012   * DeleteFont - called by PDFium when done with a font
10013   */
10014  deleteFont(fontHandle) {
10015    const handle = this.fontHandles.get(fontHandle);
10016    if (handle) {
10017      this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, \`Deleting font handle \${fontHandle}\`);
10018      this.fontHandles.delete(fontHandle);
10019    }
10020  }
10021  // ============================================================================
10022  // Helper Methods
10023  // ============================================================================
10024  /**
10025   * Find the best matching font variant for the given parameters
10026   */
10027  findBestFontMatch(charset, requestedWeight, requestedItalic) {
10028    const { fonts: fonts2, defaultFont, baseUrl } = this.fontConfig;
10029    const entry = fonts2[charset] ?? defaultFont;
10030    if (!entry) {
10031      return null;
10032    }
10033    const variants = this.normalizeToVariants(entry);
10034    if (variants.length === 0) {
10035      return null;
10036    }
10037    const best = this.selectBestVariant(variants, requestedWeight, requestedItalic);
10038    let url = best.url;
10039    if (baseUrl && !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("/")) {
10040      url = \`\${baseUrl}/\${url}\`;
10041    }
10042    return {
10043      url,
10044      matchedWeight: best.weight ?? 400,
10045      matchedItalic: best.italic ?? false
10046    };
10047  }
10048  /**
10049   * Normalize a FontEntry to an array of FontVariants
10050   */
10051  normalizeToVariants(entry) {
10052    if (typeof entry === "string") {
10053      return [{ url: entry, weight: 400, italic: false }];
10054    }
10055    if (Array.isArray(entry)) {
10056      return entry.map((v) => ({
10057        url: v.url,
10058        weight: v.weight ?? 400,
10059        italic: v.italic ?? false
10060      }));
10061    }
10062    return [{ url: entry.url, weight: entry.weight ?? 400, italic: entry.italic ?? false }];
10063  }
10064  /**
10065   * Select the best matching variant based on weight and italic
10066   * Uses CSS font matching algorithm principles:
10067   * 1. Exact italic match preferred
10068   * 2. Closest weight (with bias toward bolder for weights >= 400)
10069   */
10070  selectBestVariant(variants, requestedWeight, requestedItalic) {
10071    if (variants.length === 1) {
10072      return variants[0];
10073    }
10074    const italicMatches = variants.filter((v) => (v.italic ?? false) === requestedItalic);
10075    const candidates = italicMatches.length > 0 ? italicMatches : variants;
10076    let bestMatch = candidates[0];
10077    let bestDistance = Math.abs((bestMatch.weight ?? 400) - requestedWeight);
10078    for (const variant of candidates) {
10079      const variantWeight = variant.weight ?? 400;
10080      const distance = Math.abs(variantWeight - requestedWeight);
10081      if (distance < bestDistance) {
10082        bestMatch = variant;
10083        bestDistance = distance;
10084      } else if (distance === bestDistance) {
10085        const currentWeight = bestMatch.weight ?? 400;
10086        if (requestedWeight >= 500) {
10087          if (variantWeight > currentWeight) {
10088            bestMatch = variant;
10089          }
10090        } else {
10091          if (variantWeight < currentWeight) {
10092            bestMatch = variant;
10093          }
10094        }
10095      }
10096    }
10097    return bestMatch;
10098  }
10099  /**
10100   * Get font URL for a charset (backward compatible helper)
10101   */
10102  getFontUrlForCharset(charset) {
10103    const result = this.findBestFontMatch(charset, 400, false);
10104    return (result == null ? void 0 : result.url) ?? null;
10105  }
10106  /**
10107   * Fetch font data synchronously
10108   * Uses custom fontLoader if provided, otherwise falls back to XMLHttpRequest (browser)
10109   */
10110  fetchFontSync(pathOrUrl) {
10111    this.logger.debug(LOG_SOURCE$2, LOG_CATEGORY$2, \`Fetching font synchronously: \${pathOrUrl}\`);
10112    if (this.fontConfig.fontLoader) {
10113      try {
10114        const data = this.fontConfig.fontLoader(pathOrUrl);
10115        if (data) {
10116          this.logger.info(
10117            LOG_SOURCE$2,
10118            LOG_CATEGORY$2,
10119            \`Loaded font via custom loader: \${pathOrUrl} (\${data.length} bytes)\`
10120          );
10121        } else {
10122          this.logger.warn(
10123            LOG_SOURCE$2,
10124            LOG_CATEGORY$2,
10125            \`Custom font loader returned null for: \${pathOrUrl}\`
10126          );
10127        }
10128        return data;
10129      } catch (error) {
10130        this.logger.error(
10131          LOG_SOURCE$2,
10132          LOG_CATEGORY$2,
10133          \`Error in custom font loader: \${pathOrUrl}\`,
10134          error
10135        );
10136        return null;
10137      }
10138    }
10139    try {
10140      const xhr = new XMLHttpRequest();
10141      xhr.open("GET", pathOrUrl, false);
10142      xhr.responseType = "arraybuffer";
10143      xhr.send();
10144      if (xhr.status === 200) {
10145        const data = new Uint8Array(xhr.response);
10146        this.logger.info(
10147          LOG_SOURCE$2,
10148          LOG_CATEGORY$2,
10149          \`Loaded font: \${pathOrUrl} (\${data.length} bytes)\`
10150        );
10151        return data;
10152      } else {
10153        this.logger.error(
10154          LOG_SOURCE$2,
10155          LOG_CATEGORY$2,
10156          \`Failed to load font: \${pathOrUrl} (HTTP \${xhr.status})\`
10157        );
10158        return null;
10159      }
10160    } catch (error) {
10161      this.logger.error(LOG_SOURCE$2, LOG_CATEGORY$2, \`Error fetching font: \${pathOrUrl}\`, error);
10162      return null;
10163    }
10164  }
10165  /**
10166   * Fetch font data asynchronously (for preloading)
10167   * Uses custom fontLoader if provided, otherwise falls back to fetch API
10168   */
10169  async fetchFontAsync(pathOrUrl) {
10170    if (this.fontConfig.fontLoader) {
10171      try {
10172        return this.fontConfig.fontLoader(pathOrUrl);
10173      } catch {
10174        return null;
10175      }
10176    }
10177    try {
10178      const response = await fetch(pathOrUrl);
10179      if (response.ok) {
10180        const buffer = await response.arrayBuffer();
10181        return new Uint8Array(buffer);
10182      }
10183      return null;
10184    } catch {
10185      return null;
10186    }
10187  }
10188}
10189const LOG_SOURCE$1 = "PDFiumEngine";
10190const LOG_CATEGORY$1 = "Engine";
10191class PdfiumNative {
10192  /**
10193   * Create an instance of PdfiumNative and initialize PDFium
10194   * @param wasmModule - pdfium wasm module
10195   * @param options - configuration options
10196   */
10197  constructor(pdfiumModule, options = {}) {
10198    this.pdfiumModule = pdfiumModule;
10199    this.memoryLeakCheckInterval = null;
10200    this.fontFallbackManager = null;
10201    const { logger = new NoopLogger(), fontFallback } = options;
10202    this.logger = logger;
10203    this.memoryManager = new MemoryManager(this.pdfiumModule, this.logger);
10204    this.cache = new PdfCache(this.pdfiumModule, this.memoryManager);
10205    if (this.logger.isEnabled("debug")) {
10206      this.memoryLeakCheckInterval = setInterval(() => {
10207        this.memoryManager.checkLeaks();
10208      }, 1e4);
10209    }
10210    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "initialize");
10211    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Initialize\`, "Begin", "General");
10212    this.pdfiumModule.PDFiumExt_Init();
10213    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Initialize\`, "End", "General");
10214    if (fontFallback) {
10215      this.fontFallbackManager = new FontFallbackManager(fontFallback, this.logger);
10216      this.fontFallbackManager.initialize(this.pdfiumModule);
10217      this.logger.info(LOG_SOURCE$1, LOG_CATEGORY$1, "Font fallback system enabled");
10218    }
10219  }
10220  /**
10221   * {@inheritDoc @embedpdf/models!PdfEngine.destroy}
10222   *
10223   * @public
10224   */
10225  destroy() {
10226    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "destroy");
10227    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Destroy\`, "Begin", "General");
10228    if (this.fontFallbackManager) {
10229      this.fontFallbackManager.disable();
10230      this.fontFallbackManager = null;
10231    }
10232    this.pdfiumModule.FPDF_DestroyLibrary();
10233    if (this.memoryLeakCheckInterval) {
10234      clearInterval(this.memoryLeakCheckInterval);
10235      this.memoryLeakCheckInterval = null;
10236    }
10237    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Destroy\`, "End", "General");
10238    return PdfTaskHelper.resolve(true);
10239  }
10240  /**
10241   * Get the font fallback manager instance
10242   * Useful for pre-loading fonts or checking stats
10243   */
10244  getFontFallbackManager() {
10245    return this.fontFallbackManager;
10246  }
10247  /** Write a UTF-16LE (WIDESTRING) to wasm, call \`fn(ptr)\`, then free. */
10248  withWString(value, fn) {
10249    const length = (value.length + 1) * 2;
10250    const ptr = this.memoryManager.malloc(length);
10251    try {
10252      this.pdfiumModule.pdfium.stringToUTF16(value, ptr, length);
10253      return fn(ptr);
10254    } finally {
10255      this.memoryManager.free(ptr);
10256    }
10257  }
10258  /** Write a float[] to wasm, call \`fn(ptr, count)\`, then free. */
10259  withFloatArray(values, fn) {
10260    const arr = values ?? [];
10261    const bytes = arr.length * 4;
10262    const ptr = bytes ? this.memoryManager.malloc(bytes) : WasmPointer(0);
10263    try {
10264      if (bytes) {
10265        for (let i = 0; i < arr.length; i++) {
10266          this.pdfiumModule.pdfium.setValue(ptr + i * 4, arr[i], "float");
10267        }
10268      }
10269      return fn(ptr, arr.length);
10270    } finally {
10271      if (bytes) this.memoryManager.free(ptr);
10272    }
10273  }
10274  /**
10275   * {@inheritDoc @embedpdf/models!PdfEngine.openDocument}
10276   *
10277   * @public
10278   */
10279  openDocumentBuffer(file, options) {
10280    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "openDocumentBuffer", file, options);
10281    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`OpenDocumentBuffer\`, "Begin", file.id);
10282    const normalizeRotation = (options == null ? void 0 : options.normalizeRotation) ?? false;
10283    const array = new Uint8Array(file.content);
10284    const length = array.length;
10285    const filePtr = this.memoryManager.malloc(length);
10286    this.pdfiumModule.pdfium.HEAPU8.set(array, filePtr);
10287    const docPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, length, (options == null ? void 0 : options.password) ?? "");
10288    if (!docPtr) {
10289      const lastError = this.pdfiumModule.FPDF_GetLastError();
10290      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, \`FPDF_LoadMemDocument failed with \${lastError}\`);
10291      this.memoryManager.free(filePtr);
10292      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`OpenDocumentBuffer\`, "End", file.id);
10293      return PdfTaskHelper.reject({
10294        code: lastError,
10295        message: \`FPDF_LoadMemDocument failed\`
10296      });
10297    }
10298    const pageCount = this.pdfiumModule.FPDF_GetPageCount(docPtr);
10299    const pages = [];
10300    const sizePtr = this.memoryManager.malloc(8);
10301    for (let index = 0; index < pageCount; index++) {
10302      const result = normalizeRotation ? this.pdfiumModule.EPDF_GetPageSizeByIndexNormalized(docPtr, index, sizePtr) : this.pdfiumModule.FPDF_GetPageSizeByIndexF(docPtr, index, sizePtr);
10303      if (!result) {
10304        const lastError = this.pdfiumModule.FPDF_GetLastError();
10305        this.logger.error(
10306          LOG_SOURCE$1,
10307          LOG_CATEGORY$1,
10308          \`\${normalizeRotation ? "EPDF_GetPageSizeByIndexNormalized" : "FPDF_GetPageSizeByIndexF"} failed with \${lastError}\`
10309        );
10310        this.memoryManager.free(sizePtr);
10311        this.pdfiumModule.FPDF_CloseDocument(docPtr);
10312        this.memoryManager.free(filePtr);
10313        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`OpenDocumentBuffer\`, "End", file.id);
10314        return PdfTaskHelper.reject({
10315          code: lastError,
10316          message: \`\${normalizeRotation ? "EPDF_GetPageSizeByIndexNormalized" : "FPDF_GetPageSizeByIndexF"} failed\`
10317        });
10318      }
10319      const rotation = this.pdfiumModule.EPDF_GetPageRotationByIndex(docPtr, index);
10320      const page = {
10321        index,
10322        size: {
10323          width: this.pdfiumModule.pdfium.getValue(sizePtr, "float"),
10324          height: this.pdfiumModule.pdfium.getValue(sizePtr + 4, "float")
10325        },
10326        rotation
10327      };
10328      pages.push(page);
10329    }
10330    this.memoryManager.free(sizePtr);
10331    const isEncrypted = this.pdfiumModule.EPDF_IsEncrypted(docPtr);
10332    const isOwnerUnlocked = this.pdfiumModule.EPDF_IsOwnerUnlocked(docPtr);
10333    const permissions = this.pdfiumModule.FPDF_GetDocPermissions(docPtr);
10334    const pdfDoc = {
10335      id: file.id,
10336      pageCount,
10337      pages,
10338      isEncrypted,
10339      isOwnerUnlocked,
10340      permissions,
10341      normalizedRotation: normalizeRotation
10342    };
10343    this.cache.setDocument(file.id, filePtr, docPtr, normalizeRotation);
10344    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`OpenDocumentBuffer\`, "End", file.id);
10345    return PdfTaskHelper.resolve(pdfDoc);
10346  }
10347  /**
10348   * Create a new empty PDF document and register it in the cache.
10349   *
10350   * @param id - unique document identifier
10351   * @returns task containing the empty PdfDocumentObject
10352   */
10353  createDocument(id) {
10354    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "createDocument", id);
10355    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "CreateDocument", "Begin", id);
10356    const docPtr = this.pdfiumModule.FPDF_CreateNewDocument();
10357    if (!docPtr) {
10358      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "CreateDocument", "End", id);
10359      return PdfTaskHelper.reject({
10360        code: PdfErrorCode.CantCreateNewDoc,
10361        message: "can not create new document"
10362      });
10363    }
10364    const pdfDoc = {
10365      id,
10366      pageCount: 0,
10367      pages: [],
10368      isEncrypted: false,
10369      isOwnerUnlocked: true,
10370      permissions: 4294967295,
10371      normalizedRotation: false
10372    };
10373    this.cache.setDocument(id, 0, docPtr, false);
10374    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "CreateDocument", "End", id);
10375    return PdfTaskHelper.resolve(pdfDoc);
10376  }
10377  /**
10378   * {@inheritDoc @embedpdf/models!PdfEngine.getMetadata}
10379   *
10380   * @public
10381   */
10382  getMetadata(doc) {
10383    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getMetadata", doc);
10384    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetMetadata\`, "Begin", doc.id);
10385    const ctx = this.cache.getContext(doc.id);
10386    if (!ctx) {
10387      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetMetadata\`, "End", doc.id);
10388      return PdfTaskHelper.reject({
10389        code: PdfErrorCode.DocNotOpen,
10390        message: "document does not open"
10391      });
10392    }
10393    const creationRaw = this.readMetaText(ctx.docPtr, "CreationDate");
10394    const modRaw = this.readMetaText(ctx.docPtr, "ModDate");
10395    const metadata = {
10396      title: this.readMetaText(ctx.docPtr, "Title"),
10397      author: this.readMetaText(ctx.docPtr, "Author"),
10398      subject: this.readMetaText(ctx.docPtr, "Subject"),
10399      keywords: this.readMetaText(ctx.docPtr, "Keywords"),
10400      producer: this.readMetaText(ctx.docPtr, "Producer"),
10401      creator: this.readMetaText(ctx.docPtr, "Creator"),
10402      creationDate: creationRaw ? pdfDateToDate(creationRaw) ?? null : null,
10403      modificationDate: modRaw ? pdfDateToDate(modRaw) ?? null : null,
10404      trapped: this.getMetaTrapped(ctx.docPtr),
10405      custom: this.readAllMeta(ctx.docPtr, true)
10406    };
10407    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetMetadata\`, "End", doc.id);
10408    return PdfTaskHelper.resolve(metadata);
10409  }
10410  /**
10411   * {@inheritDoc @embedpdf/models!PdfEngine.setMetadata}
10412   *
10413   * @public
10414   */
10415  setMetadata(doc, meta) {
10416    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setMetadata", doc, meta);
10417    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "Begin", doc.id);
10418    const ctx = this.cache.getContext(doc.id);
10419    if (!ctx) {
10420      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "End", doc.id);
10421      return PdfTaskHelper.reject({
10422        code: PdfErrorCode.DocNotOpen,
10423        message: "document does not open"
10424      });
10425    }
10426    const strMap = [
10427      ["title", "Title"],
10428      ["author", "Author"],
10429      ["subject", "Subject"],
10430      ["keywords", "Keywords"],
10431      ["producer", "Producer"],
10432      ["creator", "Creator"]
10433    ];
10434    let ok = true;
10435    for (const [field, key] of strMap) {
10436      const v = meta[field];
10437      if (v === void 0) continue;
10438      const s = v === null ? null : v;
10439      if (!this.setMetaText(ctx.docPtr, key, s)) ok = false;
10440    }
10441    const writeDate = (field, key) => {
10442      const v = meta[field];
10443      if (v === void 0) return;
10444      if (v === null) {
10445        if (!this.setMetaText(ctx.docPtr, key, null)) ok = false;
10446        return;
10447      }
10448      const d = v;
10449      const raw = dateToPdfDate(d);
10450      if (!this.setMetaText(ctx.docPtr, key, raw)) ok = false;
10451    };
10452    writeDate("creationDate", "CreationDate");
10453    writeDate("modificationDate", "ModDate");
10454    if (meta.trapped !== void 0) {
10455      if (!this.setMetaTrapped(ctx.docPtr, meta.trapped ?? null)) ok = false;
10456    }
10457    if (meta.custom !== void 0) {
10458      for (const [key, value] of Object.entries(meta.custom)) {
10459        if (!isValidCustomKey(key)) {
10460          this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, "Invalid custom metadata key skipped", key);
10461          continue;
10462        }
10463        if (!this.setMetaText(ctx.docPtr, key, value ?? null)) ok = false;
10464      }
10465    }
10466    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SetMetadata", "End", doc.id);
10467    return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({
10468      code: PdfErrorCode.Unknown,
10469      message: "one or more metadata fields could not be written"
10470    });
10471  }
10472  /**
10473   * {@inheritDoc @embedpdf/models!PdfEngine.getDocPermissions}
10474   *
10475   * @public
10476   */
10477  getDocPermissions(doc) {
10478    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocPermissions", doc);
10479    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getDocPermissions\`, "Begin", doc.id);
10480    const ctx = this.cache.getContext(doc.id);
10481    if (!ctx) {
10482      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getDocPermissions\`, "End", doc.id);
10483      return PdfTaskHelper.reject({
10484        code: PdfErrorCode.DocNotOpen,
10485        message: "document does not open"
10486      });
10487    }
10488    const permissions = this.pdfiumModule.FPDF_GetDocPermissions(ctx.docPtr);
10489    return PdfTaskHelper.resolve(permissions);
10490  }
10491  /**
10492   * {@inheritDoc @embedpdf/models!PdfEngine.getDocUserPermissions}
10493   *
10494   * @public
10495   */
10496  getDocUserPermissions(doc) {
10497    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocUserPermissions", doc);
10498    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getDocUserPermissions\`, "Begin", doc.id);
10499    const ctx = this.cache.getContext(doc.id);
10500    if (!ctx) {
10501      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getDocUserPermissions\`, "End", doc.id);
10502      return PdfTaskHelper.reject({
10503        code: PdfErrorCode.DocNotOpen,
10504        message: "document does not open"
10505      });
10506    }
10507    const permissions = this.pdfiumModule.FPDF_GetDocUserPermissions(ctx.docPtr);
10508    return PdfTaskHelper.resolve(permissions);
10509  }
10510  /**
10511   * {@inheritDoc @embedpdf/models!PdfEngine.getSignatures}
10512   *
10513   * @public
10514   */
10515  getSignatures(doc) {
10516    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getSignatures", doc);
10517    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetSignatures\`, "Begin", doc.id);
10518    const ctx = this.cache.getContext(doc.id);
10519    if (!ctx) {
10520      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetSignatures\`, "End", doc.id);
10521      return PdfTaskHelper.reject({
10522        code: PdfErrorCode.DocNotOpen,
10523        message: "document does not open"
10524      });
10525    }
10526    const signatures = [];
10527    const count = this.pdfiumModule.FPDF_GetSignatureCount(ctx.docPtr);
10528    for (let i = 0; i < count; i++) {
10529      const signatureObjPtr = this.pdfiumModule.FPDF_GetSignatureObject(ctx.docPtr, i);
10530      const contents = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {
10531        return this.pdfiumModule.FPDFSignatureObj_GetContents(signatureObjPtr, buffer, bufferSize);
10532      });
10533      const byteRange = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {
10534        return this.pdfiumModule.FPDFSignatureObj_GetByteRange(signatureObjPtr, buffer, bufferSize) * 4;
10535      });
10536      const subFilter = readArrayBuffer(this.pdfiumModule.pdfium, (buffer, bufferSize) => {
10537        return this.pdfiumModule.FPDFSignatureObj_GetSubFilter(signatureObjPtr, buffer, bufferSize);
10538      });
10539      const reason = readString(
10540        this.pdfiumModule.pdfium,
10541        (buffer, bufferLength) => {
10542          return this.pdfiumModule.FPDFSignatureObj_GetReason(
10543            signatureObjPtr,
10544            buffer,
10545            bufferLength
10546          );
10547        },
10548        this.pdfiumModule.pdfium.UTF16ToString
10549      );
10550      const time = readString(
10551        this.pdfiumModule.pdfium,
10552        (buffer, bufferLength) => {
10553          return this.pdfiumModule.FPDFSignatureObj_GetTime(signatureObjPtr, buffer, bufferLength);
10554        },
10555        this.pdfiumModule.pdfium.UTF8ToString
10556      );
10557      const docMDP = this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(signatureObjPtr);
10558      signatures.push({
10559        contents,
10560        byteRange,
10561        subFilter,
10562        reason,
10563        time,
10564        docMDP
10565      });
10566    }
10567    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetSignatures\`, "End", doc.id);
10568    return PdfTaskHelper.resolve(signatures);
10569  }
10570  /**
10571   * {@inheritDoc @embedpdf/models!PdfEngine.getBookmarks}
10572   *
10573   * @public
10574   */
10575  getBookmarks(doc) {
10576    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getBookmarks", doc);
10577    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetBookmarks\`, "Begin", doc.id);
10578    const ctx = this.cache.getContext(doc.id);
10579    if (!ctx) {
10580      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`getBookmarks\`, "End", doc.id);
10581      return PdfTaskHelper.reject({
10582        code: PdfErrorCode.DocNotOpen,
10583        message: "document does not open"
10584      });
10585    }
10586    const bookmarks = this.readPdfBookmarks(ctx.docPtr, 0);
10587    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetBookmarks\`, "End", doc.id);
10588    return PdfTaskHelper.resolve({
10589      bookmarks
10590    });
10591  }
10592  /**
10593   * {@inheritDoc @embedpdf/models!PdfEngine.setBookmarks}
10594   *
10595   * @public
10596   */
10597  setBookmarks(doc, list) {
10598    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setBookmarks", doc, list);
10599    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SetBookmarks\`, "Begin", doc.id);
10600    const ctx = this.cache.getContext(doc.id);
10601    if (!ctx) {
10602      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SetBookmarks\`, "End", doc.id);
10603      return PdfTaskHelper.reject({
10604        code: PdfErrorCode.DocNotOpen,
10605        message: "document does not open"
10606      });
10607    }
10608    if (!this.pdfiumModule.EPDFBookmark_Clear(ctx.docPtr)) {
10609      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SetBookmarks\`, "End", doc.id);
10610      return PdfTaskHelper.reject({
10611        code: PdfErrorCode.Unknown,
10612        message: "failed to clear existing bookmarks"
10613      });
10614    }
10615    const build = (parentPtr, items) => {
10616      var _a;
10617      for (const item of items) {
10618        const bmPtr = this.withWString(
10619          item.title ?? "",
10620          (wptr) => this.pdfiumModule.EPDFBookmark_AppendChild(ctx.docPtr, parentPtr, wptr)
10621        );
10622        if (!bmPtr) return false;
10623        if (item.target) {
10624          const ok2 = this.applyBookmarkTarget(ctx.docPtr, bmPtr, item.target);
10625          if (!ok2) return false;
10626        }
10627        if ((_a = item.children) == null ? void 0 : _a.length) {
10628          const ok2 = build(bmPtr, item.children);
10629          if (!ok2) return false;
10630        }
10631      }
10632      return true;
10633    };
10634    const ok = build(
10635      /*top-level*/
10636      0,
10637      list
10638    );
10639    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SetBookmarks\`, "End", doc.id);
10640    if (!ok) {
10641      return PdfTaskHelper.reject({
10642        code: PdfErrorCode.Unknown,
10643        message: "failed to build bookmark tree"
10644      });
10645    }
10646    return PdfTaskHelper.resolve(true);
10647  }
10648  /**
10649   * {@inheritDoc @embedpdf/models!PdfEngine.deleteBookmarks}
10650   *
10651   * @public
10652   */
10653  deleteBookmarks(doc) {
10654    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deleteBookmarks", doc);
10655    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteBookmarks\`, "Begin", doc.id);
10656    const ctx = this.cache.getContext(doc.id);
10657    if (!ctx) {
10658      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteBookmarks\`, "End", doc.id);
10659      return PdfTaskHelper.reject({
10660        code: PdfErrorCode.DocNotOpen,
10661        message: "document does not open"
10662      });
10663    }
10664    const ok = this.pdfiumModule.EPDFBookmark_Clear(ctx.docPtr);
10665    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteBookmarks\`, "End", doc.id);
10666    return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({
10667      code: PdfErrorCode.Unknown,
10668      message: "failed to clear bookmarks"
10669    });
10670  }
10671  /**
10672   * {@inheritDoc @embedpdf/models!PdfEngine.renderPage}
10673   *
10674   * @public
10675   */
10676  renderPageRaw(doc, page, options) {
10677    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPage", doc, page, options);
10678    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`RenderPage\`, "Begin", \`\${doc.id}-\${page.index}\`);
10679    const rect = { origin: { x: 0, y: 0 }, size: page.size };
10680    const task = this.renderRectEncoded(doc, page, rect, options);
10681    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`RenderPage\`, "End", \`\${doc.id}-\${page.index}\`);
10682    return task;
10683  }
10684  /**
10685   * {@inheritDoc @embedpdf/models!PdfEngine.renderPageRect}
10686   *
10687   * @public
10688   */
10689  renderPageRect(doc, page, rect, options) {
10690    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPageRect", doc, page, rect, options);
10691    this.logger.perf(
10692      LOG_SOURCE$1,
10693      LOG_CATEGORY$1,
10694      \`RenderPageRect\`,
10695      "Begin",
10696      \`\${doc.id}-\${page.index}\`
10697    );
10698    const task = this.renderRectEncoded(doc, page, rect, options);
10699    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`RenderPageRect\`, "End", \`\${doc.id}-\${page.index}\`);
10700    return task;
10701  }
10702  getDocumentJavaScriptActions(doc) {
10703    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getDocumentJavaScriptActions", doc);
10704    const ctx = this.cache.getContext(doc.id);
10705    if (!ctx) {
10706      return PdfTaskHelper.reject({
10707        code: PdfErrorCode.DocNotOpen,
10708        message: "document does not open"
10709      });
10710    }
10711    const count = this.pdfiumModule.FPDFDoc_GetJavaScriptActionCount(ctx.docPtr);
10712    if (count < 0) {
10713      return PdfTaskHelper.reject({
10714        code: PdfErrorCode.Unknown,
10715        message: "failed to read document javascript actions"
10716      });
10717    }
10718    const actions = [];
10719    for (let index = 0; index < count; index++) {
10720      const actionPtr = this.pdfiumModule.FPDFDoc_GetJavaScriptAction(ctx.docPtr, index);
10721      if (!actionPtr) continue;
10722      try {
10723        const name = readString(
10724          this.pdfiumModule.pdfium,
10725          (buffer, bufferLength) => this.pdfiumModule.FPDFJavaScriptAction_GetName(actionPtr, buffer, bufferLength),
10726          this.pdfiumModule.pdfium.UTF16ToString
10727        ) ?? "";
10728        const script = readString(
10729          this.pdfiumModule.pdfium,
10730          (buffer, bufferLength) => this.pdfiumModule.FPDFJavaScriptAction_GetScript(actionPtr, buffer, bufferLength),
10731          this.pdfiumModule.pdfium.UTF16ToString
10732        ) ?? "";
10733        if (!script) continue;
10734        actions.push({
10735          id: \`document:\${index}:\${name}\`,
10736          trigger: PdfJavaScriptActionTrigger.DocumentNamed,
10737          name,
10738          script
10739        });
10740      } finally {
10741        this.pdfiumModule.FPDFDoc_CloseJavaScriptAction(actionPtr);
10742      }
10743    }
10744    return PdfTaskHelper.resolve(actions);
10745  }
10746  getPageAnnoWidgets(doc, page) {
10747    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnoWidgets", doc, page);
10748    this.logger.perf(
10749      LOG_SOURCE$1,
10750      LOG_CATEGORY$1,
10751      \`GetPageAnnoWidgets\`,
10752      "Begin",
10753      \`\${doc.id}-\${page.index}\`
10754    );
10755    const ctx = this.cache.getContext(doc.id);
10756    if (!ctx) {
10757      this.logger.perf(
10758        LOG_SOURCE$1,
10759        LOG_CATEGORY$1,
10760        \`GetPageAnnoWidgets\`,
10761        "End",
10762        \`\${doc.id}-\${page.index}\`
10763      );
10764      return PdfTaskHelper.reject({
10765        code: PdfErrorCode.DocNotOpen,
10766        message: "document does not open"
10767      });
10768    }
10769    const annotationWidgets = this.readPageAnnoWidgets(doc, ctx, page);
10770    this.logger.perf(
10771      LOG_SOURCE$1,
10772      LOG_CATEGORY$1,
10773      \`GetPageAnnoWidgets\`,
10774      "End",
10775      \`\${doc.id}-\${page.index}\`
10776    );
10777    this.logger.debug(
10778      LOG_SOURCE$1,
10779      LOG_CATEGORY$1,
10780      \`GetPageAnnoWidgets\`,
10781      \`\${doc.id}-\${page.index}\`,
10782      annotationWidgets
10783    );
10784    return PdfTaskHelper.resolve(annotationWidgets);
10785  }
10786  getPageWidgetJavaScriptActions(doc, page) {
10787    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageWidgetJavaScriptActions", doc, page);
10788    const ctx = this.cache.getContext(doc.id);
10789    if (!ctx) {
10790      return PdfTaskHelper.reject({
10791        code: PdfErrorCode.DocNotOpen,
10792        message: "document does not open"
10793      });
10794    }
10795    const actions = [];
10796    ctx.borrowPage(page.index, (pageCtx) => {
10797      pageCtx.withFormHandle((formHandle) => {
10798        const annotCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
10799        for (let i = 0; i < annotCount; i++) {
10800          pageCtx.withAnnotation(i, (annotPtr) => {
10801            const subtype = this.pdfiumModule.FPDFAnnot_GetSubtype(
10802              annotPtr
10803            );
10804            if (subtype !== PdfAnnotationSubtype.WIDGET) return;
10805            let annotationId = this.getAnnotString(annotPtr, "NM");
10806            if (!annotationId || !isUuidV4(annotationId)) {
10807              annotationId = uuidV4();
10808              this.setAnnotString(annotPtr, "NM", annotationId);
10809            }
10810            const fieldName = readString(
10811              this.pdfiumModule.pdfium,
10812              (buffer, bufferLength) => this.pdfiumModule.FPDFAnnot_GetFormFieldName(
10813                formHandle,
10814                annotPtr,
10815                buffer,
10816                bufferLength
10817              ),
10818              this.pdfiumModule.pdfium.UTF16ToString
10819            ) ?? "";
10820            const eventConfigs = [
10821              {
10822                event: PDF_ANNOT_AACTION_EVENT.KEY_STROKE,
10823                eventType: PdfJavaScriptWidgetEventType.Keystroke,
10824                trigger: PdfJavaScriptActionTrigger.WidgetKeystroke
10825              },
10826              {
10827                event: PDF_ANNOT_AACTION_EVENT.FORMAT,
10828                eventType: PdfJavaScriptWidgetEventType.Format,
10829                trigger: PdfJavaScriptActionTrigger.WidgetFormat
10830              },
10831              {
10832                event: PDF_ANNOT_AACTION_EVENT.VALIDATE,
10833                eventType: PdfJavaScriptWidgetEventType.Validate,
10834                trigger: PdfJavaScriptActionTrigger.WidgetValidate
10835              },
10836              {
10837                event: PDF_ANNOT_AACTION_EVENT.CALCULATE,
10838                eventType: PdfJavaScriptWidgetEventType.Calculate,
10839                trigger: PdfJavaScriptActionTrigger.WidgetCalculate
10840              }
10841            ];
10842            for (const config of eventConfigs) {
10843              const script = readString(
10844                this.pdfiumModule.pdfium,
10845                (buffer, bufferLength) => this.pdfiumModule.FPDFAnnot_GetFormAdditionalActionJavaScript(
10846                  formHandle,
10847                  annotPtr,
10848                  config.event,
10849                  buffer,
10850                  bufferLength
10851                ),
10852                this.pdfiumModule.pdfium.UTF16ToString
10853              ) ?? "";
10854              if (!script) continue;
10855              actions.push({
10856                id: \`widget:\${page.index}:\${annotationId}:\${config.eventType}\`,
10857                trigger: config.trigger,
10858                eventType: config.eventType,
10859                pageIndex: page.index,
10860                annotationId,
10861                fieldName,
10862                script
10863              });
10864            }
10865          });
10866        }
10867      });
10868    });
10869    return PdfTaskHelper.resolve(actions);
10870  }
10871  regenerateWidgetAppearances(doc, page, annotationIds) {
10872    const ctx = this.cache.getContext(doc.id);
10873    if (!ctx) {
10874      return PdfTaskHelper.reject({
10875        code: PdfErrorCode.DocNotOpen,
10876        message: "document does not open"
10877      });
10878    }
10879    const idSet = new Set(annotationIds);
10880    let regenerated = 0;
10881    ctx.borrowPage(page.index, (pageCtx) => {
10882      const count = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
10883      for (let i = 0; i < count; i++) {
10884        pageCtx.withAnnotation(i, (annotPtr) => {
10885          const nm = this.getAnnotString(annotPtr, "NM");
10886          if (nm && idSet.has(nm)) {
10887            this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotPtr);
10888            regenerated++;
10889          }
10890        });
10891      }
10892      if (regenerated > 0) {
10893        this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
10894      }
10895    });
10896    return PdfTaskHelper.resolve(regenerated > 0);
10897  }
10898  /**
10899   * {@inheritDoc @embedpdf/models!PdfEngine.getPageAnnotations}
10900   *
10901   * @public
10902   */
10903  getPageAnnotations(doc, page) {
10904    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnotations", doc, page);
10905    this.logger.perf(
10906      LOG_SOURCE$1,
10907      LOG_CATEGORY$1,
10908      \`GetPageAnnotations\`,
10909      "Begin",
10910      \`\${doc.id}-\${page.index}\`
10911    );
10912    const ctx = this.cache.getContext(doc.id);
10913    if (!ctx) {
10914      this.logger.perf(
10915        LOG_SOURCE$1,
10916        LOG_CATEGORY$1,
10917        \`GetPageAnnotations\`,
10918        "End",
10919        \`\${doc.id}-\${page.index}\`
10920      );
10921      return PdfTaskHelper.reject({
10922        code: PdfErrorCode.DocNotOpen,
10923        message: "document does not open"
10924      });
10925    }
10926    const annotations = this.readPageAnnotations(doc, ctx, page);
10927    this.logger.perf(
10928      LOG_SOURCE$1,
10929      LOG_CATEGORY$1,
10930      \`GetPageAnnotations\`,
10931      "End",
10932      \`\${doc.id}-\${page.index}\`
10933    );
10934    this.logger.debug(
10935      LOG_SOURCE$1,
10936      LOG_CATEGORY$1,
10937      \`GetPageAnnotations\`,
10938      \`\${doc.id}-\${page.index}\`,
10939      annotations
10940    );
10941    return PdfTaskHelper.resolve(annotations);
10942  }
10943  /**
10944   * {@inheritDoc @embedpdf/models!PdfEngine.createPageAnnotation}
10945   *
10946   * @public
10947   */
10948  createPageAnnotation(doc, page, annotation, context) {
10949    var _a;
10950    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "createPageAnnotation", doc, page, annotation);
10951    this.logger.perf(
10952      LOG_SOURCE$1,
10953      LOG_CATEGORY$1,
10954      \`CreatePageAnnotation\`,
10955      "Begin",
10956      \`\${doc.id}-\${page.index}\`
10957    );
10958    const ctx = this.cache.getContext(doc.id);
10959    if (!ctx) {
10960      this.logger.perf(
10961        LOG_SOURCE$1,
10962        LOG_CATEGORY$1,
10963        \`CreatePageAnnotation\`,
10964        "End",
10965        \`\${doc.id}-\${page.index}\`
10966      );
10967      return PdfTaskHelper.reject({
10968        code: PdfErrorCode.DocNotOpen,
10969        message: "document does not open"
10970      });
10971    }
10972    const pageCtx = ctx.acquirePage(page.index);
10973    let annotationPtr;
10974    let widgetFormInfoPtr;
10975    let widgetFormHandle;
10976    if (annotation.type === PdfAnnotationSubtype.WIDGET) {
10977      const widget = annotation;
10978      widgetFormInfoPtr = this.pdfiumModule.PDFiumExt_OpenFormFillInfo();
10979      widgetFormHandle = this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(
10980        ctx.docPtr,
10981        widgetFormInfoPtr
10982      );
10983      this.pdfiumModule.FORM_OnAfterLoadPage(pageCtx.pagePtr, widgetFormHandle);
10984      const fieldName = ((_a = widget.field) == null ? void 0 : _a.name) ?? "";
10985      annotationPtr = this.withWString(
10986        fieldName,
10987        (namePtr) => this.pdfiumModule.EPDFPage_CreateFormField(
10988          pageCtx.pagePtr,
10989          widgetFormHandle,
10990          widget.field.type,
10991          namePtr
10992        )
10993      );
10994    } else {
10995      annotationPtr = this.pdfiumModule.EPDFPage_CreateAnnot(pageCtx.pagePtr, annotation.type);
10996    }
10997    if (!annotationPtr) {
10998      this.logger.perf(
10999        LOG_SOURCE$1,
11000        LOG_CATEGORY$1,
11001        \`CreatePageAnnotation\`,
11002        "End",
11003        \`\${doc.id}-\${page.index}\`
11004      );
11005      pageCtx.release();
11006      return PdfTaskHelper.reject({
11007        code: PdfErrorCode.CantCreateAnnot,
11008        message: "can not create annotation with specified type"
11009      });
11010    }
11011    if (!isUuidV4(annotation.id)) {
11012      annotation.id = uuidV4();
11013    }
11014    if (!this.setAnnotString(annotationPtr, "NM", annotation.id)) {
11015      this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
11016      pageCtx.release();
11017      return PdfTaskHelper.reject({
11018        code: PdfErrorCode.CantSetAnnotString,
11019        message: "can not set the name of the annotation"
11020      });
11021    }
11022    if (!this.setPageAnnoRect(doc, page, annotationPtr, annotation.rect)) {
11023      this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
11024      pageCtx.release();
11025      this.logger.perf(
11026        LOG_SOURCE$1,
11027        LOG_CATEGORY$1,
11028        \`CreatePageAnnotation\`,
11029        "End",
11030        \`\${doc.id}-\${page.index}\`
11031      );
11032      return PdfTaskHelper.reject({
11033        code: PdfErrorCode.CantSetAnnotRect,
11034        message: "can not set the rect of the annotation"
11035      });
11036    }
11037    const saveAnnotation = this.prepareAnnotationForSave(annotation);
11038    let isSucceed = false;
11039    switch (saveAnnotation.type) {
11040      case PdfAnnotationSubtype.INK:
11041        isSucceed = this.addInkStroke(
11042          doc,
11043          page,
11044          pageCtx.pagePtr,
11045          annotationPtr,
11046          saveAnnotation
11047        );
11048        break;
11049      case PdfAnnotationSubtype.STAMP:
11050        isSucceed = this.addStampContent(
11051          doc,
11052          ctx.docPtr,
11053          page,
11054          pageCtx.pagePtr,
11055          annotationPtr,
11056          saveAnnotation,
11057          context
11058        );
11059        break;
11060      case PdfAnnotationSubtype.TEXT:
11061        isSucceed = this.addTextContent(
11062          doc,
11063          page,
11064          pageCtx.pagePtr,
11065          annotationPtr,
11066          saveAnnotation
11067        );
11068        break;
11069      case PdfAnnotationSubtype.FREETEXT:
11070        isSucceed = this.addFreeTextContent(
11071          doc,
11072          page,
11073          pageCtx.pagePtr,
11074          annotationPtr,
11075          saveAnnotation
11076        );
11077        break;
11078      case PdfAnnotationSubtype.LINE:
11079        isSucceed = this.addLineContent(
11080          doc,
11081          page,
11082          pageCtx.pagePtr,
11083          annotationPtr,
11084          saveAnnotation
11085        );
11086        break;
11087      case PdfAnnotationSubtype.POLYLINE:
11088      case PdfAnnotationSubtype.POLYGON:
11089        isSucceed = this.addPolyContent(
11090          doc,
11091          page,
11092          pageCtx.pagePtr,
11093          annotationPtr,
11094          saveAnnotation
11095        );
11096        break;
11097      case PdfAnnotationSubtype.CIRCLE:
11098      case PdfAnnotationSubtype.SQUARE:
11099        isSucceed = this.addShapeContent(doc, page, pageCtx.pagePtr, annotationPtr, saveAnnotation);
11100        break;
11101      case PdfAnnotationSubtype.UNDERLINE:
11102      case PdfAnnotationSubtype.STRIKEOUT:
11103      case PdfAnnotationSubtype.SQUIGGLY:
11104      case PdfAnnotationSubtype.HIGHLIGHT:
11105        isSucceed = this.addTextMarkupContent(
11106          doc,
11107          page,
11108          pageCtx.pagePtr,
11109          annotationPtr,
11110          saveAnnotation
11111        );
11112        break;
11113      case PdfAnnotationSubtype.LINK:
11114        isSucceed = this.addLinkContent(
11115          doc,
11116          page,
11117          ctx.docPtr,
11118          pageCtx.pagePtr,
11119          annotationPtr,
11120          saveAnnotation
11121        );
11122        break;
11123      case PdfAnnotationSubtype.CARET:
11124        isSucceed = this.addCaretContent(
11125          doc,
11126          page,
11127          pageCtx.pagePtr,
11128          annotationPtr,
11129          saveAnnotation
11130        );
11131        break;
11132      case PdfAnnotationSubtype.REDACT:
11133        isSucceed = this.addRedactContent(
11134          doc,
11135          page,
11136          pageCtx.pagePtr,
11137          annotationPtr,
11138          saveAnnotation
11139        );
11140        break;
11141      case PdfAnnotationSubtype.WIDGET: {
11142        const widget = saveAnnotation;
11143        if (widgetFormHandle !== void 0) {
11144          switch (widget.field.type) {
11145            case PDF_FORM_FIELD_TYPE.TEXTFIELD:
11146              isSucceed = this.addTextFieldContent(widgetFormHandle, annotationPtr, widget);
11147              break;
11148            case PDF_FORM_FIELD_TYPE.CHECKBOX:
11149            case PDF_FORM_FIELD_TYPE.RADIOBUTTON:
11150              isSucceed = this.addToggleFieldContent(widgetFormHandle, annotationPtr, widget);
11151              break;
11152            case PDF_FORM_FIELD_TYPE.COMBOBOX:
11153            case PDF_FORM_FIELD_TYPE.LISTBOX:
11154              isSucceed = this.addChoiceFieldContent(widgetFormHandle, annotationPtr, widget);
11155              break;
11156          }
11157        }
11158        break;
11159      }
11160    }
11161    if (widgetFormHandle !== void 0) {
11162      this.pdfiumModule.FORM_OnBeforeClosePage(pageCtx.pagePtr, widgetFormHandle);
11163      this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(widgetFormHandle);
11164    }
11165    if (widgetFormInfoPtr !== void 0) {
11166      this.pdfiumModule.PDFiumExt_CloseFormFillInfo(widgetFormInfoPtr);
11167    }
11168    if (!isSucceed) {
11169      this.pdfiumModule.FPDFPage_RemoveAnnot(pageCtx.pagePtr, annotationPtr);
11170      pageCtx.release();
11171      this.logger.perf(
11172        LOG_SOURCE$1,
11173        LOG_CATEGORY$1,
11174        \`CreatePageAnnotation\`,
11175        "End",
11176        \`\${doc.id}-\${page.index}\`
11177      );
11178      return PdfTaskHelper.reject({
11179        code: PdfErrorCode.CantSetAnnotContent,
11180        message: "can not add content of the annotation"
11181      });
11182    }
11183    if (annotation.type === PdfAnnotationSubtype.WIDGET) {
11184      this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotationPtr);
11185    } else if (annotation.blendMode !== void 0) {
11186      this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(annotationPtr, annotation.blendMode);
11187    } else {
11188      this.pdfiumModule.EPDFAnnot_GenerateAppearance(annotationPtr);
11189    }
11190    this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
11191    this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
11192    pageCtx.release();
11193    this.logger.perf(
11194      LOG_SOURCE$1,
11195      LOG_CATEGORY$1,
11196      \`CreatePageAnnotation\`,
11197      "End",
11198      \`\${doc.id}-\${page.index}\`
11199    );
11200    return PdfTaskHelper.resolve(annotation.id);
11201  }
11202  /**
11203   * Update an existing page annotation in-place
11204   *
11205   *  • Locates the annot by page-local index (\`annotation.id\`)
11206   *  • Re-writes its /Rect and type-specific payload
11207   *  • Calls FPDFPage_GenerateContent so the new appearance is rendered
11208   *
11209   * @returns PdfTask<boolean>  –  true on success
11210   */
11211  updatePageAnnotation(doc, page, annotation, options) {
11212    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "updatePageAnnotation", doc, page, annotation);
11213    this.logger.perf(
11214      LOG_SOURCE$1,
11215      LOG_CATEGORY$1,
11216      "UpdatePageAnnotation",
11217      "Begin",
11218      \`\${doc.id}-\${page.index}\`
11219    );
11220    const ctx = this.cache.getContext(doc.id);
11221    if (!ctx) {
11222      this.logger.perf(
11223        LOG_SOURCE$1,
11224        LOG_CATEGORY$1,
11225        "UpdatePageAnnotation",
11226        "End",
11227        \`\${doc.id}-\${page.index}\`
11228      );
11229      return PdfTaskHelper.reject({
11230        code: PdfErrorCode.DocNotOpen,
11231        message: "document does not open"
11232      });
11233    }
11234    const pageCtx = ctx.acquirePage(page.index);
11235    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
11236    if (!annotPtr) {
11237      pageCtx.release();
11238      this.logger.perf(
11239        LOG_SOURCE$1,
11240        LOG_CATEGORY$1,
11241        "UpdatePageAnnotation",
11242        "End",
11243        \`\${doc.id}-\${page.index}\`
11244      );
11245      return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });
11246    }
11247    if (!this.setPageAnnoRect(doc, page, annotPtr, annotation.rect)) {
11248      this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
11249      pageCtx.release();
11250      this.logger.perf(
11251        LOG_SOURCE$1,
11252        LOG_CATEGORY$1,
11253        "UpdatePageAnnotation",
11254        "End",
11255        \`\${doc.id}-\${page.index}\`
11256      );
11257      return PdfTaskHelper.reject({
11258        code: PdfErrorCode.CantSetAnnotRect,
11259        message: "failed to move annotation"
11260      });
11261    }
11262    const saveAnnotation = this.prepareAnnotationForSave(annotation);
11263    let ok = false;
11264    switch (saveAnnotation.type) {
11265      /* ── Ink ─────────────────────────────────────────────────────────────── */
11266      case PdfAnnotationSubtype.INK: {
11267        if (!this.pdfiumModule.FPDFAnnot_RemoveInkList(annotPtr)) break;
11268        ok = this.addInkStroke(
11269          doc,
11270          page,
11271          pageCtx.pagePtr,
11272          annotPtr,
11273          saveAnnotation
11274        );
11275        break;
11276      }
11277      /* ── Stamp ───────────────────────────────────────────────────────────── */
11278      case PdfAnnotationSubtype.STAMP: {
11279        ok = this.addStampContent(
11280          doc,
11281          ctx.docPtr,
11282          page,
11283          pageCtx.pagePtr,
11284          annotPtr,
11285          saveAnnotation
11286        );
11287        break;
11288      }
11289      case PdfAnnotationSubtype.TEXT: {
11290        ok = this.addTextContent(
11291          doc,
11292          page,
11293          pageCtx.pagePtr,
11294          annotPtr,
11295          saveAnnotation
11296        );
11297        break;
11298      }
11299      /* ── Free text ────────────────────────────────────────────────────────── */
11300      case PdfAnnotationSubtype.FREETEXT: {
11301        ok = this.addFreeTextContent(
11302          doc,
11303          page,
11304          pageCtx.pagePtr,
11305          annotPtr,
11306          saveAnnotation
11307        );
11308        break;
11309      }
11310      /* ── Shape ───────────────────────────────────────────────────────────── */
11311      case PdfAnnotationSubtype.CIRCLE:
11312      case PdfAnnotationSubtype.SQUARE: {
11313        ok = this.addShapeContent(doc, page, pageCtx.pagePtr, annotPtr, saveAnnotation);
11314        break;
11315      }
11316      /* ── Line ─────────────────────────────────────────────────────────────── */
11317      case PdfAnnotationSubtype.LINE: {
11318        ok = this.addLineContent(
11319          doc,
11320          page,
11321          pageCtx.pagePtr,
11322          annotPtr,
11323          saveAnnotation
11324        );
11325        break;
11326      }
11327      /* ── Polygon / Polyline ───────────────────────────────────────────────── */
11328      case PdfAnnotationSubtype.POLYGON:
11329      case PdfAnnotationSubtype.POLYLINE: {
11330        ok = this.addPolyContent(
11331          doc,
11332          page,
11333          pageCtx.pagePtr,
11334          annotPtr,
11335          saveAnnotation
11336        );
11337        break;
11338      }
11339      /* ── Text-markup family ──────────────────────────────────────────────── */
11340      case PdfAnnotationSubtype.HIGHLIGHT:
11341      case PdfAnnotationSubtype.UNDERLINE:
11342      case PdfAnnotationSubtype.STRIKEOUT:
11343      case PdfAnnotationSubtype.SQUIGGLY: {
11344        ok = this.addTextMarkupContent(
11345          doc,
11346          page,
11347          pageCtx.pagePtr,
11348          annotPtr,
11349          saveAnnotation
11350        );
11351        break;
11352      }
11353      /* ── Link ─────────────────────────────────────────────────────────────── */
11354      case PdfAnnotationSubtype.LINK: {
11355        ok = this.addLinkContent(
11356          doc,
11357          page,
11358          ctx.docPtr,
11359          pageCtx.pagePtr,
11360          annotPtr,
11361          saveAnnotation
11362        );
11363        break;
11364      }
11365      /* ── Caret ────────────────────────────────────────────────────────────── */
11366      case PdfAnnotationSubtype.CARET: {
11367        ok = this.addCaretContent(
11368          doc,
11369          page,
11370          pageCtx.pagePtr,
11371          annotPtr,
11372          saveAnnotation
11373        );
11374        break;
11375      }
11376      /* ── Redact ───────────────────────────────────────────────────────────── */
11377      case PdfAnnotationSubtype.REDACT: {
11378        ok = this.addRedactContent(
11379          doc,
11380          page,
11381          pageCtx.pagePtr,
11382          annotPtr,
11383          saveAnnotation
11384        );
11385        break;
11386      }
11387      /* ── Widget (form field) ─────────────────────────────────────────────── */
11388      case PdfAnnotationSubtype.WIDGET: {
11389        const widget = saveAnnotation;
11390        pageCtx.withFormHandle((formHandle) => {
11391          switch (widget.field.type) {
11392            case PDF_FORM_FIELD_TYPE.TEXTFIELD:
11393              ok = this.addTextFieldContent(formHandle, annotPtr, widget);
11394              break;
11395            case PDF_FORM_FIELD_TYPE.CHECKBOX:
11396            case PDF_FORM_FIELD_TYPE.RADIOBUTTON:
11397              ok = this.addToggleFieldContent(formHandle, annotPtr, widget);
11398              break;
11399            case PDF_FORM_FIELD_TYPE.COMBOBOX:
11400            case PDF_FORM_FIELD_TYPE.LISTBOX:
11401              ok = this.addChoiceFieldContent(formHandle, annotPtr, widget);
11402              break;
11403          }
11404        });
11405        break;
11406      }
11407      /* ── Unsupported edits – fall through to error ───────────────────────── */
11408      default:
11409        ok = false;
11410    }
11411    if (ok && (options == null ? void 0 : options.regenerateAppearance) !== false) {
11412      if (annotation.type === PdfAnnotationSubtype.WIDGET) {
11413        this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotPtr);
11414      } else if (annotation.blendMode !== void 0) {
11415        this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(annotPtr, annotation.blendMode);
11416      } else {
11417        this.pdfiumModule.EPDFAnnot_GenerateAppearance(annotPtr);
11418      }
11419      this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
11420    }
11421    this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
11422    pageCtx.release();
11423    this.logger.perf(
11424      LOG_SOURCE$1,
11425      LOG_CATEGORY$1,
11426      "UpdatePageAnnotation",
11427      "End",
11428      \`\${doc.id}-\${page.index}\`
11429    );
11430    return ok ? PdfTaskHelper.resolve(true) : PdfTaskHelper.reject({
11431      code: PdfErrorCode.CantSetAnnotContent,
11432      message: "failed to update annotation"
11433    });
11434  }
11435  /**
11436   * {@inheritDoc @embedpdf/models!PdfEngine.removePageAnnotation}
11437   *
11438   * @public
11439   */
11440  removePageAnnotation(doc, page, annotation) {
11441    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "removePageAnnotation", doc, page, annotation);
11442    this.logger.perf(
11443      LOG_SOURCE$1,
11444      LOG_CATEGORY$1,
11445      \`RemovePageAnnotation\`,
11446      "Begin",
11447      \`\${doc.id}-\${page.index}\`
11448    );
11449    const ctx = this.cache.getContext(doc.id);
11450    if (!ctx) {
11451      this.logger.perf(
11452        LOG_SOURCE$1,
11453        LOG_CATEGORY$1,
11454        \`RemovePageAnnotation\`,
11455        "End",
11456        \`\${doc.id}-\${page.index}\`
11457      );
11458      return PdfTaskHelper.reject({
11459        code: PdfErrorCode.DocNotOpen,
11460        message: "document does not open"
11461      });
11462    }
11463    const pageCtx = ctx.acquirePage(page.index);
11464    let result = false;
11465    result = this.removeAnnotationByName(pageCtx.pagePtr, annotation.id);
11466    if (!result) {
11467      this.logger.error(
11468        LOG_SOURCE$1,
11469        LOG_CATEGORY$1,
11470        \`FPDFPage_RemoveAnnot Failed\`,
11471        \`\${doc.id}-\${page.index}\`
11472      );
11473    } else {
11474      result = this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
11475      if (!result) {
11476        this.logger.error(
11477          LOG_SOURCE$1,
11478          LOG_CATEGORY$1,
11479          \`FPDFPage_GenerateContent Failed\`,
11480          \`\${doc.id}-\${page.index}\`
11481        );
11482      }
11483    }
11484    pageCtx.release();
11485    this.logger.perf(
11486      LOG_SOURCE$1,
11487      LOG_CATEGORY$1,
11488      \`RemovePageAnnotation\`,
11489      "End",
11490      \`\${doc.id}-\${page.index}\`
11491    );
11492    return PdfTaskHelper.resolve(result);
11493  }
11494  /**
11495   * {@inheritDoc @embedpdf/models!PdfEngine.getPageTextRects}
11496   *
11497   * @public
11498   */
11499  getPageTextRects(doc, page) {
11500    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageTextRects", doc, page);
11501    this.logger.perf(
11502      LOG_SOURCE$1,
11503      LOG_CATEGORY$1,
11504      \`GetPageTextRects\`,
11505      "Begin",
11506      \`\${doc.id}-\${page.index}\`
11507    );
11508    const ctx = this.cache.getContext(doc.id);
11509    if (!ctx) {
11510      this.logger.perf(
11511        LOG_SOURCE$1,
11512        LOG_CATEGORY$1,
11513        \`GetPageTextRects\`,
11514        "End",
11515        \`\${doc.id}-\${page.index}\`
11516      );
11517      return PdfTaskHelper.reject({
11518        code: PdfErrorCode.DocNotOpen,
11519        message: "document does not open"
11520      });
11521    }
11522    const pageCtx = ctx.acquirePage(page.index);
11523    const textPagePtr = this.pdfiumModule.FPDFText_LoadPage(pageCtx.pagePtr);
11524    const textRects = this.readPageTextRects(page, pageCtx.docPtr, pageCtx.pagePtr, textPagePtr);
11525    this.pdfiumModule.FPDFText_ClosePage(textPagePtr);
11526    pageCtx.release();
11527    this.logger.perf(
11528      LOG_SOURCE$1,
11529      LOG_CATEGORY$1,
11530      \`GetPageTextRects\`,
11531      "End",
11532      \`\${doc.id}-\${page.index}\`
11533    );
11534    return PdfTaskHelper.resolve(textRects);
11535  }
11536  /**
11537   * {@inheritDoc @embedpdf/models!PdfEngine.renderThumbnail}
11538   *
11539   * @public
11540   */
11541  renderThumbnailRaw(doc, page, options) {
11542    const { scaleFactor = 1, ...rest } = options ?? {};
11543    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderThumbnail", doc, page, options);
11544    this.logger.perf(
11545      LOG_SOURCE$1,
11546      LOG_CATEGORY$1,
11547      \`RenderThumbnail\`,
11548      "Begin",
11549      \`\${doc.id}-\${page.index}\`
11550    );
11551    const ctx = this.cache.getContext(doc.id);
11552    if (!ctx) {
11553      this.logger.perf(
11554        LOG_SOURCE$1,
11555        LOG_CATEGORY$1,
11556        \`RenderThumbnail\`,
11557        "End",
11558        \`\${doc.id}-\${page.index}\`
11559      );
11560      return PdfTaskHelper.reject({
11561        code: PdfErrorCode.DocNotOpen,
11562        message: "document does not open"
11563      });
11564    }
11565    const result = this.renderPageRaw(doc, page, {
11566      scaleFactor: Math.max(scaleFactor, 0.5),
11567      ...rest
11568    });
11569    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`RenderThumbnail\`, "End", \`\${doc.id}-\${page.index}\`);
11570    return result;
11571  }
11572  /**
11573   * {@inheritDoc @embedpdf/models!PdfEngine.getAttachments}
11574   *
11575   * @public
11576   */
11577  getAttachments(doc) {
11578    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getAttachments", doc);
11579    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetAttachments\`, "Begin", doc.id);
11580    const ctx = this.cache.getContext(doc.id);
11581    if (!ctx) {
11582      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetAttachments\`, "End", doc.id);
11583      return PdfTaskHelper.reject({
11584        code: PdfErrorCode.DocNotOpen,
11585        message: "document does not open"
11586      });
11587    }
11588    const attachments = [];
11589    const count = this.pdfiumModule.FPDFDoc_GetAttachmentCount(ctx.docPtr);
11590    for (let i = 0; i < count; i++) {
11591      const attachment = this.readPdfAttachment(ctx.docPtr, i);
11592      attachments.push(attachment);
11593    }
11594    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`GetAttachments\`, "End", doc.id);
11595    return PdfTaskHelper.resolve(attachments);
11596  }
11597  /**
11598   * {@inheritDoc @embedpdf/models!PdfEngine.addAttachment}
11599   *
11600   * @public
11601   */
11602  addAttachment(doc, params) {
11603    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "addAttachment", doc, params == null ? void 0 : params.name);
11604    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "Begin", doc.id);
11605    const ctx = this.cache.getContext(doc.id);
11606    if (!ctx) {
11607      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11608      return PdfTaskHelper.reject({
11609        code: PdfErrorCode.DocNotOpen,
11610        message: "document does not open"
11611      });
11612    }
11613    const { name, description, mimeType, data } = params ?? {};
11614    if (!name) {
11615      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11616      return PdfTaskHelper.reject({
11617        code: PdfErrorCode.NotFound,
11618        message: "attachment name is required"
11619      });
11620    }
11621    if (!data || (data instanceof Uint8Array ? data.byteLength === 0 : data.byteLength === 0)) {
11622      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11623      return PdfTaskHelper.reject({
11624        code: PdfErrorCode.NotFound,
11625        message: "attachment data is empty"
11626      });
11627    }
11628    const attachmentPtr = this.withWString(
11629      name,
11630      (wNamePtr) => this.pdfiumModule.FPDFDoc_AddAttachment(ctx.docPtr, wNamePtr)
11631    );
11632    if (!attachmentPtr) {
11633      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11634      return PdfTaskHelper.reject({
11635        code: PdfErrorCode.Unknown,
11636        message: \`An attachment named "\${name}" already exists\`
11637      });
11638    }
11639    this.withWString(
11640      description,
11641      (wDescriptionPtr) => this.pdfiumModule.EPDFAttachment_SetDescription(attachmentPtr, wDescriptionPtr)
11642    );
11643    this.pdfiumModule.EPDFAttachment_SetSubtype(attachmentPtr, mimeType);
11644    const u8 = data instanceof Uint8Array ? data : new Uint8Array(data);
11645    const len = u8.byteLength;
11646    const contentPtr = this.memoryManager.malloc(len);
11647    try {
11648      this.pdfiumModule.pdfium.HEAPU8.set(u8, contentPtr);
11649      const ok = this.pdfiumModule.FPDFAttachment_SetFile(
11650        attachmentPtr,
11651        ctx.docPtr,
11652        contentPtr,
11653        len
11654      );
11655      if (!ok) {
11656        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11657        return PdfTaskHelper.reject({
11658          code: PdfErrorCode.Unknown,
11659          message: "failed to write attachment bytes"
11660        });
11661      }
11662    } finally {
11663      this.memoryManager.free(contentPtr);
11664    }
11665    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`AddAttachment\`, "End", doc.id);
11666    return PdfTaskHelper.resolve(true);
11667  }
11668  /**
11669   * {@inheritDoc @embedpdf/models!PdfEngine.removeAttachment}
11670   *
11671   * @public
11672   */
11673  removeAttachment(doc, attachment) {
11674    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deleteAttachment", doc, attachment);
11675    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteAttachment\`, "Begin", doc.id);
11676    const ctx = this.cache.getContext(doc.id);
11677    if (!ctx) {
11678      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteAttachment\`, "End", doc.id);
11679      return PdfTaskHelper.reject({
11680        code: PdfErrorCode.DocNotOpen,
11681        message: "document does not open"
11682      });
11683    }
11684    const count = this.pdfiumModule.FPDFDoc_GetAttachmentCount(ctx.docPtr);
11685    if (attachment.index < 0 || attachment.index >= count) {
11686      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteAttachment\`, "End", doc.id);
11687      return PdfTaskHelper.reject({
11688        code: PdfErrorCode.Unknown,
11689        message: \`attachment index \${attachment.index} out of range\`
11690      });
11691    }
11692    const ok = this.pdfiumModule.FPDFDoc_DeleteAttachment(ctx.docPtr, attachment.index);
11693    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`DeleteAttachment\`, "End", doc.id);
11694    if (!ok) {
11695      return PdfTaskHelper.reject({
11696        code: PdfErrorCode.Unknown,
11697        message: "failed to delete attachment"
11698      });
11699    }
11700    return PdfTaskHelper.resolve(true);
11701  }
11702  /**
11703   * {@inheritDoc @embedpdf/models!PdfEngine.readAttachmentContent}
11704   *
11705   * @public
11706   */
11707  readAttachmentContent(doc, attachment) {
11708    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "readAttachmentContent", doc, attachment);
11709    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "Begin", doc.id);
11710    const ctx = this.cache.getContext(doc.id);
11711    if (!ctx) {
11712      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "End", doc.id);
11713      return PdfTaskHelper.reject({
11714        code: PdfErrorCode.DocNotOpen,
11715        message: "document does not open"
11716      });
11717    }
11718    const attachmentPtr = this.pdfiumModule.FPDFDoc_GetAttachment(ctx.docPtr, attachment.index);
11719    const sizePtr = this.memoryManager.malloc(4);
11720    if (!this.pdfiumModule.FPDFAttachment_GetFile(attachmentPtr, 0, 0, sizePtr)) {
11721      this.memoryManager.free(sizePtr);
11722      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "End", doc.id);
11723      return PdfTaskHelper.reject({
11724        code: PdfErrorCode.CantReadAttachmentSize,
11725        message: "can not read attachment size"
11726      });
11727    }
11728    const size = this.pdfiumModule.pdfium.getValue(sizePtr, "i32") >>> 0;
11729    const contentPtr = this.memoryManager.malloc(size);
11730    if (!this.pdfiumModule.FPDFAttachment_GetFile(attachmentPtr, contentPtr, size, sizePtr)) {
11731      this.memoryManager.free(sizePtr);
11732      this.memoryManager.free(contentPtr);
11733      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "End", doc.id);
11734      return PdfTaskHelper.reject({
11735        code: PdfErrorCode.CantReadAttachmentContent,
11736        message: "can not read attachment content"
11737      });
11738    }
11739    const buffer = new ArrayBuffer(size);
11740    const view = new DataView(buffer);
11741    for (let i = 0; i < size; i++) {
11742      view.setInt8(i, this.pdfiumModule.pdfium.getValue(contentPtr + i, "i8"));
11743    }
11744    this.memoryManager.free(sizePtr);
11745    this.memoryManager.free(contentPtr);
11746    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ReadAttachmentContent\`, "End", doc.id);
11747    return PdfTaskHelper.resolve(buffer);
11748  }
11749  /**
11750   * {@inheritDoc @embedpdf/models!PdfEngine.setFormFieldValue}
11751   *
11752   * @public
11753   */
11754  setFormFieldValue(doc, page, annotation, value) {
11755    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldValue", doc, annotation, value);
11756    this.logger.perf(
11757      LOG_SOURCE$1,
11758      LOG_CATEGORY$1,
11759      \`SetFormFieldValue\`,
11760      "Begin",
11761      \`\${doc.id}-\${annotation.id}\`
11762    );
11763    const ctx = this.cache.getContext(doc.id);
11764    if (!ctx) {
11765      this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldValue", "document is not opened");
11766      this.logger.perf(
11767        LOG_SOURCE$1,
11768        LOG_CATEGORY$1,
11769        \`SetFormFieldValue\`,
11770        "End",
11771        \`\${doc.id}-\${annotation.id}\`
11772      );
11773      return PdfTaskHelper.reject({
11774        code: PdfErrorCode.DocNotOpen,
11775        message: "document does not open"
11776      });
11777    }
11778    const pageCtx = ctx.acquirePage(page.index);
11779    try {
11780      return pageCtx.withFormHandle((formHandle) => {
11781        const annotationPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
11782        if (!annotationPtr) {
11783          return PdfTaskHelper.reject({
11784            code: PdfErrorCode.NotFound,
11785            message: "annotation not found"
11786          });
11787        }
11788        try {
11789          if (!this.pdfiumModule.FORM_SetFocusedAnnot(formHandle, annotationPtr)) {
11790            return PdfTaskHelper.reject({
11791              code: PdfErrorCode.CantFocusAnnot,
11792              message: "failed to set focused annotation"
11793            });
11794          }
11795          switch (value.kind) {
11796            case "text": {
11797              if (!this.pdfiumModule.FORM_SelectAllText(formHandle, pageCtx.pagePtr)) {
11798                this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11799                return PdfTaskHelper.reject({
11800                  code: PdfErrorCode.CantSelectText,
11801                  message: "failed to select all text"
11802                });
11803              }
11804              const length = 2 * (value.text.length + 1);
11805              const textPtr = this.memoryManager.malloc(length);
11806              this.pdfiumModule.pdfium.stringToUTF16(value.text, textPtr, length);
11807              this.pdfiumModule.FORM_ReplaceSelection(formHandle, pageCtx.pagePtr, textPtr);
11808              this.memoryManager.free(textPtr);
11809              break;
11810            }
11811            case "selection": {
11812              if (!this.pdfiumModule.FORM_SetIndexSelected(
11813                formHandle,
11814                pageCtx.pagePtr,
11815                value.index,
11816                value.isSelected
11817              )) {
11818                this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11819                return PdfTaskHelper.reject({
11820                  code: PdfErrorCode.CantSelectOption,
11821                  message: "failed to set index selected"
11822                });
11823              }
11824              break;
11825            }
11826            case "checked": {
11827              const rawChecked = this.pdfiumModule.FPDFAnnot_IsChecked(formHandle, annotationPtr);
11828              const currentlyChecked = !!rawChecked;
11829              if (currentlyChecked !== value.checked) {
11830                const kReturn = 13;
11831                if (!this.pdfiumModule.FORM_OnChar(formHandle, pageCtx.pagePtr, kReturn, 0)) {
11832                  this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11833                  return PdfTaskHelper.reject({
11834                    code: PdfErrorCode.CantCheckField,
11835                    message: "failed to set field checked"
11836                  });
11837                }
11838              }
11839              break;
11840            }
11841          }
11842          this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11843          this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotationPtr);
11844          return PdfTaskHelper.resolve(true);
11845        } finally {
11846          this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
11847        }
11848      });
11849    } finally {
11850      pageCtx.release();
11851    }
11852  }
11853  /**
11854   * {@inheritDoc @embedpdf/models!PdfEngine.setFormFieldState}
11855   *
11856   * @public
11857   */
11858  setFormFieldState(doc, page, annotation, field) {
11859    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldState", doc, annotation, field);
11860    this.logger.perf(
11861      LOG_SOURCE$1,
11862      LOG_CATEGORY$1,
11863      \`SetFormFieldState\`,
11864      "Begin",
11865      \`\${doc.id}-\${annotation.id}\`
11866    );
11867    const ctx = this.cache.getContext(doc.id);
11868    if (!ctx) {
11869      this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "SetFormFieldState", "document is not opened");
11870      this.logger.perf(
11871        LOG_SOURCE$1,
11872        LOG_CATEGORY$1,
11873        \`SetFormFieldState\`,
11874        "End",
11875        \`\${doc.id}-\${annotation.id}\`
11876      );
11877      return PdfTaskHelper.reject({
11878        code: PdfErrorCode.DocNotOpen,
11879        message: "document does not open"
11880      });
11881    }
11882    const pageCtx = ctx.acquirePage(page.index);
11883    try {
11884      return pageCtx.withFormHandle((formHandle) => {
11885        const annotationPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
11886        if (!annotationPtr) {
11887          return PdfTaskHelper.reject({
11888            code: PdfErrorCode.NotFound,
11889            message: "annotation not found"
11890          });
11891        }
11892        try {
11893          if (!this.pdfiumModule.FORM_SetFocusedAnnot(formHandle, annotationPtr)) {
11894            return PdfTaskHelper.reject({
11895              code: PdfErrorCode.CantFocusAnnot,
11896              message: "failed to set focused annotation"
11897            });
11898          }
11899          switch (field.type) {
11900            case PDF_FORM_FIELD_TYPE.TEXTFIELD: {
11901              if (!this.pdfiumModule.FORM_SelectAllText(formHandle, pageCtx.pagePtr)) {
11902                this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11903                return PdfTaskHelper.reject({
11904                  code: PdfErrorCode.CantSelectText,
11905                  message: "failed to select all text"
11906                });
11907              }
11908              const length = 2 * (field.value.length + 1);
11909              const textPtr = this.memoryManager.malloc(length);
11910              this.pdfiumModule.pdfium.stringToUTF16(field.value, textPtr, length);
11911              this.pdfiumModule.FORM_ReplaceSelection(formHandle, pageCtx.pagePtr, textPtr);
11912              this.memoryManager.free(textPtr);
11913              break;
11914            }
11915            case PDF_FORM_FIELD_TYPE.CHECKBOX:
11916            case PDF_FORM_FIELD_TYPE.RADIOBUTTON: {
11917              const currentlyChecked = !!this.pdfiumModule.FPDFAnnot_IsChecked(
11918                formHandle,
11919                annotationPtr
11920              );
11921              const desiredChecked = annotation.exportValue != null && field.value === annotation.exportValue;
11922              if (currentlyChecked !== desiredChecked) {
11923                const kReturn = 13;
11924                if (!this.pdfiumModule.FORM_OnChar(formHandle, pageCtx.pagePtr, kReturn, 0)) {
11925                  this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11926                  return PdfTaskHelper.reject({
11927                    code: PdfErrorCode.CantCheckField,
11928                    message: "failed to set field checked"
11929                  });
11930                }
11931              }
11932              break;
11933            }
11934            case PDF_FORM_FIELD_TYPE.COMBOBOX: {
11935              const selectedIndex = field.options.findIndex((opt) => opt.isSelected);
11936              if (selectedIndex >= 0) {
11937                if (!this.pdfiumModule.FORM_SetIndexSelected(
11938                  formHandle,
11939                  pageCtx.pagePtr,
11940                  selectedIndex,
11941                  true
11942                )) {
11943                  this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11944                  return PdfTaskHelper.reject({
11945                    code: PdfErrorCode.CantSelectOption,
11946                    message: "failed to set index selected"
11947                  });
11948                }
11949              }
11950              break;
11951            }
11952            case PDF_FORM_FIELD_TYPE.LISTBOX: {
11953              for (let i = 0; i < field.options.length; i++) {
11954                if (!this.pdfiumModule.FORM_SetIndexSelected(
11955                  formHandle,
11956                  pageCtx.pagePtr,
11957                  i,
11958                  field.options[i].isSelected
11959                )) {
11960                  this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11961                  return PdfTaskHelper.reject({
11962                    code: PdfErrorCode.CantSelectOption,
11963                    message: "failed to set index selected"
11964                  });
11965                }
11966              }
11967              break;
11968            }
11969            default:
11970              break;
11971          }
11972          this.pdfiumModule.FORM_ForceToKillFocus(formHandle);
11973          if (field.type !== PDF_FORM_FIELD_TYPE.CHECKBOX && field.type !== PDF_FORM_FIELD_TYPE.RADIOBUTTON) {
11974            this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotationPtr);
11975          }
11976          this.logger.perf(
11977            LOG_SOURCE$1,
11978            LOG_CATEGORY$1,
11979            \`SetFormFieldState\`,
11980            "End",
11981            \`\${doc.id}-\${annotation.id}\`
11982          );
11983          return PdfTaskHelper.resolve(true);
11984        } finally {
11985          this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
11986        }
11987      });
11988    } finally {
11989      pageCtx.release();
11990    }
11991  }
11992  renameWidgetField(doc, page, annotation, name) {
11993    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "RenameWidgetField", doc, annotation, name);
11994    this.logger.perf(
11995      LOG_SOURCE$1,
11996      LOG_CATEGORY$1,
11997      \`RenameWidgetField\`,
11998      "Begin",
11999      \`\${doc.id}-\${annotation.id}\`
12000    );
12001    const ctx = this.cache.getContext(doc.id);
12002    if (!ctx) {
12003      this.logger.perf(
12004        LOG_SOURCE$1,
12005        LOG_CATEGORY$1,
12006        \`RenameWidgetField\`,
12007        "End",
12008        \`\${doc.id}-\${annotation.id}\`
12009      );
12010      return PdfTaskHelper.reject({
12011        code: PdfErrorCode.DocNotOpen,
12012        message: "document does not open"
12013      });
12014    }
12015    const pageCtx = ctx.acquirePage(page.index);
12016    try {
12017      return pageCtx.withFormHandle((formHandle) => {
12018        const annotationPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
12019        if (!annotationPtr) {
12020          return PdfTaskHelper.reject({
12021            code: PdfErrorCode.NotFound,
12022            message: "annotation not found"
12023          });
12024        }
12025        try {
12026          const ok = this.withWString(
12027            name,
12028            (namePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldName(formHandle, annotationPtr, namePtr)
12029          );
12030          if (!ok) {
12031            return PdfTaskHelper.reject({
12032              code: PdfErrorCode.CantSetAnnotString,
12033              message: "failed to rename widget field"
12034            });
12035          }
12036          this.logger.perf(
12037            LOG_SOURCE$1,
12038            LOG_CATEGORY$1,
12039            \`RenameWidgetField\`,
12040            "End",
12041            \`\${doc.id}-\${annotation.id}\`
12042          );
12043          return PdfTaskHelper.resolve(true);
12044        } finally {
12045          this.pdfiumModule.FPDFPage_CloseAnnot(annotationPtr);
12046        }
12047      });
12048    } finally {
12049      pageCtx.release();
12050    }
12051  }
12052  shareWidgetField(doc, sourcePage, sourceAnnotation, targetPage, targetAnnotation) {
12053    this.logger.debug(
12054      LOG_SOURCE$1,
12055      LOG_CATEGORY$1,
12056      "ShareWidgetField",
12057      doc,
12058      sourceAnnotation,
12059      targetAnnotation
12060    );
12061    this.logger.perf(
12062      LOG_SOURCE$1,
12063      LOG_CATEGORY$1,
12064      \`ShareWidgetField\`,
12065      "Begin",
12066      \`\${doc.id}-\${sourceAnnotation.id}-\${targetAnnotation.id}\`
12067    );
12068    const ctx = this.cache.getContext(doc.id);
12069    if (!ctx) {
12070      this.logger.perf(
12071        LOG_SOURCE$1,
12072        LOG_CATEGORY$1,
12073        \`ShareWidgetField\`,
12074        "End",
12075        \`\${doc.id}-\${sourceAnnotation.id}-\${targetAnnotation.id}\`
12076      );
12077      return PdfTaskHelper.reject({
12078        code: PdfErrorCode.DocNotOpen,
12079        message: "document does not open"
12080      });
12081    }
12082    const sourcePageCtx = ctx.acquirePage(sourcePage.index);
12083    const targetPageCtx = targetPage.index === sourcePage.index ? sourcePageCtx : ctx.acquirePage(targetPage.index);
12084    try {
12085      return sourcePageCtx.withFormHandle((formHandle) => {
12086        let targetPageLoaded = false;
12087        if (targetPageCtx !== sourcePageCtx) {
12088          this.pdfiumModule.FORM_OnAfterLoadPage(targetPageCtx.pagePtr, formHandle);
12089          targetPageLoaded = true;
12090        }
12091        const sourceAnnotationPtr = this.getAnnotationByName(
12092          sourcePageCtx.pagePtr,
12093          sourceAnnotation.id
12094        );
12095        const targetAnnotationPtr = this.getAnnotationByName(
12096          targetPageCtx.pagePtr,
12097          targetAnnotation.id
12098        );
12099        if (!sourceAnnotationPtr || !targetAnnotationPtr) {
12100          if (sourceAnnotationPtr) {
12101            this.pdfiumModule.FPDFPage_CloseAnnot(sourceAnnotationPtr);
12102          }
12103          if (targetAnnotationPtr) {
12104            this.pdfiumModule.FPDFPage_CloseAnnot(targetAnnotationPtr);
12105          }
12106          if (targetPageLoaded) {
12107            this.pdfiumModule.FORM_OnBeforeClosePage(targetPageCtx.pagePtr, formHandle);
12108          }
12109          return PdfTaskHelper.reject({
12110            code: PdfErrorCode.NotFound,
12111            message: "annotation not found"
12112          });
12113        }
12114        try {
12115          const ok = this.pdfiumModule.EPDFAnnot_ShareFormField(
12116            formHandle,
12117            sourceAnnotationPtr,
12118            targetAnnotationPtr
12119          );
12120          if (!ok) {
12121            return PdfTaskHelper.reject({
12122              code: PdfErrorCode.Unknown,
12123              message: "failed to share widget field"
12124            });
12125          }
12126          this.logger.perf(
12127            LOG_SOURCE$1,
12128            LOG_CATEGORY$1,
12129            \`ShareWidgetField\`,
12130            "End",
12131            \`\${doc.id}-\${sourceAnnotation.id}-\${targetAnnotation.id}\`
12132          );
12133          return PdfTaskHelper.resolve(true);
12134        } finally {
12135          this.pdfiumModule.FPDFPage_CloseAnnot(sourceAnnotationPtr);
12136          this.pdfiumModule.FPDFPage_CloseAnnot(targetAnnotationPtr);
12137          if (targetPageLoaded) {
12138            this.pdfiumModule.FORM_OnBeforeClosePage(targetPageCtx.pagePtr, formHandle);
12139          }
12140        }
12141      });
12142    } finally {
12143      sourcePageCtx.release();
12144      if (targetPageCtx !== sourcePageCtx) {
12145        targetPageCtx.release();
12146      }
12147    }
12148  }
12149  /**
12150   * {@inheritDoc @embedpdf/models!PdfEngine.flattenPage}
12151   *
12152   * @public
12153   */
12154  flattenPage(doc, page, options) {
12155    const { flag = PdfPageFlattenFlag.Display } = options ?? {};
12156    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "flattenPage", doc, page, flag);
12157    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`flattenPage\`, "Begin", doc.id);
12158    const ctx = this.cache.getContext(doc.id);
12159    if (!ctx) {
12160      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`flattenPage\`, "End", doc.id);
12161      return PdfTaskHelper.reject({
12162        code: PdfErrorCode.DocNotOpen,
12163        message: "document does not open"
12164      });
12165    }
12166    const pageCtx = ctx.acquirePage(page.index);
12167    const result = this.pdfiumModule.FPDFPage_Flatten(pageCtx.pagePtr, flag);
12168    pageCtx.release();
12169    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`flattenPage\`, "End", doc.id);
12170    return PdfTaskHelper.resolve(result);
12171  }
12172  /**
12173   * {@inheritDoc @embedpdf/models!PdfEngine.extractPages}
12174   *
12175   * @public
12176   */
12177  extractPages(doc, pageIndexes) {
12178    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "extractPages", doc, pageIndexes);
12179    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "Begin", doc.id);
12180    const ctx = this.cache.getContext(doc.id);
12181    if (!ctx) {
12182      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "End", doc.id);
12183      return PdfTaskHelper.reject({
12184        code: PdfErrorCode.DocNotOpen,
12185        message: "document does not open"
12186      });
12187    }
12188    const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();
12189    if (!newDocPtr) {
12190      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "End", doc.id);
12191      return PdfTaskHelper.reject({
12192        code: PdfErrorCode.CantCreateNewDoc,
12193        message: "can not create new document"
12194      });
12195    }
12196    const pageIndexesPtr = this.memoryManager.malloc(pageIndexes.length * 4);
12197    for (let i = 0; i < pageIndexes.length; i++) {
12198      this.pdfiumModule.pdfium.setValue(pageIndexesPtr + i * 4, pageIndexes[i], "i32");
12199    }
12200    if (!this.pdfiumModule.FPDF_ImportPagesByIndex(
12201      newDocPtr,
12202      ctx.docPtr,
12203      pageIndexesPtr,
12204      pageIndexes.length,
12205      0
12206    )) {
12207      this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12208      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "End", doc.id);
12209      return PdfTaskHelper.reject({
12210        code: PdfErrorCode.CantImportPages,
12211        message: "can not import pages to new document"
12212      });
12213    }
12214    const buffer = this.saveDocument(newDocPtr);
12215    this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12216    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractPages\`, "End", doc.id);
12217    return PdfTaskHelper.resolve(buffer);
12218  }
12219  /**
12220   * Import pages from a source document into a destination document.
12221   *
12222   * @param destDoc - destination document (must be open in cache)
12223   * @param srcDoc - source document (must be open in cache)
12224   * @param srcPageIndices - zero-based page indices in the source document
12225   * @param insertIndex - position to insert at in destination (defaults to end)
12226   * @returns task containing the newly added PdfPageObjects
12227   */
12228  importPages(destDoc, srcDoc, srcPageIndices, insertIndex) {
12229    this.logger.debug(
12230      LOG_SOURCE$1,
12231      LOG_CATEGORY$1,
12232      "importPages",
12233      destDoc.id,
12234      srcDoc.id,
12235      srcPageIndices
12236    );
12237    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "Begin", destDoc.id);
12238    const destCtx = this.cache.getContext(destDoc.id);
12239    if (!destCtx) {
12240      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12241      return PdfTaskHelper.reject({
12242        code: PdfErrorCode.DocNotOpen,
12243        message: "destination document is not open"
12244      });
12245    }
12246    const srcCtx = this.cache.getContext(srcDoc.id);
12247    if (!srcCtx) {
12248      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12249      return PdfTaskHelper.reject({
12250        code: PdfErrorCode.DocNotOpen,
12251        message: "source document is not open"
12252      });
12253    }
12254    const destInsertIndex = insertIndex ?? this.pdfiumModule.FPDF_GetPageCount(destCtx.docPtr);
12255    const indicesPtr = this.memoryManager.malloc(srcPageIndices.length * 4);
12256    for (let i = 0; i < srcPageIndices.length; i++) {
12257      this.pdfiumModule.pdfium.setValue(indicesPtr + i * 4, srcPageIndices[i], "i32");
12258    }
12259    if (!this.pdfiumModule.FPDF_ImportPagesByIndex(
12260      destCtx.docPtr,
12261      srcCtx.docPtr,
12262      indicesPtr,
12263      srcPageIndices.length,
12264      destInsertIndex
12265    )) {
12266      this.memoryManager.free(indicesPtr);
12267      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12268      return PdfTaskHelper.reject({
12269        code: PdfErrorCode.CantImportPages,
12270        message: "can not import pages into destination document"
12271      });
12272    }
12273    this.memoryManager.free(indicesPtr);
12274    const newPages = [];
12275    const sizePtr = this.memoryManager.malloc(8);
12276    const normalizeRotation = destCtx.normalizeRotation;
12277    for (let i = 0; i < srcPageIndices.length; i++) {
12278      const newPageIndex = destInsertIndex + i;
12279      const result = normalizeRotation ? this.pdfiumModule.EPDF_GetPageSizeByIndexNormalized(destCtx.docPtr, newPageIndex, sizePtr) : this.pdfiumModule.FPDF_GetPageSizeByIndexF(destCtx.docPtr, newPageIndex, sizePtr);
12280      if (!result) {
12281        this.memoryManager.free(sizePtr);
12282        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12283        return PdfTaskHelper.reject({
12284          code: PdfErrorCode.Unknown,
12285          message: \`failed to read metadata for imported page \${newPageIndex}\`
12286        });
12287      }
12288      const rotation = this.pdfiumModule.EPDF_GetPageRotationByIndex(
12289        destCtx.docPtr,
12290        newPageIndex
12291      );
12292      newPages.push({
12293        index: newPageIndex,
12294        size: {
12295          width: this.pdfiumModule.pdfium.getValue(sizePtr, "float"),
12296          height: this.pdfiumModule.pdfium.getValue(sizePtr + 4, "float")
12297        },
12298        rotation
12299      });
12300    }
12301    this.memoryManager.free(sizePtr);
12302    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "ImportPages", "End", destDoc.id);
12303    return PdfTaskHelper.resolve(newPages);
12304  }
12305  deletePage(doc, pageIndex) {
12306    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "deletePage", doc.id, pageIndex);
12307    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "DeletePage", "Begin", doc.id);
12308    const ctx = this.cache.getContext(doc.id);
12309    if (!ctx) {
12310      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "DeletePage", "End", doc.id);
12311      return PdfTaskHelper.reject({
12312        code: PdfErrorCode.DocNotOpen,
12313        message: "document is not open"
12314      });
12315    }
12316    const pageCount = this.pdfiumModule.FPDF_GetPageCount(ctx.docPtr);
12317    if (pageIndex < 0 || pageIndex >= pageCount) {
12318      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "DeletePage", "End", doc.id);
12319      return PdfTaskHelper.reject({
12320        code: PdfErrorCode.CantDeletePage,
12321        message: \`page index \${pageIndex} out of range (0..\${pageCount - 1})\`
12322      });
12323    }
12324    this.pdfiumModule.FPDFPage_Delete(ctx.docPtr, pageIndex);
12325    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "DeletePage", "End", doc.id);
12326    return PdfTaskHelper.resolve(true);
12327  }
12328  /**
12329   * {@inheritDoc @embedpdf/models!PdfEngine.extractText}
12330   *
12331   * @public
12332   */
12333  extractText(doc, pageIndexes) {
12334    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "extractText", doc, pageIndexes);
12335    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractText\`, "Begin", doc.id);
12336    const ctx = this.cache.getContext(doc.id);
12337    if (!ctx) {
12338      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractText\`, "End", doc.id);
12339      return PdfTaskHelper.reject({
12340        code: PdfErrorCode.DocNotOpen,
12341        message: "document does not open"
12342      });
12343    }
12344    const strings = [];
12345    for (let i = 0; i < pageIndexes.length; i++) {
12346      const pageCtx = ctx.acquirePage(pageIndexes[i]);
12347      const textPagePtr = this.pdfiumModule.FPDFText_LoadPage(pageCtx.pagePtr);
12348      const charCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
12349      const bufferPtr = this.memoryManager.malloc((charCount + 1) * 2);
12350      this.pdfiumModule.FPDFText_GetText(textPagePtr, 0, charCount, bufferPtr);
12351      const text2 = this.pdfiumModule.pdfium.UTF16ToString(bufferPtr);
12352      this.memoryManager.free(bufferPtr);
12353      strings.push(text2);
12354      this.pdfiumModule.FPDFText_ClosePage(textPagePtr);
12355      pageCtx.release();
12356    }
12357    const text = strings.join("\\n\\n");
12358    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`ExtractText\`, "End", doc.id);
12359    return PdfTaskHelper.resolve(text);
12360  }
12361  /**
12362   * {@inheritDoc @embedpdf/models!PdfEngine.getTextSlices}
12363   *
12364   * @public
12365   */
12366  getTextSlices(doc, slices) {
12367    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getTextSlices", doc, slices);
12368    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "Begin", doc.id);
12369    if (slices.length === 0) {
12370      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);
12371      return PdfTaskHelper.resolve([]);
12372    }
12373    const ctx = this.cache.getContext(doc.id);
12374    if (!ctx) {
12375      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);
12376      return PdfTaskHelper.reject({
12377        code: PdfErrorCode.DocNotOpen,
12378        message: "document does not open"
12379      });
12380    }
12381    try {
12382      const out = new Array(slices.length);
12383      const byPage = /* @__PURE__ */ new Map();
12384      slices.forEach((s, i) => {
12385        (byPage.get(s.pageIndex) ?? byPage.set(s.pageIndex, []).get(s.pageIndex)).push({
12386          slice: s,
12387          pos: i
12388        });
12389      });
12390      for (const [pageIdx, list] of byPage) {
12391        const pageCtx = ctx.acquirePage(pageIdx);
12392        const textPagePtr = pageCtx.getTextPage();
12393        for (const { slice, pos } of list) {
12394          const bufPtr = this.memoryManager.malloc(2 * (slice.charCount + 1));
12395          this.pdfiumModule.FPDFText_GetText(textPagePtr, slice.charIndex, slice.charCount, bufPtr);
12396          out[pos] = stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(bufPtr));
12397          this.memoryManager.free(bufPtr);
12398        }
12399        pageCtx.release();
12400      }
12401      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);
12402      return PdfTaskHelper.resolve(out);
12403    } catch (e) {
12404      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "getTextSlices error", e);
12405      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetTextSlices", "End", doc.id);
12406      return PdfTaskHelper.reject({
12407        code: PdfErrorCode.Unknown,
12408        message: String(e)
12409      });
12410    }
12411  }
12412  /**
12413   * {@inheritDoc @embedpdf/models!PdfEngine.merge}
12414   *
12415   * @public
12416   */
12417  merge(files) {
12418    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "merge", files);
12419    const fileIds = files.map((file2) => file2.id).join(".");
12420    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "Begin", fileIds);
12421    const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();
12422    if (!newDocPtr) {
12423      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "End", fileIds);
12424      return PdfTaskHelper.reject({
12425        code: PdfErrorCode.CantCreateNewDoc,
12426        message: "can not create new document"
12427      });
12428    }
12429    const ptrs = [];
12430    for (const file2 of files.reverse()) {
12431      const array = new Uint8Array(file2.content);
12432      const length = array.length;
12433      const filePtr = this.memoryManager.malloc(length);
12434      this.pdfiumModule.pdfium.HEAPU8.set(array, filePtr);
12435      const docPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, length, "");
12436      if (!docPtr) {
12437        const lastError = this.pdfiumModule.FPDF_GetLastError();
12438        this.logger.error(
12439          LOG_SOURCE$1,
12440          LOG_CATEGORY$1,
12441          \`FPDF_LoadMemDocument failed with \${lastError}\`
12442        );
12443        this.memoryManager.free(filePtr);
12444        for (const ptr of ptrs) {
12445          this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);
12446          this.memoryManager.free(ptr.filePtr);
12447        }
12448        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "End", fileIds);
12449        return PdfTaskHelper.reject({
12450          code: lastError,
12451          message: \`FPDF_LoadMemDocument failed\`
12452        });
12453      }
12454      ptrs.push({ filePtr, docPtr });
12455      if (!this.pdfiumModule.FPDF_ImportPages(newDocPtr, docPtr, "", 0)) {
12456        this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12457        for (const ptr of ptrs) {
12458          this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);
12459          this.memoryManager.free(ptr.filePtr);
12460        }
12461        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "End", fileIds);
12462        return PdfTaskHelper.reject({
12463          code: PdfErrorCode.CantImportPages,
12464          message: "can not import pages to new document"
12465        });
12466      }
12467    }
12468    const buffer = this.saveDocument(newDocPtr);
12469    this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12470    for (const ptr of ptrs) {
12471      this.pdfiumModule.FPDF_CloseDocument(ptr.docPtr);
12472      this.memoryManager.free(ptr.filePtr);
12473    }
12474    const file = {
12475      id: \`\${Math.random()}\`,
12476      content: buffer
12477    };
12478    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`Merge\`, "End", fileIds);
12479    return PdfTaskHelper.resolve(file);
12480  }
12481  /**
12482   * Merges specific pages from multiple PDF documents in a custom order
12483   *
12484   * @param mergeConfigs Array of configurations specifying which pages to merge from which documents
12485   * @returns A PdfTask that resolves with the merged PDF file
12486   * @public
12487   */
12488  mergePages(mergeConfigs) {
12489    const configIds = mergeConfigs.map((config) => \`\${config.docId}:\${config.pageIndices.join(",")}\`).join("|");
12490    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "mergePages", mergeConfigs);
12491    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`MergePages\`, "Begin", configIds);
12492    const newDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();
12493    if (!newDocPtr) {
12494      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`MergePages\`, "End", configIds);
12495      return PdfTaskHelper.reject({
12496        code: PdfErrorCode.CantCreateNewDoc,
12497        message: "Cannot create new document"
12498      });
12499    }
12500    try {
12501      for (const config of [...mergeConfigs].reverse()) {
12502        const ctx = this.cache.getContext(config.docId);
12503        if (!ctx) {
12504          this.logger.warn(
12505            LOG_SOURCE$1,
12506            LOG_CATEGORY$1,
12507            \`Document \${config.docId} is not open, skipping\`
12508          );
12509          continue;
12510        }
12511        const pageCount = this.pdfiumModule.FPDF_GetPageCount(ctx.docPtr);
12512        const validPageIndices = config.pageIndices.filter(
12513          (index) => index >= 0 && index < pageCount
12514        );
12515        if (validPageIndices.length === 0) {
12516          continue;
12517        }
12518        const pageString = validPageIndices.map((index) => index + 1).join(",");
12519        try {
12520          if (!this.pdfiumModule.FPDF_ImportPages(
12521            newDocPtr,
12522            ctx.docPtr,
12523            pageString,
12524            0
12525            // Insert at the beginning
12526          )) {
12527            throw new Error(\`Failed to import pages \${pageString} from document \${config.docId}\`);
12528          }
12529        } finally {
12530        }
12531      }
12532      const buffer = this.saveDocument(newDocPtr);
12533      const file = {
12534        id: \`\${Math.random()}\`,
12535        content: buffer
12536      };
12537      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`MergePages\`, "End", configIds);
12538      return PdfTaskHelper.resolve(file);
12539    } catch (error) {
12540      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "mergePages failed", error);
12541      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`MergePages\`, "End", configIds);
12542      return PdfTaskHelper.reject({
12543        code: PdfErrorCode.CantImportPages,
12544        message: error instanceof Error ? error.message : "Failed to merge pages"
12545      });
12546    } finally {
12547      if (newDocPtr) {
12548        this.pdfiumModule.FPDF_CloseDocument(newDocPtr);
12549      }
12550    }
12551  }
12552  /**
12553   * Sets AES-256 encryption on a document.
12554   * Must be called before saveAsCopy() for encryption to take effect.
12555   *
12556   * @param doc - Document to encrypt
12557   * @param userPassword - Password to open document (empty = no open password)
12558   * @param ownerPassword - Password to change permissions (required)
12559   * @param allowedFlags - OR'd PdfPermissionFlag values indicating allowed actions
12560   * @returns true on success, false if already encrypted or invalid params
12561   *
12562   * @public
12563   */
12564  setDocumentEncryption(doc, userPassword, ownerPassword, allowedFlags) {
12565    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "setDocumentEncryption", doc, allowedFlags);
12566    const ctx = this.cache.getContext(doc.id);
12567    if (!ctx) {
12568      return PdfTaskHelper.reject({
12569        code: PdfErrorCode.DocNotOpen,
12570        message: "document does not open"
12571      });
12572    }
12573    const result = this.pdfiumModule.EPDF_SetEncryption(
12574      ctx.docPtr,
12575      userPassword,
12576      ownerPassword,
12577      allowedFlags
12578    );
12579    return PdfTaskHelper.resolve(result);
12580  }
12581  /**
12582   * Marks document for encryption removal on save.
12583   * When saveAsCopy is called, the document will be saved without encryption.
12584   *
12585   * @param doc - Document to remove encryption from
12586   * @returns true on success
12587   *
12588   * @public
12589   */
12590  removeEncryption(doc) {
12591    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "removeEncryption", doc);
12592    const ctx = this.cache.getContext(doc.id);
12593    if (!ctx) {
12594      return PdfTaskHelper.reject({
12595        code: PdfErrorCode.DocNotOpen,
12596        message: "document does not open"
12597      });
12598    }
12599    const result = this.pdfiumModule.EPDF_RemoveEncryption(ctx.docPtr);
12600    return PdfTaskHelper.resolve(result);
12601  }
12602  /**
12603   * Attempts to unlock owner permissions for an already-opened encrypted document.
12604   *
12605   * @param doc - Document to unlock
12606   * @param ownerPassword - The owner password
12607   * @returns true on success, false on failure
12608   *
12609   * @public
12610   */
12611  unlockOwnerPermissions(doc, ownerPassword) {
12612    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "unlockOwnerPermissions", doc.id);
12613    const ctx = this.cache.getContext(doc.id);
12614    if (!ctx) {
12615      return PdfTaskHelper.reject({
12616        code: PdfErrorCode.DocNotOpen,
12617        message: "document does not open"
12618      });
12619    }
12620    const success = this.pdfiumModule.EPDF_UnlockOwnerPermissions(ctx.docPtr, ownerPassword);
12621    return PdfTaskHelper.resolve(success);
12622  }
12623  /**
12624   * Check if a document is encrypted.
12625   *
12626   * @param doc - Document to check
12627   * @returns true if the document is encrypted
12628   *
12629   * @public
12630   */
12631  isEncrypted(doc) {
12632    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "isEncrypted", 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 result = this.pdfiumModule.EPDF_IsEncrypted(ctx.docPtr);
12641    return PdfTaskHelper.resolve(result);
12642  }
12643  /**
12644   * Check if owner permissions are currently unlocked.
12645   *
12646   * @param doc - Document to check
12647   * @returns true if owner permissions are unlocked
12648   *
12649   * @public
12650   */
12651  isOwnerUnlocked(doc) {
12652    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "isOwnerUnlocked", 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_IsOwnerUnlocked(ctx.docPtr);
12661    return PdfTaskHelper.resolve(result);
12662  }
12663  /**
12664   * {@inheritDoc @embedpdf/models!PdfEngine.saveAsCopy}
12665   *
12666   * @public
12667   */
12668  saveAsCopy(doc) {
12669    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "saveAsCopy", doc);
12670    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SaveAsCopy\`, "Begin", doc.id);
12671    const ctx = this.cache.getContext(doc.id);
12672    if (!ctx) {
12673      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SaveAsCopy\`, "End", doc.id);
12674      return PdfTaskHelper.reject({
12675        code: PdfErrorCode.DocNotOpen,
12676        message: "document does not open"
12677      });
12678    }
12679    const buffer = this.saveDocument(ctx.docPtr);
12680    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SaveAsCopy\`, "End", doc.id);
12681    return PdfTaskHelper.resolve(buffer);
12682  }
12683  /**
12684   * {@inheritDoc @embedpdf/models!PdfEngine.closeDocument}
12685   *
12686   * @public
12687   */
12688  closeDocument(doc) {
12689    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "closeDocument", doc);
12690    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`CloseDocument\`, "Begin", doc.id);
12691    this.cache.closeDocument(doc.id);
12692    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`CloseDocument\`, "End", doc.id);
12693    return PdfTaskHelper.resolve(true);
12694  }
12695  /**
12696   * {@inheritDoc @embedpdf/models!PdfEngine.closeAllDocuments}
12697   *
12698   * @public
12699   */
12700  closeAllDocuments() {
12701    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "closeAllDocuments");
12702    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`CloseAllDocuments\`, "Begin");
12703    this.cache.closeAllDocuments();
12704    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`CloseAllDocuments\`, "End");
12705    return PdfTaskHelper.resolve(true);
12706  }
12707  /**
12708   * Add text content to annotation
12709   * @param page - page info
12710   * @param pagePtr - pointer to page object
12711   * @param annotationPtr - pointer to text annotation
12712   * @param annotation - text annotation
12713   * @returns whether text content is added to annotation
12714   *
12715   * @private
12716   */
12717  addTextContent(doc, page, pagePtr, annotationPtr, annotation) {
12718    if (!this.setAnnotationName(
12719      annotationPtr,
12720      annotation.name ?? annotation.icon ?? PdfAnnotationName.Comment
12721    )) {
12722      return false;
12723    }
12724    if (annotation.state && !this.setAnnotString(annotationPtr, "State", annotation.state)) {
12725      return false;
12726    }
12727    if (annotation.stateModel && !this.setAnnotString(annotationPtr, "StateModel", annotation.stateModel)) {
12728      return false;
12729    }
12730    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
12731      return false;
12732    }
12733    const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";
12734    if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {
12735      return false;
12736    }
12737    if (!annotation.flags) {
12738      if (!this.setAnnotationFlags(annotationPtr, ["print", "noZoom", "noRotate"])) {
12739        return false;
12740      }
12741    }
12742    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
12743  }
12744  /**
12745   * Add caret content to annotation
12746   * @param doc - document object
12747   * @param page - page info
12748   * @param pagePtr - pointer to page object
12749   * @param annotationPtr - pointer to caret annotation
12750   * @param annotation - caret annotation
12751   * @returns whether caret content is added to annotation
12752   *
12753   * @private
12754   */
12755  addCaretContent(doc, page, pagePtr, annotationPtr, annotation) {
12756    if (annotation.strokeColor) {
12757      this.setAnnotationColor(annotationPtr, annotation.strokeColor, PdfAnnotationColorType.Color);
12758    }
12759    if (annotation.opacity !== void 0) {
12760      this.setAnnotationOpacity(annotationPtr, annotation.opacity);
12761    }
12762    if (annotation.intent) {
12763      this.setAnnotIntent(annotationPtr, annotation.intent);
12764    }
12765    this.setRectangleDifferences(annotationPtr, annotation.rectangleDifferences);
12766    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
12767  }
12768  /**
12769   * Add free text content to annotation
12770   * @param page - page info
12771   * @param pagePtr - pointer to page object
12772   * @param annotationPtr - pointer to free text annotation
12773   * @param annotation - free text annotation
12774   * @returns whether free text content is added to annotation
12775   *
12776   * @private
12777   */
12778  addFreeTextContent(doc, page, pagePtr, annotationPtr, annotation) {
12779    if (!this.setBorderStyle(annotationPtr, PdfAnnotationBorderStyle.SOLID, 0)) {
12780      return false;
12781    }
12782    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
12783      return false;
12784    }
12785    if (!this.setAnnotationTextAlignment(annotationPtr, annotation.textAlign)) {
12786      return false;
12787    }
12788    if (!this.setAnnotationVerticalAlignment(annotationPtr, annotation.verticalAlign)) {
12789      return false;
12790    }
12791    if (!this.setAnnotationDefaultAppearance(
12792      annotationPtr,
12793      annotation.fontFamily === PdfStandardFont.Unknown ? PdfStandardFont.Helvetica : annotation.fontFamily,
12794      annotation.fontSize,
12795      annotation.fontColor
12796    )) {
12797      return false;
12798    }
12799    if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {
12800      return false;
12801    }
12802    const bgColor = annotation.color ?? annotation.backgroundColor;
12803    if (!bgColor || bgColor === "transparent") {
12804      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.Color)) {
12805        return false;
12806      }
12807    } else if (!this.setAnnotationColor(annotationPtr, bgColor ?? "#FFFFFF", PdfAnnotationColorType.Color)) {
12808      return false;
12809    }
12810    this.setRectangleDifferences(annotationPtr, annotation.rectangleDifferences);
12811    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
12812  }
12813  addTextFieldContent(formHandle, annotationPtr, annotation) {
12814    if (!this.setAnnotationDefaultAppearance(
12815      annotationPtr,
12816      annotation.fontFamily,
12817      annotation.fontSize,
12818      annotation.fontColor
12819    )) {
12820      return false;
12821    }
12822    if (!this.setBorderStyle(
12823      annotationPtr,
12824      PdfAnnotationBorderStyle.SOLID,
12825      annotation.strokeWidth ?? 1
12826    )) {
12827      return false;
12828    }
12829    if (annotation.strokeColor && annotation.strokeColor !== "transparent") {
12830      this.setMKColor(annotationPtr, 0, annotation.strokeColor);
12831    } else {
12832      this.clearMKColor(annotationPtr, 0);
12833    }
12834    if (annotation.color && annotation.color !== "transparent") {
12835      this.setMKColor(annotationPtr, 1, annotation.color);
12836    } else {
12837      this.clearMKColor(annotationPtr, 1);
12838    }
12839    const userFlags = annotation.field.flag ?? PDF_FORM_FIELD_FLAG.NONE;
12840    this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(formHandle, annotationPtr, userFlags);
12841    if (annotation.field.name) {
12842      this.withWString(
12843        annotation.field.name,
12844        (namePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldName(formHandle, annotationPtr, namePtr)
12845      );
12846    }
12847    this.withWString(
12848      annotation.field.value ?? "",
12849      (valuePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldValue(formHandle, annotationPtr, valuePtr)
12850    );
12851    const textField = annotation.field;
12852    if (textField.maxLen != null && textField.maxLen > 0) {
12853      this.pdfiumModule.EPDFAnnot_SetNumberValue(annotationPtr, "MaxLen", textField.maxLen);
12854    }
12855    return true;
12856  }
12857  addToggleFieldContent(formHandle, annotationPtr, annotation) {
12858    if (!this.setBorderStyle(
12859      annotationPtr,
12860      PdfAnnotationBorderStyle.SOLID,
12861      annotation.strokeWidth ?? 1
12862    )) {
12863      return false;
12864    }
12865    if (annotation.strokeColor && annotation.strokeColor !== "transparent") {
12866      this.setMKColor(annotationPtr, 0, annotation.strokeColor);
12867    } else {
12868      this.clearMKColor(annotationPtr, 0);
12869    }
12870    if (annotation.color && annotation.color !== "transparent") {
12871      this.setMKColor(annotationPtr, 1, annotation.color);
12872    } else {
12873      this.clearMKColor(annotationPtr, 1);
12874    }
12875    let finalFlags = annotation.field.flag ?? PDF_FORM_FIELD_FLAG.NONE;
12876    if (annotation.field.type === PDF_FORM_FIELD_TYPE.RADIOBUTTON) {
12877      finalFlags |= PDF_FORM_FIELD_FLAG.BUTTON_RADIO | PDF_FORM_FIELD_FLAG.BUTTON_NOTOGGLETOOFF;
12878    }
12879    this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(formHandle, annotationPtr, finalFlags);
12880    if (annotation.field.name) {
12881      this.withWString(
12882        annotation.field.name,
12883        (namePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldName(formHandle, annotationPtr, namePtr)
12884      );
12885    }
12886    return true;
12887  }
12888  addChoiceFieldContent(formHandle, annotationPtr, annotation) {
12889    if (!this.setAnnotationDefaultAppearance(
12890      annotationPtr,
12891      annotation.fontFamily,
12892      annotation.fontSize,
12893      annotation.fontColor
12894    )) {
12895      return false;
12896    }
12897    if (!this.setBorderStyle(
12898      annotationPtr,
12899      PdfAnnotationBorderStyle.SOLID,
12900      annotation.strokeWidth ?? 1
12901    )) {
12902      return false;
12903    }
12904    if (annotation.strokeColor && annotation.strokeColor !== "transparent") {
12905      this.setMKColor(annotationPtr, 0, annotation.strokeColor);
12906    } else {
12907      this.clearMKColor(annotationPtr, 0);
12908    }
12909    if (annotation.color && annotation.color !== "transparent") {
12910      this.setMKColor(annotationPtr, 1, annotation.color);
12911    } else {
12912      this.clearMKColor(annotationPtr, 1);
12913    }
12914    let choiceFlags = annotation.field.flag ?? PDF_FORM_FIELD_FLAG.NONE;
12915    if (annotation.field.type === PDF_FORM_FIELD_TYPE.COMBOBOX) {
12916      choiceFlags |= 1 << 17;
12917    }
12918    this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(formHandle, annotationPtr, choiceFlags);
12919    if (annotation.field.name) {
12920      this.withWString(
12921        annotation.field.name,
12922        (namePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldName(formHandle, annotationPtr, namePtr)
12923      );
12924    }
12925    const field = annotation.field;
12926    const options = field.options ?? [];
12927    if (options.length > 0) {
12928      const ptrSize = 4;
12929      const arrayPtr = this.memoryManager.malloc(options.length * ptrSize);
12930      const labelPtrs = [];
12931      try {
12932        for (let i = 0; i < options.length; i++) {
12933          const label = options[i].label;
12934          const byteLen = (label.length + 1) * 2;
12935          const labelPtr = this.memoryManager.malloc(byteLen);
12936          this.pdfiumModule.pdfium.stringToUTF16(label, labelPtr, byteLen);
12937          labelPtrs.push(labelPtr);
12938          this.pdfiumModule.pdfium.setValue(arrayPtr + i * ptrSize, labelPtr, "*");
12939        }
12940        this.pdfiumModule.EPDFAnnot_SetFormFieldOptions(
12941          formHandle,
12942          annotationPtr,
12943          arrayPtr,
12944          options.length
12945        );
12946      } finally {
12947        for (const ptr of labelPtrs) {
12948          this.memoryManager.free(WasmPointer(ptr));
12949        }
12950        this.memoryManager.free(arrayPtr);
12951      }
12952    }
12953    const selectedOption = options.find((opt) => opt.isSelected);
12954    const value = (selectedOption == null ? void 0 : selectedOption.label) ?? annotation.field.value ?? "";
12955    this.withWString(
12956      value,
12957      (valuePtr) => this.pdfiumModule.EPDFAnnot_SetFormFieldValue(formHandle, annotationPtr, valuePtr)
12958    );
12959    return true;
12960  }
12961  setMKColor(annotationPtr, mkType, webColor) {
12962    const { red, green, blue } = webColorToPdfColor(webColor);
12963    return this.pdfiumModule.EPDFAnnot_SetMKColor(
12964      annotationPtr,
12965      mkType,
12966      red & 255,
12967      green & 255,
12968      blue & 255
12969    );
12970  }
12971  clearMKColor(annotationPtr, mkType) {
12972    return this.pdfiumModule.EPDFAnnot_ClearMKColor(annotationPtr, mkType);
12973  }
12974  getMKColor(annotationPtr, mkType) {
12975    const rPtr = this.memoryManager.malloc(4);
12976    const gPtr = this.memoryManager.malloc(4);
12977    const bPtr = this.memoryManager.malloc(4);
12978    try {
12979      const ok = this.pdfiumModule.EPDFAnnot_GetMKColor(annotationPtr, mkType, rPtr, gPtr, bPtr);
12980      if (!ok) return void 0;
12981      const r = this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255;
12982      const g = this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255;
12983      const b = this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255;
12984      return pdfColorToWebColor({ red: r, green: g, blue: b });
12985    } finally {
12986      this.memoryManager.free(bPtr);
12987      this.memoryManager.free(gPtr);
12988      this.memoryManager.free(rPtr);
12989    }
12990  }
12991  /**
12992   * Set the rect of specified annotation
12993   * @param page - page info that the annotation is belonged to
12994   * @param pagePtr - pointer of page object
12995   * @param annotationPtr - pointer to annotation object
12996   * @param inkList - ink lists that added to the annotation
12997   * @returns whether the ink lists is setted
12998   *
12999   * @private
13000   */
13001  addInkStroke(doc, page, pagePtr, annotationPtr, annotation) {
13002    if (!this.setBorderStyle(annotationPtr, PdfAnnotationBorderStyle.SOLID, annotation.strokeWidth)) {
13003      return false;
13004    }
13005    if (!this.setInkList(doc, page, annotationPtr, annotation.inkList)) {
13006      return false;
13007    }
13008    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13009      return false;
13010    }
13011    const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";
13012    if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {
13013      return false;
13014    }
13015    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13016  }
13017  /**
13018   * Add line content to annotation
13019   * @param page - page info
13020   * @param pagePtr - pointer to page object
13021   * @param annotationPtr - pointer to line annotation
13022   * @param annotation - line annotation
13023   * @returns whether line content is added to annotation
13024   *
13025   * @private
13026   */
13027  addLineContent(doc, page, pagePtr, annotationPtr, annotation) {
13028    var _a, _b;
13029    if (!this.setLinePoints(
13030      doc,
13031      page,
13032      annotationPtr,
13033      annotation.linePoints.start,
13034      annotation.linePoints.end
13035    )) {
13036      return false;
13037    }
13038    if (!this.setLineEndings(
13039      annotationPtr,
13040      ((_a = annotation.lineEndings) == null ? void 0 : _a.start) ?? PdfAnnotationLineEnding.None,
13041      ((_b = annotation.lineEndings) == null ? void 0 : _b.end) ?? PdfAnnotationLineEnding.None
13042    )) {
13043      return false;
13044    }
13045    if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {
13046      return false;
13047    }
13048    if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {
13049      return false;
13050    }
13051    if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {
13052      return false;
13053    }
13054    if (!annotation.color || annotation.color === "transparent") {
13055      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {
13056        return false;
13057      }
13058    } else if (!this.setAnnotationColor(
13059      annotationPtr,
13060      annotation.color ?? "#FFFF00",
13061      PdfAnnotationColorType.InteriorColor
13062    )) {
13063      return false;
13064    }
13065    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13066      return false;
13067    }
13068    if (!this.setAnnotationColor(
13069      annotationPtr,
13070      annotation.strokeColor ?? "#FFFF00",
13071      PdfAnnotationColorType.Color
13072    )) {
13073      return false;
13074    }
13075    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13076  }
13077  /**
13078   * Add polygon or polyline content to annotation
13079   * @param page - page info
13080   * @param pagePtr - pointer to page object
13081   * @param annotationPtr - pointer to polygon or polyline annotation
13082   * @param annotation - polygon or polyline annotation
13083   * @returns whether polygon or polyline content is added to annotation
13084   *
13085   * @private
13086   */
13087  addPolyContent(doc, page, pagePtr, annotationPtr, annotation) {
13088    var _a, _b;
13089    if (annotation.type === PdfAnnotationSubtype.POLYLINE && !this.setLineEndings(
13090      annotationPtr,
13091      ((_a = annotation.lineEndings) == null ? void 0 : _a.start) ?? PdfAnnotationLineEnding.None,
13092      ((_b = annotation.lineEndings) == null ? void 0 : _b.end) ?? PdfAnnotationLineEnding.None
13093    )) {
13094      return false;
13095    }
13096    if (!this.setPdfAnnoVertices(doc, page, annotationPtr, annotation.vertices)) {
13097      return false;
13098    }
13099    if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {
13100      return false;
13101    }
13102    if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {
13103      return false;
13104    }
13105    if (annotation.intent && !this.setAnnotIntent(annotationPtr, annotation.intent)) {
13106      return false;
13107    }
13108    if (!annotation.color || annotation.color === "transparent") {
13109      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {
13110        return false;
13111      }
13112    } else if (!this.setAnnotationColor(
13113      annotationPtr,
13114      annotation.color ?? "#FFFF00",
13115      PdfAnnotationColorType.InteriorColor
13116    )) {
13117      return false;
13118    }
13119    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13120      return false;
13121    }
13122    if (!this.setAnnotationColor(
13123      annotationPtr,
13124      annotation.strokeColor ?? "#FFFF00",
13125      PdfAnnotationColorType.Color
13126    )) {
13127      return false;
13128    }
13129    if (annotation.type === PdfAnnotationSubtype.POLYGON) {
13130      const poly = annotation;
13131      this.setRectangleDifferences(annotationPtr, poly.rectangleDifferences);
13132      this.setBorderEffect(annotationPtr, poly.cloudyBorderIntensity);
13133    }
13134    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13135  }
13136  /**
13137   * Add link content (action or destination) to a link annotation
13138   * @param docPtr - pointer to pdf document
13139   * @param pagePtr - pointer to the page
13140   * @param annotationPtr - pointer to pdf annotation
13141   * @param annotation - the link annotation object
13142   * @returns true if successful
13143   *
13144   * @private
13145   */
13146  addLinkContent(doc, page, docPtr, pagePtr, annotationPtr, annotation) {
13147    const style = annotation.strokeStyle ?? PdfAnnotationBorderStyle.UNDERLINE;
13148    const width = annotation.strokeWidth ?? 2;
13149    if (!this.setBorderStyle(annotationPtr, style, width)) {
13150      return false;
13151    }
13152    if (annotation.strokeDashArray && !this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray)) {
13153      return false;
13154    }
13155    if (annotation.strokeColor) {
13156      if (!this.setAnnotationColor(
13157        annotationPtr,
13158        annotation.strokeColor,
13159        PdfAnnotationColorType.Color
13160      )) {
13161        return false;
13162      }
13163    }
13164    if (annotation.target) {
13165      if (!this.applyLinkTarget(docPtr, annotationPtr, annotation.target)) {
13166        return false;
13167      }
13168    }
13169    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13170  }
13171  /**
13172   * Add shape content to annotation
13173   * @param page - page info
13174   * @param pagePtr - pointer to page object
13175   * @param annotationPtr - pointer to shape annotation
13176   * @param annotation - shape annotation
13177   * @returns whether shape content is added to annotation
13178   *
13179   * @private
13180   */
13181  addShapeContent(doc, page, pagePtr, annotationPtr, annotation) {
13182    if (!this.setBorderStyle(annotationPtr, annotation.strokeStyle, annotation.strokeWidth)) {
13183      return false;
13184    }
13185    if (!this.setBorderDashPattern(annotationPtr, annotation.strokeDashArray ?? [])) {
13186      return false;
13187    }
13188    if (!annotation.color || annotation.color === "transparent") {
13189      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {
13190        return false;
13191      }
13192    } else if (!this.setAnnotationColor(
13193      annotationPtr,
13194      annotation.color ?? "#FFFF00",
13195      PdfAnnotationColorType.InteriorColor
13196    )) {
13197      return false;
13198    }
13199    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13200      return false;
13201    }
13202    if (!this.setAnnotationColor(
13203      annotationPtr,
13204      annotation.strokeColor ?? "#FFFF00",
13205      PdfAnnotationColorType.Color
13206    )) {
13207      return false;
13208    }
13209    this.setRectangleDifferences(annotationPtr, annotation.rectangleDifferences);
13210    this.setBorderEffect(annotationPtr, annotation.cloudyBorderIntensity);
13211    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13212  }
13213  /**
13214   * Add highlight content to annotation
13215   * @param page - page info
13216   * @param annotationPtr - pointer to highlight annotation
13217   * @param annotation - highlight annotation
13218   * @returns whether highlight content is added to annotation
13219   *
13220   * @private
13221   */
13222  addTextMarkupContent(doc, page, pagePtr, annotationPtr, annotation) {
13223    if (!this.syncQuadPointsAnno(doc, page, annotationPtr, annotation.segmentRects)) {
13224      return false;
13225    }
13226    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13227      return false;
13228    }
13229    const strokeColor = annotation.strokeColor ?? annotation.color ?? "#FFFF00";
13230    if (!this.setAnnotationColor(annotationPtr, strokeColor, PdfAnnotationColorType.Color)) {
13231      return false;
13232    }
13233    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13234  }
13235  /**
13236   * Add content to redact annotation
13237   * @param page - page info
13238   * @param pagePtr - pointer to page object
13239   * @param annotationPtr - pointer to redact annotation
13240   * @param annotation - redact annotation
13241   * @returns whether redact content is added to annotation
13242   *
13243   * @private
13244   */
13245  addRedactContent(doc, page, pagePtr, annotationPtr, annotation) {
13246    if (!this.syncQuadPointsAnno(doc, page, annotationPtr, annotation.segmentRects)) {
13247      return false;
13248    }
13249    if (!this.setAnnotationOpacity(annotationPtr, annotation.opacity ?? 1)) {
13250      return false;
13251    }
13252    if (!annotation.color || annotation.color === "transparent") {
13253      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.InteriorColor)) {
13254        return false;
13255      }
13256    } else if (!this.setAnnotationColor(
13257      annotationPtr,
13258      annotation.color,
13259      PdfAnnotationColorType.InteriorColor
13260    )) {
13261      return false;
13262    }
13263    if (!annotation.overlayColor || annotation.overlayColor === "transparent") {
13264      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.OverlayColor)) {
13265        return false;
13266      }
13267    } else if (!this.setAnnotationColor(
13268      annotationPtr,
13269      annotation.overlayColor,
13270      PdfAnnotationColorType.OverlayColor
13271    )) {
13272      return false;
13273    }
13274    if (!annotation.strokeColor || annotation.strokeColor === "transparent") {
13275      if (!this.pdfiumModule.EPDFAnnot_ClearColor(annotationPtr, PdfAnnotationColorType.Color)) {
13276        return false;
13277      }
13278    } else if (!this.setAnnotationColor(annotationPtr, annotation.strokeColor, PdfAnnotationColorType.Color)) {
13279      return false;
13280    }
13281    if (!this.setOverlayText(annotationPtr, annotation.overlayText)) {
13282      return false;
13283    }
13284    if (annotation.overlayTextRepeat !== void 0 && !this.setOverlayTextRepeat(annotationPtr, annotation.overlayTextRepeat)) {
13285      return false;
13286    }
13287    if (annotation.fontFamily !== void 0 || annotation.fontSize !== void 0) {
13288      const font = annotation.fontFamily == null || annotation.fontFamily === PdfStandardFont.Unknown ? PdfStandardFont.Helvetica : annotation.fontFamily;
13289      if (!this.setAnnotationDefaultAppearance(
13290        annotationPtr,
13291        font,
13292        annotation.fontSize ?? 12,
13293        annotation.fontColor ?? "#000000"
13294      )) {
13295        return false;
13296      }
13297    }
13298    if (annotation.textAlign !== void 0 && !this.setAnnotationTextAlignment(annotationPtr, annotation.textAlign)) {
13299      return false;
13300    }
13301    return this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation);
13302  }
13303  /**
13304   * Add contents to stamp annotation
13305   * @param doc - pdf document object
13306   * @param docPtr - pointer to pdf document object
13307   * @param page - page info
13308   * @param pagePtr - pointer to page object
13309   * @param annotationPtr - pointer to stamp annotation
13310   * @param rect - rect of stamp annotation
13311   * @param contents - contents of stamp annotation
13312   * @returns whether contents is added to annotation
13313   *
13314   * @private
13315   */
13316  addStampContent(doc, docPtr, page, pagePtr, annotationPtr, annotation, context) {
13317    const stampName = annotation.name ?? annotation.icon;
13318    if (stampName && !this.setAnnotationName(annotationPtr, stampName)) {
13319      return false;
13320    }
13321    if (context && "data" in context && context.data) {
13322      const meta = getImageMetadata(context.data);
13323      if (!meta) return false;
13324      if (meta.mimeType === "application/pdf") {
13325        if (!this.setAppearanceFromPdf(docPtr, annotationPtr, context.data)) {
13326          return false;
13327        }
13328      } else {
13329        for (let i = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr) - 1; i >= 0; i--) {
13330          this.pdfiumModule.FPDFAnnot_RemoveObject(annotationPtr, i);
13331        }
13332        if (meta.mimeType === "image/png") {
13333          if (!this.addPngImageObject(
13334            doc,
13335            docPtr,
13336            page,
13337            pagePtr,
13338            annotationPtr,
13339            annotation.rect,
13340            context.data
13341          )) {
13342            return false;
13343          }
13344        } else if (meta.mimeType === "image/jpeg") {
13345          if (!this.addJpegImageObject(
13346            doc,
13347            docPtr,
13348            page,
13349            pagePtr,
13350            annotationPtr,
13351            annotation.rect,
13352            context.data
13353          )) {
13354            return false;
13355          }
13356        }
13357      }
13358    } else if (context && "imageData" in context && context.imageData) {
13359      for (let i = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr) - 1; i >= 0; i--) {
13360        this.pdfiumModule.FPDFAnnot_RemoveObject(annotationPtr, i);
13361      }
13362      if (!this.addImageObject(
13363        doc,
13364        docPtr,
13365        page,
13366        pagePtr,
13367        annotationPtr,
13368        annotation.rect,
13369        context.imageData
13370      )) {
13371        return false;
13372      }
13373    } else if (context && "appearance" in context && context.appearance) {
13374      if (!this.setAppearanceFromPdf(docPtr, annotationPtr, context.appearance)) {
13375        return false;
13376      }
13377    }
13378    if (!this.applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation)) {
13379      return false;
13380    }
13381    return !!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(annotationPtr, PdfStampFit.Cover);
13382  }
13383  /**
13384   * Set an annotation's appearance from a single-page PDF document.
13385   * Loads the PDF into WASM memory, calls the native SetAppearanceFromPage,
13386   * then cleans up.
13387   */
13388  setAppearanceFromPdf(docPtr, annotationPtr, appearance) {
13389    const data = new Uint8Array(appearance);
13390    const filePtr = this.memoryManager.malloc(data.byteLength);
13391    this.pdfiumModule.pdfium.HEAPU8.set(data, filePtr);
13392    const tempDocPtr = this.pdfiumModule.FPDF_LoadMemDocument(filePtr, data.byteLength, "");
13393    if (!tempDocPtr) {
13394      this.memoryManager.free(filePtr);
13395      return false;
13396    }
13397    const ok = this.pdfiumModule.EPDFAnnot_SetAppearanceFromPage(annotationPtr, tempDocPtr, 0);
13398    this.pdfiumModule.FPDF_CloseDocument(tempDocPtr);
13399    this.memoryManager.free(filePtr);
13400    return !!ok;
13401  }
13402  /**
13403   * Add image object to annotation
13404   * @param doc - pdf document object
13405   * @param docPtr - pointer to pdf document object
13406   * @param page - page info
13407   * @param pagePtr - pointer to page object
13408   * @param annotationPtr - pointer to stamp annotation
13409   * @param position - position of image
13410   * @param imageData - data of image
13411   * @returns whether image is added to annotation
13412   *
13413   * @private
13414   */
13415  addImageObject(doc, docPtr, page, pagePtr, annotationPtr, rect, imageData) {
13416    const bytesPerPixel = 4;
13417    const pixelCount = imageData.width * imageData.height;
13418    const bitmapBufferPtr = this.memoryManager.malloc(bytesPerPixel * pixelCount);
13419    if (!bitmapBufferPtr) {
13420      return false;
13421    }
13422    for (let i = 0; i < pixelCount; i++) {
13423      const red = imageData.data[i * bytesPerPixel];
13424      const green = imageData.data[i * bytesPerPixel + 1];
13425      const blue = imageData.data[i * bytesPerPixel + 2];
13426      const alpha = imageData.data[i * bytesPerPixel + 3];
13427      this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel, blue, "i8");
13428      this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 1, green, "i8");
13429      this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 2, red, "i8");
13430      this.pdfiumModule.pdfium.setValue(bitmapBufferPtr + i * bytesPerPixel + 3, alpha, "i8");
13431    }
13432    const format = 4;
13433    const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(
13434      imageData.width,
13435      imageData.height,
13436      format,
13437      bitmapBufferPtr,
13438      0
13439    );
13440    if (!bitmapPtr) {
13441      this.memoryManager.free(bitmapBufferPtr);
13442      return false;
13443    }
13444    const imageObjectPtr = this.pdfiumModule.FPDFPageObj_NewImageObj(docPtr);
13445    if (!imageObjectPtr) {
13446      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13447      this.memoryManager.free(bitmapBufferPtr);
13448      return false;
13449    }
13450    if (!this.pdfiumModule.FPDFImageObj_SetBitmap(pagePtr, 0, imageObjectPtr, bitmapPtr)) {
13451      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13452      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13453      this.memoryManager.free(bitmapBufferPtr);
13454      return false;
13455    }
13456    const matrixPtr = this.memoryManager.malloc(6 * 4);
13457    this.pdfiumModule.pdfium.setValue(matrixPtr, rect.size.width, "float");
13458    this.pdfiumModule.pdfium.setValue(matrixPtr + 4, 0, "float");
13459    this.pdfiumModule.pdfium.setValue(matrixPtr + 8, 0, "float");
13460    this.pdfiumModule.pdfium.setValue(matrixPtr + 12, rect.size.height, "float");
13461    this.pdfiumModule.pdfium.setValue(matrixPtr + 16, 0, "float");
13462    this.pdfiumModule.pdfium.setValue(matrixPtr + 20, 0, "float");
13463    if (!this.pdfiumModule.FPDFPageObj_SetMatrix(imageObjectPtr, matrixPtr)) {
13464      this.memoryManager.free(matrixPtr);
13465      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13466      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13467      this.memoryManager.free(bitmapBufferPtr);
13468      return false;
13469    }
13470    this.memoryManager.free(matrixPtr);
13471    const pagePos = this.convertDevicePointToPagePoint(doc, page, {
13472      x: rect.origin.x,
13473      y: rect.origin.y + rect.size.height
13474      // shift down by the authored display height
13475    });
13476    this.pdfiumModule.FPDFPageObj_Transform(imageObjectPtr, 1, 0, 0, 1, pagePos.x, pagePos.y);
13477    if (!this.pdfiumModule.FPDFAnnot_AppendObject(annotationPtr, imageObjectPtr)) {
13478      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13479      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13480      this.memoryManager.free(bitmapBufferPtr);
13481      return false;
13482    }
13483    this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
13484    this.memoryManager.free(bitmapBufferPtr);
13485    return true;
13486  }
13487  /**
13488   * Add PNG image object to annotation using native PNG import.
13489   * Passes raw PNG bytes to PDFium which decodes and stores them with
13490   * FlateDecode + PNG prediction filters for optimal compression.
13491   *
13492   * @private
13493   */
13494  addPngImageObject(doc, docPtr, page, pagePtr, annotationPtr, rect, pngData) {
13495    const imageObjectPtr = this.pdfiumModule.FPDFPageObj_NewImageObj(docPtr);
13496    if (!imageObjectPtr) {
13497      return false;
13498    }
13499    const pngBytes = new Uint8Array(pngData);
13500    const pngPtr = this.memoryManager.malloc(pngBytes.byteLength);
13501    if (!pngPtr) {
13502      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13503      return false;
13504    }
13505    this.pdfiumModule.pdfium.HEAPU8.set(pngBytes, pngPtr);
13506    if (!this.pdfiumModule.EPDFImageObj_SetPng(
13507      pagePtr,
13508      0,
13509      imageObjectPtr,
13510      pngPtr,
13511      pngBytes.byteLength
13512    )) {
13513      this.memoryManager.free(pngPtr);
13514      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13515      return false;
13516    }
13517    this.memoryManager.free(pngPtr);
13518    const matrixPtr = this.memoryManager.malloc(6 * 4);
13519    this.pdfiumModule.pdfium.setValue(matrixPtr, rect.size.width, "float");
13520    this.pdfiumModule.pdfium.setValue(matrixPtr + 4, 0, "float");
13521    this.pdfiumModule.pdfium.setValue(matrixPtr + 8, 0, "float");
13522    this.pdfiumModule.pdfium.setValue(matrixPtr + 12, rect.size.height, "float");
13523    this.pdfiumModule.pdfium.setValue(matrixPtr + 16, 0, "float");
13524    this.pdfiumModule.pdfium.setValue(matrixPtr + 20, 0, "float");
13525    if (!this.pdfiumModule.FPDFPageObj_SetMatrix(imageObjectPtr, matrixPtr)) {
13526      this.memoryManager.free(matrixPtr);
13527      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13528      return false;
13529    }
13530    this.memoryManager.free(matrixPtr);
13531    const pagePos = this.convertDevicePointToPagePoint(doc, page, {
13532      x: rect.origin.x,
13533      y: rect.origin.y + rect.size.height
13534    });
13535    this.pdfiumModule.FPDFPageObj_Transform(imageObjectPtr, 1, 0, 0, 1, pagePos.x, pagePos.y);
13536    if (!this.pdfiumModule.FPDFAnnot_AppendObject(annotationPtr, imageObjectPtr)) {
13537      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13538      return false;
13539    }
13540    return true;
13541  }
13542  /**
13543   * Add JPEG image object to annotation using native JPEG pass-through.
13544   * Passes raw JPEG bytes to PDFium which embeds them as a DCTDecode
13545   * stream — no decode/re-encode roundtrip.
13546   *
13547   * @private
13548   */
13549  addJpegImageObject(doc, docPtr, page, pagePtr, annotationPtr, rect, jpegData) {
13550    const imageObjectPtr = this.pdfiumModule.FPDFPageObj_NewImageObj(docPtr);
13551    if (!imageObjectPtr) {
13552      return false;
13553    }
13554    const jpegBytes = new Uint8Array(jpegData);
13555    const jpegPtr = this.memoryManager.malloc(jpegBytes.byteLength);
13556    if (!jpegPtr) {
13557      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13558      return false;
13559    }
13560    this.pdfiumModule.pdfium.HEAPU8.set(jpegBytes, jpegPtr);
13561    if (!this.pdfiumModule.EPDFImageObj_SetJpeg(
13562      pagePtr,
13563      0,
13564      imageObjectPtr,
13565      jpegPtr,
13566      jpegBytes.byteLength
13567    )) {
13568      this.memoryManager.free(jpegPtr);
13569      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13570      return false;
13571    }
13572    this.memoryManager.free(jpegPtr);
13573    const matrixPtr = this.memoryManager.malloc(6 * 4);
13574    this.pdfiumModule.pdfium.setValue(matrixPtr, rect.size.width, "float");
13575    this.pdfiumModule.pdfium.setValue(matrixPtr + 4, 0, "float");
13576    this.pdfiumModule.pdfium.setValue(matrixPtr + 8, 0, "float");
13577    this.pdfiumModule.pdfium.setValue(matrixPtr + 12, rect.size.height, "float");
13578    this.pdfiumModule.pdfium.setValue(matrixPtr + 16, 0, "float");
13579    this.pdfiumModule.pdfium.setValue(matrixPtr + 20, 0, "float");
13580    if (!this.pdfiumModule.FPDFPageObj_SetMatrix(imageObjectPtr, matrixPtr)) {
13581      this.memoryManager.free(matrixPtr);
13582      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13583      return false;
13584    }
13585    this.memoryManager.free(matrixPtr);
13586    const pagePos = this.convertDevicePointToPagePoint(doc, page, {
13587      x: rect.origin.x,
13588      y: rect.origin.y + rect.size.height
13589    });
13590    this.pdfiumModule.FPDFPageObj_Transform(imageObjectPtr, 1, 0, 0, 1, pagePos.x, pagePos.y);
13591    if (!this.pdfiumModule.FPDFAnnot_AppendObject(annotationPtr, imageObjectPtr)) {
13592      this.pdfiumModule.FPDFPageObj_Destroy(imageObjectPtr);
13593      return false;
13594    }
13595    return true;
13596  }
13597  /**
13598   * Save document to array buffer
13599   * @param docPtr - pointer to pdf document
13600   * @returns array buffer contains the pdf content
13601   *
13602   * @private
13603   */
13604  saveDocument(docPtr) {
13605    const writerPtr = this.pdfiumModule.PDFiumExt_OpenFileWriter();
13606    this.pdfiumModule.PDFiumExt_SaveAsCopy(docPtr, writerPtr);
13607    const size = this.pdfiumModule.PDFiumExt_GetFileWriterSize(writerPtr);
13608    const dataPtr = this.memoryManager.malloc(size);
13609    this.pdfiumModule.PDFiumExt_GetFileWriterData(writerPtr, dataPtr, size);
13610    const buffer = new ArrayBuffer(size);
13611    const view = new DataView(buffer);
13612    for (let i = 0; i < size; i++) {
13613      view.setInt8(i, this.pdfiumModule.pdfium.getValue(dataPtr + i, "i8"));
13614    }
13615    this.memoryManager.free(dataPtr);
13616    this.pdfiumModule.PDFiumExt_CloseFileWriter(writerPtr);
13617    return buffer;
13618  }
13619  /**
13620   * Read Catalog /Lang via EPDFCatalog_GetLanguage (UTF-16LE → JS string).
13621   * Returns:
13622   *   null  -> /Lang not present (getter returned 0) OR doc not open,
13623   *   ''    -> /Lang exists but is explicitly empty,
13624   *   'en', 'en-US', ... -> normal tag.
13625   *
13626   * Note: EPDFCatalog_GetLanguage lengths are BYTES (incl. trailing NUL).
13627   *
13628   * @private
13629   */
13630  readCatalogLanguage(docPtr) {
13631    const byteLen = this.pdfiumModule.EPDFCatalog_GetLanguage(docPtr, 0, 0) >>> 0;
13632    if (byteLen === 0) return null;
13633    if (byteLen === 2) return "";
13634    return readString(
13635      this.pdfiumModule.pdfium,
13636      (buffer, bufferLength) => this.pdfiumModule.EPDFCatalog_GetLanguage(docPtr, buffer, bufferLength),
13637      this.pdfiumModule.pdfium.UTF16ToString,
13638      byteLen
13639    );
13640  }
13641  /**
13642   * Read metadata from pdf document
13643   * @param docPtr - pointer to pdf document
13644   * @param key - key of metadata field
13645   * @returns metadata value
13646   *
13647   * @private
13648   */
13649  readMetaText(docPtr, key) {
13650    const exists = !!this.pdfiumModule.EPDF_HasMetaText(docPtr, key);
13651    if (!exists) return null;
13652    const len = this.pdfiumModule.FPDF_GetMetaText(docPtr, key, 0, 0);
13653    if (len === 2) return "";
13654    return readString(
13655      this.pdfiumModule.pdfium,
13656      (buffer, bufferLength) => this.pdfiumModule.FPDF_GetMetaText(docPtr, key, buffer, bufferLength),
13657      this.pdfiumModule.pdfium.UTF16ToString,
13658      len
13659    );
13660  }
13661  /**
13662   * Write metadata into the PDF's Info dictionary.
13663   * If \`value\` is null or empty string, the key is removed.
13664   * @param docPtr - pointer to pdf document
13665   * @param key - key of metadata field
13666   * @param value - value of metadata field
13667   * @returns whether metadata is written to the pdf document
13668   *
13669   * @private
13670   */
13671  setMetaText(docPtr, key, value) {
13672    if (value == null || value.length === 0) {
13673      const ok = this.pdfiumModule.EPDF_SetMetaText(docPtr, key, 0);
13674      return !!ok;
13675    }
13676    const bytes = 2 * (value.length + 1);
13677    const ptr = this.memoryManager.malloc(bytes);
13678    try {
13679      this.pdfiumModule.pdfium.stringToUTF16(value, ptr, bytes);
13680      const ok = this.pdfiumModule.EPDF_SetMetaText(docPtr, key, ptr);
13681      return !!ok;
13682    } finally {
13683      this.memoryManager.free(ptr);
13684    }
13685  }
13686  /**
13687   * Read the document's trapped status via PDFium.
13688   * Falls back to \`Unknown\` on unexpected values.
13689   *
13690   * @private
13691   */
13692  getMetaTrapped(docPtr) {
13693    const raw = Number(this.pdfiumModule.EPDF_GetMetaTrapped(docPtr));
13694    switch (raw) {
13695      case PdfTrappedStatus.NotSet:
13696      case PdfTrappedStatus.True:
13697      case PdfTrappedStatus.False:
13698      case PdfTrappedStatus.Unknown:
13699        return raw;
13700      default:
13701        return PdfTrappedStatus.Unknown;
13702    }
13703  }
13704  /**
13705   * Write (or clear) the document's trapped status via PDFium.
13706   * Pass \`null\`/\`undefined\` to remove the \`/Trapped\` key.
13707   *
13708   * @private
13709   */
13710  setMetaTrapped(docPtr, status) {
13711    const toSet = status == null || status === void 0 ? PdfTrappedStatus.NotSet : status;
13712    const valid = toSet === PdfTrappedStatus.NotSet || toSet === PdfTrappedStatus.True || toSet === PdfTrappedStatus.False || toSet === PdfTrappedStatus.Unknown;
13713    if (!valid) return false;
13714    return !!this.pdfiumModule.EPDF_SetMetaTrapped(docPtr, toSet);
13715  }
13716  /**
13717   * Get the number of keys in the document's Info dictionary.
13718   * @param docPtr - pointer to pdf document
13719   * @param customOnly - if true, only count non-reserved (custom) keys; if false, count all keys.
13720   * @returns the number of keys (possibly 0). On error, returns 0.
13721   *
13722   * @private
13723   */
13724  getMetaKeyCount(docPtr, customOnly) {
13725    return Number(this.pdfiumModule.EPDF_GetMetaKeyCount(docPtr, customOnly)) | 0;
13726  }
13727  /**
13728   * Get the name of the Info dictionary key at |index|.
13729   * @param docPtr - pointer to pdf document
13730   * @param index - 0-based key index in the order returned by PDFium.
13731   * @param customOnly - if true, indexes only over non-reserved (custom) keys; if false, indexes over all keys.
13732   * @returns the name of the key, or null if the key is not found.
13733   *
13734   * @private
13735   */
13736  getMetaKeyName(docPtr, index, customOnly) {
13737    const len = this.pdfiumModule.EPDF_GetMetaKeyName(docPtr, index, customOnly, 0, 0);
13738    if (!len) return null;
13739    return readString(
13740      this.pdfiumModule.pdfium,
13741      (buffer, buflen) => this.pdfiumModule.EPDF_GetMetaKeyName(docPtr, index, customOnly, buffer, buflen),
13742      this.pdfiumModule.pdfium.UTF8ToString,
13743      len
13744    );
13745  }
13746  /**
13747   * Read all metadata from the document's Info dictionary.
13748   * @param docPtr - pointer to pdf document
13749   * @param customOnly - if true, only read non-reserved (custom) keys; if false, read all keys.
13750   * @returns all metadata
13751   *
13752   * @private
13753   */
13754  readAllMeta(docPtr, customOnly = true) {
13755    const n = this.getMetaKeyCount(docPtr, customOnly);
13756    const out = {};
13757    for (let i = 0; i < n; i++) {
13758      const key = this.getMetaKeyName(docPtr, i, customOnly);
13759      if (!key) continue;
13760      out[key] = this.readMetaText(docPtr, key);
13761    }
13762    return out;
13763  }
13764  /**
13765   * Read bookmarks in the pdf document
13766   * @param docPtr - pointer to pdf document
13767   * @param rootBookmarkPtr - pointer to root bookmark
13768   * @returns bookmarks in the pdf document
13769   *
13770   * @private
13771   */
13772  readPdfBookmarks(docPtr, rootBookmarkPtr = 0) {
13773    let bookmarkPtr = this.pdfiumModule.FPDFBookmark_GetFirstChild(docPtr, rootBookmarkPtr);
13774    const bookmarks = [];
13775    while (bookmarkPtr) {
13776      const bookmark = this.readPdfBookmark(docPtr, bookmarkPtr);
13777      bookmarks.push(bookmark);
13778      const nextBookmarkPtr = this.pdfiumModule.FPDFBookmark_GetNextSibling(docPtr, bookmarkPtr);
13779      bookmarkPtr = nextBookmarkPtr;
13780    }
13781    return bookmarks;
13782  }
13783  /**
13784   * Read bookmark in the pdf document
13785   * @param docPtr - pointer to pdf document
13786   * @param bookmarkPtr - pointer to bookmark object
13787   * @returns pdf bookmark object
13788   *
13789   * @private
13790   */
13791  readPdfBookmark(docPtr, bookmarkPtr) {
13792    const title = readString(
13793      this.pdfiumModule.pdfium,
13794      (buffer, bufferLength) => {
13795        return this.pdfiumModule.FPDFBookmark_GetTitle(bookmarkPtr, buffer, bufferLength);
13796      },
13797      this.pdfiumModule.pdfium.UTF16ToString
13798    );
13799    const bookmarks = this.readPdfBookmarks(docPtr, bookmarkPtr);
13800    const target = this.readPdfBookmarkTarget(
13801      docPtr,
13802      () => {
13803        return this.pdfiumModule.FPDFBookmark_GetAction(bookmarkPtr);
13804      },
13805      () => {
13806        return this.pdfiumModule.FPDFBookmark_GetDest(docPtr, bookmarkPtr);
13807      }
13808    );
13809    return {
13810      title,
13811      target,
13812      children: bookmarks
13813    };
13814  }
13815  /**
13816   * Read text rects in pdf page
13817   * @param page - pdf page info
13818   * @param docPtr - pointer to pdf document
13819   * @param pagePtr - pointer to pdf page
13820   * @param textPagePtr - pointer to pdf text page
13821   * @returns text rects in the pdf page
13822   *
13823   * @public
13824   */
13825  readPageTextRects(page, docPtr, pagePtr, textPagePtr) {
13826    const rectsCount = this.pdfiumModule.FPDFText_CountRects(textPagePtr, 0, -1);
13827    const textRects = [];
13828    for (let i = 0; i < rectsCount; i++) {
13829      const topPtr = this.memoryManager.malloc(8);
13830      const leftPtr = this.memoryManager.malloc(8);
13831      const rightPtr = this.memoryManager.malloc(8);
13832      const bottomPtr = this.memoryManager.malloc(8);
13833      const isSucceed = this.pdfiumModule.FPDFText_GetRect(
13834        textPagePtr,
13835        i,
13836        leftPtr,
13837        topPtr,
13838        rightPtr,
13839        bottomPtr
13840      );
13841      if (!isSucceed) {
13842        this.memoryManager.free(leftPtr);
13843        this.memoryManager.free(topPtr);
13844        this.memoryManager.free(rightPtr);
13845        this.memoryManager.free(bottomPtr);
13846        continue;
13847      }
13848      const left = this.pdfiumModule.pdfium.getValue(leftPtr, "double");
13849      const top = this.pdfiumModule.pdfium.getValue(topPtr, "double");
13850      const right = this.pdfiumModule.pdfium.getValue(rightPtr, "double");
13851      const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "double");
13852      this.memoryManager.free(leftPtr);
13853      this.memoryManager.free(topPtr);
13854      this.memoryManager.free(rightPtr);
13855      this.memoryManager.free(bottomPtr);
13856      const deviceXPtr = this.memoryManager.malloc(4);
13857      const deviceYPtr = this.memoryManager.malloc(4);
13858      this.pdfiumModule.FPDF_PageToDevice(
13859        pagePtr,
13860        0,
13861        0,
13862        page.size.width,
13863        page.size.height,
13864        0,
13865        left,
13866        top,
13867        deviceXPtr,
13868        deviceYPtr
13869      );
13870      const x = this.pdfiumModule.pdfium.getValue(deviceXPtr, "i32");
13871      const y = this.pdfiumModule.pdfium.getValue(deviceYPtr, "i32");
13872      this.memoryManager.free(deviceXPtr);
13873      this.memoryManager.free(deviceYPtr);
13874      const rect = {
13875        origin: {
13876          x,
13877          y
13878        },
13879        size: {
13880          width: Math.ceil(Math.abs(right - left)),
13881          height: Math.ceil(Math.abs(top - bottom))
13882        }
13883      };
13884      const utf16Length = this.pdfiumModule.FPDFText_GetBoundedText(
13885        textPagePtr,
13886        left,
13887        top,
13888        right,
13889        bottom,
13890        0,
13891        0
13892      );
13893      const bytesCount = (utf16Length + 1) * 2;
13894      const textBuffer = this.memoryManager.malloc(bytesCount);
13895      this.pdfiumModule.FPDFText_GetBoundedText(
13896        textPagePtr,
13897        left,
13898        top,
13899        right,
13900        bottom,
13901        textBuffer,
13902        utf16Length
13903      );
13904      const content = this.pdfiumModule.pdfium.UTF16ToString(textBuffer);
13905      this.memoryManager.free(textBuffer);
13906      const charIndex = this.pdfiumModule.FPDFText_GetCharIndexAtPos(textPagePtr, left, top, 2, 2);
13907      let fontFamily = "";
13908      let fontSize = rect.size.height;
13909      if (charIndex >= 0) {
13910        fontSize = this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, charIndex);
13911        const fontNameLength = this.pdfiumModule.FPDFText_GetFontInfo(
13912          textPagePtr,
13913          charIndex,
13914          0,
13915          0,
13916          0
13917        );
13918        const bytesCount2 = fontNameLength + 1;
13919        const textBufferPtr = this.memoryManager.malloc(bytesCount2);
13920        const flagsPtr = this.memoryManager.malloc(4);
13921        this.pdfiumModule.FPDFText_GetFontInfo(
13922          textPagePtr,
13923          charIndex,
13924          textBufferPtr,
13925          bytesCount2,
13926          flagsPtr
13927        );
13928        fontFamily = this.pdfiumModule.pdfium.UTF8ToString(textBufferPtr);
13929        this.memoryManager.free(textBufferPtr);
13930        this.memoryManager.free(flagsPtr);
13931      }
13932      const textRect = {
13933        content,
13934        rect,
13935        font: {
13936          family: fontFamily,
13937          size: fontSize
13938        }
13939      };
13940      textRects.push(textRect);
13941    }
13942    return textRects;
13943  }
13944  /**
13945   * Return geometric + logical text layout for one page
13946   * (glyph-only implementation, no FPDFText_GetRect).
13947   *
13948   * @public
13949   */
13950  getPageGeometry(doc, page) {
13951    const label = "getPageGeometry";
13952    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", doc.id);
13953    const ctx = this.cache.getContext(doc.id);
13954    if (!ctx) {
13955      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);
13956      return PdfTaskHelper.reject({
13957        code: PdfErrorCode.DocNotOpen,
13958        message: "document does not open"
13959      });
13960    }
13961    const pageCtx = ctx.acquirePage(page.index);
13962    const textPagePtr = pageCtx.getTextPage();
13963    const glyphCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
13964    const glyphs = [];
13965    for (let i = 0; i < glyphCount; i++) {
13966      const g = this.readGlyphInfo(page, pageCtx.pagePtr, textPagePtr, i);
13967      glyphs.push(g);
13968    }
13969    const runs = this.buildRunsFromGlyphs(glyphs, textPagePtr);
13970    pageCtx.release();
13971    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);
13972    return PdfTaskHelper.resolve({ runs });
13973  }
13974  /**
13975   * Group consecutive glyphs that belong to the same CPDF_TextObject
13976   * using FPDFText_GetTextObject(), and calculate rotation from glyph positions.
13977   */
13978  buildRunsFromGlyphs(glyphs, textPagePtr) {
13979    const runs = [];
13980    let current = null;
13981    let curObjPtr = null;
13982    let bounds = null;
13983    for (let i = 0; i < glyphs.length; i++) {
13984      const g = glyphs[i];
13985      const objPtr = this.pdfiumModule.FPDFText_GetTextObject(textPagePtr, i);
13986      if (objPtr !== curObjPtr) {
13987        curObjPtr = objPtr;
13988        current = {
13989          rect: {
13990            x: g.origin.x,
13991            y: g.origin.y,
13992            width: g.size.width,
13993            height: g.size.height
13994          },
13995          charStart: i,
13996          glyphs: [],
13997          fontSize: this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, i)
13998        };
13999        bounds = {
14000          minX: g.origin.x,
14001          minY: g.origin.y,
14002          maxX: g.origin.x + g.size.width,
14003          maxY: g.origin.y + g.size.height
14004        };
14005        runs.push(current);
14006      }
14007      current.glyphs.push({
14008        x: g.origin.x,
14009        y: g.origin.y,
14010        width: g.size.width,
14011        height: g.size.height,
14012        flags: g.isEmpty ? 2 : g.isSpace ? 1 : 0,
14013        ...g.tightOrigin && { tightX: g.tightOrigin.x, tightY: g.tightOrigin.y },
14014        ...g.tightSize && { tightWidth: g.tightSize.width, tightHeight: g.tightSize.height }
14015      });
14016      if (g.isEmpty) {
14017        continue;
14018      }
14019      const right = g.origin.x + g.size.width;
14020      const bottom = g.origin.y + g.size.height;
14021      bounds.minX = Math.min(bounds.minX, g.origin.x);
14022      bounds.minY = Math.min(bounds.minY, g.origin.y);
14023      bounds.maxX = Math.max(bounds.maxX, right);
14024      bounds.maxY = Math.max(bounds.maxY, bottom);
14025      current.rect.x = bounds.minX;
14026      current.rect.y = bounds.minY;
14027      current.rect.width = bounds.maxX - bounds.minX;
14028      current.rect.height = bounds.maxY - bounds.minY;
14029    }
14030    return runs;
14031  }
14032  /**
14033   * Rich text runs: groups consecutive characters sharing the same
14034   * text object, font, size, and fill color into structured segments
14035   * with full font metadata and bounding boxes in PDF page coordinates.
14036   *
14037   * @public
14038   */
14039  getPageTextRuns(doc, page) {
14040    const label = "getPageTextRuns";
14041    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", doc.id);
14042    const ctx = this.cache.getContext(doc.id);
14043    if (!ctx) {
14044      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);
14045      return PdfTaskHelper.reject({
14046        code: PdfErrorCode.DocNotOpen,
14047        message: "document does not open"
14048      });
14049    }
14050    const pageCtx = ctx.acquirePage(page.index);
14051    const textPagePtr = pageCtx.getTextPage();
14052    const charCount = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
14053    const runs = [];
14054    let runStart = 0;
14055    let curObjPtr = null;
14056    let curFont = null;
14057    let curFontSize = 0;
14058    let curColor = null;
14059    let bounds = null;
14060    const flushRun = (end) => {
14061      if (curObjPtr === null || curFont === null || curColor === null || bounds === null) return;
14062      const count = end - runStart;
14063      if (count <= 0) return;
14064      const bufPtr = this.memoryManager.malloc(2 * (count + 1));
14065      this.pdfiumModule.FPDFText_GetText(textPagePtr, runStart, count, bufPtr);
14066      const text = stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(bufPtr));
14067      this.memoryManager.free(bufPtr);
14068      runs.push({
14069        text,
14070        rect: {
14071          origin: { x: bounds.minX, y: bounds.minY },
14072          size: {
14073            width: Math.max(1, bounds.maxX - bounds.minX),
14074            height: Math.max(1, bounds.maxY - bounds.minY)
14075          }
14076        },
14077        font: curFont,
14078        fontSize: curFontSize,
14079        color: curColor,
14080        charIndex: runStart,
14081        charCount: count
14082      });
14083    };
14084    const rPtr = this.memoryManager.malloc(4);
14085    const gPtr = this.memoryManager.malloc(4);
14086    const bPtr = this.memoryManager.malloc(4);
14087    const aPtr = this.memoryManager.malloc(4);
14088    const rectPtr = this.memoryManager.malloc(16);
14089    const dx1Ptr = this.memoryManager.malloc(4);
14090    const dy1Ptr = this.memoryManager.malloc(4);
14091    const dx2Ptr = this.memoryManager.malloc(4);
14092    const dy2Ptr = this.memoryManager.malloc(4);
14093    const italicAnglePtr = this.memoryManager.malloc(4);
14094    for (let i = 0; i < charCount; i++) {
14095      const uc = this.pdfiumModule.FPDFText_GetUnicode(textPagePtr, i);
14096      if (uc === 65534 || uc === 65533) continue;
14097      const objPtr = this.pdfiumModule.FPDFText_GetTextObject(textPagePtr, i);
14098      if (objPtr === 0) continue;
14099      const fontSize = this.pdfiumModule.FPDFText_GetFontSize(textPagePtr, i);
14100      this.pdfiumModule.FPDFText_GetFillColor(textPagePtr, i, rPtr, gPtr, bPtr, aPtr);
14101      const red = this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255;
14102      const green = this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255;
14103      const blue = this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255;
14104      const alpha = this.pdfiumModule.pdfium.getValue(aPtr, "i32") & 255;
14105      const fontInfo = this.readFontInfoFromTextObject(objPtr, italicAnglePtr);
14106      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;
14107      if (needNewRun) {
14108        flushRun(i);
14109        curObjPtr = objPtr;
14110        curFont = fontInfo;
14111        curFontSize = fontSize;
14112        curColor = { red, green, blue, alpha };
14113        runStart = i;
14114        bounds = null;
14115      }
14116      if (this.pdfiumModule.FPDFText_GetLooseCharBox(textPagePtr, i, rectPtr)) {
14117        const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");
14118        const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");
14119        const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");
14120        const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");
14121        if (left !== right && top !== bottom) {
14122          this.pdfiumModule.FPDF_PageToDevice(
14123            pageCtx.pagePtr,
14124            0,
14125            0,
14126            page.size.width,
14127            page.size.height,
14128            0,
14129            left,
14130            top,
14131            dx1Ptr,
14132            dy1Ptr
14133          );
14134          this.pdfiumModule.FPDF_PageToDevice(
14135            pageCtx.pagePtr,
14136            0,
14137            0,
14138            page.size.width,
14139            page.size.height,
14140            0,
14141            right,
14142            bottom,
14143            dx2Ptr,
14144            dy2Ptr
14145          );
14146          const x1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");
14147          const y1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");
14148          const x2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");
14149          const y2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");
14150          const cx = Math.min(x1, x2);
14151          const cy = Math.min(y1, y2);
14152          const cw = Math.abs(x2 - x1);
14153          const ch = Math.abs(y2 - y1);
14154          if (bounds === null) {
14155            bounds = { minX: cx, minY: cy, maxX: cx + cw, maxY: cy + ch };
14156          } else {
14157            bounds.minX = Math.min(bounds.minX, cx);
14158            bounds.minY = Math.min(bounds.minY, cy);
14159            bounds.maxX = Math.max(bounds.maxX, cx + cw);
14160            bounds.maxY = Math.max(bounds.maxY, cy + ch);
14161          }
14162        }
14163      }
14164    }
14165    flushRun(charCount);
14166    [rPtr, gPtr, bPtr, aPtr, rectPtr, dx1Ptr, dy1Ptr, dx2Ptr, dy2Ptr, italicAnglePtr].forEach(
14167      (p) => this.memoryManager.free(p)
14168    );
14169    pageCtx.release();
14170    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", doc.id);
14171    return PdfTaskHelper.resolve({ runs });
14172  }
14173  /**
14174   * Read font metadata from a text object handle via FPDFFont_* APIs.
14175   */
14176  readFontInfoFromTextObject(textObjPtr, italicAnglePtr) {
14177    const fontPtr = this.pdfiumModule.FPDFTextObj_GetFont(textObjPtr);
14178    let name = "";
14179    let familyName = "";
14180    let weight = 400;
14181    let italic = false;
14182    let monospaced = false;
14183    let embedded = false;
14184    if (fontPtr) {
14185      const nameLen = this.pdfiumModule.FPDFFont_GetBaseFontName(fontPtr, 0, 0);
14186      if (nameLen > 0) {
14187        const nameBuf = this.memoryManager.malloc(nameLen + 1);
14188        this.pdfiumModule.FPDFFont_GetBaseFontName(fontPtr, nameBuf, nameLen + 1);
14189        name = this.pdfiumModule.pdfium.UTF8ToString(nameBuf);
14190        this.memoryManager.free(nameBuf);
14191      }
14192      const famLen = this.pdfiumModule.FPDFFont_GetFamilyName(fontPtr, 0, 0);
14193      if (famLen > 0) {
14194        const famBuf = this.memoryManager.malloc(famLen + 1);
14195        this.pdfiumModule.FPDFFont_GetFamilyName(fontPtr, famBuf, famLen + 1);
14196        familyName = this.pdfiumModule.pdfium.UTF8ToString(famBuf);
14197        this.memoryManager.free(famBuf);
14198      }
14199      weight = this.pdfiumModule.FPDFFont_GetWeight(fontPtr);
14200      embedded = this.pdfiumModule.FPDFFont_GetIsEmbedded(fontPtr) !== 0;
14201      if (this.pdfiumModule.FPDFFont_GetItalicAngle(fontPtr, italicAnglePtr)) {
14202        const angle = this.pdfiumModule.pdfium.getValue(italicAnglePtr, "i32");
14203        italic = angle !== 0;
14204      }
14205      const flags = this.pdfiumModule.FPDFFont_GetFlags(fontPtr);
14206      monospaced = (flags & 1) !== 0;
14207    }
14208    return { name, familyName, weight, italic, monospaced, embedded };
14209  }
14210  /**
14211   * Extract glyph geometry + metadata for \`charIndex\`
14212   *
14213   * Returns device–space coordinates:
14214   *   x,y  → **top-left** corner (integer-pixels)
14215   *   w,h  → width / height (integer-pixels, ≥ 1)
14216   *
14217   * And two flags:
14218   *   isSpace → true if the glyph's Unicode code-point is U+0020
14219   */
14220  readGlyphInfo(page, pagePtr, textPagePtr, charIndex) {
14221    const dx1Ptr = this.memoryManager.malloc(4);
14222    const dy1Ptr = this.memoryManager.malloc(4);
14223    const dx2Ptr = this.memoryManager.malloc(4);
14224    const dy2Ptr = this.memoryManager.malloc(4);
14225    const rectPtr = this.memoryManager.malloc(16);
14226    const tLeftPtr = this.memoryManager.malloc(8);
14227    const tRightPtr = this.memoryManager.malloc(8);
14228    const tBottomPtr = this.memoryManager.malloc(8);
14229    const tTopPtr = this.memoryManager.malloc(8);
14230    const allPtrs = [
14231      rectPtr,
14232      dx1Ptr,
14233      dy1Ptr,
14234      dx2Ptr,
14235      dy2Ptr,
14236      tLeftPtr,
14237      tRightPtr,
14238      tBottomPtr,
14239      tTopPtr
14240    ];
14241    let x = 0, y = 0, width = 0, height = 0, isSpace = false;
14242    let tightOrigin;
14243    let tightSize;
14244    if (this.pdfiumModule.FPDFText_GetLooseCharBox(textPagePtr, charIndex, rectPtr)) {
14245      const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");
14246      const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");
14247      const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");
14248      const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");
14249      if (left === right || top === bottom) {
14250        allPtrs.forEach((p) => this.memoryManager.free(p));
14251        return {
14252          origin: { x: 0, y: 0 },
14253          size: { width: 0, height: 0 },
14254          isEmpty: true
14255        };
14256      }
14257      this.pdfiumModule.FPDF_PageToDevice(
14258        pagePtr,
14259        0,
14260        0,
14261        page.size.width,
14262        page.size.height,
14263        0,
14264        left,
14265        top,
14266        dx1Ptr,
14267        dy1Ptr
14268      );
14269      this.pdfiumModule.FPDF_PageToDevice(
14270        pagePtr,
14271        0,
14272        0,
14273        page.size.width,
14274        page.size.height,
14275        0,
14276        right,
14277        bottom,
14278        dx2Ptr,
14279        dy2Ptr
14280      );
14281      const x1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");
14282      const y1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");
14283      const x2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");
14284      const y2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");
14285      x = Math.min(x1, x2);
14286      y = Math.min(y1, y2);
14287      width = Math.max(1, Math.abs(x2 - x1));
14288      height = Math.max(1, Math.abs(y2 - y1));
14289      if (this.pdfiumModule.FPDFText_GetCharBox(
14290        textPagePtr,
14291        charIndex,
14292        tLeftPtr,
14293        tRightPtr,
14294        tBottomPtr,
14295        tTopPtr
14296      )) {
14297        const tLeft = this.pdfiumModule.pdfium.getValue(tLeftPtr, "double");
14298        const tRight = this.pdfiumModule.pdfium.getValue(tRightPtr, "double");
14299        const tBottom = this.pdfiumModule.pdfium.getValue(tBottomPtr, "double");
14300        const tTop = this.pdfiumModule.pdfium.getValue(tTopPtr, "double");
14301        this.pdfiumModule.FPDF_PageToDevice(
14302          pagePtr,
14303          0,
14304          0,
14305          page.size.width,
14306          page.size.height,
14307          0,
14308          tLeft,
14309          tTop,
14310          dx1Ptr,
14311          dy1Ptr
14312        );
14313        this.pdfiumModule.FPDF_PageToDevice(
14314          pagePtr,
14315          0,
14316          0,
14317          page.size.width,
14318          page.size.height,
14319          0,
14320          tRight,
14321          tBottom,
14322          dx2Ptr,
14323          dy2Ptr
14324        );
14325        const tx1 = this.pdfiumModule.pdfium.getValue(dx1Ptr, "i32");
14326        const ty1 = this.pdfiumModule.pdfium.getValue(dy1Ptr, "i32");
14327        const tx2 = this.pdfiumModule.pdfium.getValue(dx2Ptr, "i32");
14328        const ty2 = this.pdfiumModule.pdfium.getValue(dy2Ptr, "i32");
14329        tightOrigin = { x: Math.min(tx1, tx2), y: Math.min(ty1, ty2) };
14330        tightSize = {
14331          width: Math.max(1, Math.abs(tx2 - tx1)),
14332          height: Math.max(1, Math.abs(ty2 - ty1))
14333        };
14334      }
14335      const uc = this.pdfiumModule.FPDFText_GetUnicode(textPagePtr, charIndex);
14336      isSpace = uc === 32;
14337    }
14338    allPtrs.forEach((p) => this.memoryManager.free(p));
14339    return {
14340      origin: { x, y },
14341      size: { width, height },
14342      ...tightOrigin && { tightOrigin },
14343      ...tightSize && { tightSize },
14344      ...isSpace && { isSpace }
14345    };
14346  }
14347  /**
14348   * Geometry-only text extraction
14349   * ------------------------------------------
14350   * Returns every glyph on the requested page
14351   * in the logical order delivered by PDFium.
14352   *
14353   * The promise resolves to an array of objects:
14354   *   {
14355   *     idx:     number;            // glyph index on the page (0…n-1)
14356   *     origin:  { x: number; y: number };
14357   *     size:    { width: number;  height: number };
14358   *     angle:   number;            // degrees, counter-clock-wise
14359   *     isSpace: boolean;           // true  → U+0020
14360   *   }
14361   *
14362   * No Unicode is included; front-end decides whether to hydrate it.
14363   */
14364  getPageGlyphs(doc, page) {
14365    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", doc, page);
14366    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "Begin", doc.id);
14367    const ctx = this.cache.getContext(doc.id);
14368    if (!ctx) {
14369      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "End", doc.id);
14370      return PdfTaskHelper.reject({
14371        code: PdfErrorCode.DocNotOpen,
14372        message: "document does not open"
14373      });
14374    }
14375    const pageCtx = ctx.acquirePage(page.index);
14376    const textPagePtr = pageCtx.getTextPage();
14377    const total = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
14378    const glyphs = new Array(total);
14379    for (let i = 0; i < total; i++) {
14380      const g = this.readGlyphInfo(page, pageCtx.pagePtr, textPagePtr, i);
14381      if (g.isEmpty) {
14382        continue;
14383      }
14384      glyphs[i] = { ...g };
14385    }
14386    pageCtx.release();
14387    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageGlyphs", "End", doc.id);
14388    return PdfTaskHelper.resolve(glyphs);
14389  }
14390  readCharBox(page, pagePtr, textPagePtr, charIndex) {
14391    const topPtr = this.memoryManager.malloc(8);
14392    const leftPtr = this.memoryManager.malloc(8);
14393    const bottomPtr = this.memoryManager.malloc(8);
14394    const rightPtr = this.memoryManager.malloc(8);
14395    let x = 0;
14396    let y = 0;
14397    let width = 0;
14398    let height = 0;
14399    if (this.pdfiumModule.FPDFText_GetCharBox(
14400      textPagePtr,
14401      charIndex,
14402      leftPtr,
14403      rightPtr,
14404      bottomPtr,
14405      topPtr
14406    )) {
14407      const top = this.pdfiumModule.pdfium.getValue(topPtr, "double");
14408      const left = this.pdfiumModule.pdfium.getValue(leftPtr, "double");
14409      const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "double");
14410      const right = this.pdfiumModule.pdfium.getValue(rightPtr, "double");
14411      const deviceXPtr = this.memoryManager.malloc(4);
14412      const deviceYPtr = this.memoryManager.malloc(4);
14413      this.pdfiumModule.FPDF_PageToDevice(
14414        pagePtr,
14415        0,
14416        0,
14417        page.size.width,
14418        page.size.height,
14419        0,
14420        left,
14421        top,
14422        deviceXPtr,
14423        deviceYPtr
14424      );
14425      x = this.pdfiumModule.pdfium.getValue(deviceXPtr, "i32");
14426      y = this.pdfiumModule.pdfium.getValue(deviceYPtr, "i32");
14427      this.memoryManager.free(deviceXPtr);
14428      this.memoryManager.free(deviceYPtr);
14429      width = Math.ceil(Math.abs(right - left));
14430      height = Math.ceil(Math.abs(top - bottom));
14431    }
14432    this.memoryManager.free(topPtr);
14433    this.memoryManager.free(leftPtr);
14434    this.memoryManager.free(bottomPtr);
14435    this.memoryManager.free(rightPtr);
14436    return {
14437      origin: {
14438        x,
14439        y
14440      },
14441      size: {
14442        width,
14443        height
14444      }
14445    };
14446  }
14447  /**
14448   * Read page annotations
14449   *
14450   * @param doc - pdf document object
14451   * @param ctx - document context
14452   * @param page - page info
14453   * @returns annotations on the pdf page
14454   *
14455   * @private
14456   */
14457  readPageAnnotations(doc, ctx, page) {
14458    return ctx.borrowPage(page.index, (pageCtx) => {
14459      return pageCtx.withFormHandle((formHandle) => {
14460        const annotationCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
14461        const annotations = [];
14462        for (let i = 0; i < annotationCount; i++) {
14463          pageCtx.withAnnotation(i, (annotPtr) => {
14464            const anno = this.readPageAnnotation(doc, ctx.docPtr, page, annotPtr, formHandle);
14465            if (anno) annotations.push(anno);
14466          });
14467        }
14468        return annotations;
14469      });
14470    });
14471  }
14472  /**
14473   *
14474   *
14475   * @param ctx - document context
14476   * @param page - page info
14477   * @returns form fields on the pdf page
14478   *
14479   * @private
14480   */
14481  readPageAnnoWidgets(doc, ctx, page) {
14482    return ctx.borrowPage(page.index, (pageCtx) => {
14483      return pageCtx.withFormHandle((formHandle) => {
14484        const annotationCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
14485        const annotations = [];
14486        for (let i = 0; i < annotationCount; i++) {
14487          pageCtx.withAnnotation(i, (annotPtr) => {
14488            const anno = this.readPageAnnoWidget(doc, page, annotPtr, formHandle);
14489            if (anno) annotations.push(anno);
14490          });
14491        }
14492        return annotations;
14493      });
14494    });
14495  }
14496  /**
14497   * Read page annotations
14498   * Read page annotations without loading the page (raw approach)
14499   *
14500   * @param doc - pdf document object
14501   * @param ctx - document context
14502   * @param page - page info
14503   * @returns annotations on the pdf page
14504   *
14505   * @private
14506   */
14507  readPageAnnotationsRaw(doc, ctx, page, formHandle) {
14508    const count = this.pdfiumModule.EPDFPage_GetAnnotCountRaw(ctx.docPtr, page.index);
14509    if (count <= 0) return [];
14510    const out = [];
14511    for (let i = 0; i < count; ++i) {
14512      const annotPtr = this.pdfiumModule.EPDFPage_GetAnnotRaw(ctx.docPtr, page.index, i);
14513      if (!annotPtr) continue;
14514      try {
14515        const anno = this.readPageAnnotation(doc, ctx.docPtr, page, annotPtr, formHandle);
14516        if (anno) out.push(anno);
14517      } finally {
14518        this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
14519      }
14520    }
14521    return out;
14522  }
14523  /**
14524   * Read page form field
14525   *
14526   * @param ctx - document context
14527   * @param page - page info
14528   * @param annotationPtr - pointer to pdf annotation
14529   * @param pageCtx - page context
14530   * @returns form field
14531   *
14532   * @private
14533   */
14534  readPageAnnoWidget(doc, page, annotationPtr, formHandle) {
14535    let index = this.getAnnotString(annotationPtr, "NM");
14536    if (!index || !isUuidV4(index)) {
14537      index = uuidV4();
14538      this.setAnnotString(annotationPtr, "NM", index);
14539    }
14540    const subType = this.pdfiumModule.FPDFAnnot_GetSubtype(
14541      annotationPtr
14542    );
14543    if (subType !== PdfAnnotationSubtype.WIDGET) return;
14544    return this.readPdfWidgetAnno(doc, page, annotationPtr, formHandle, index);
14545  }
14546  /*
14547   * Get page annotations (public API, returns Task)
14548   *
14549   * @param doc - pdf document
14550   * @param page - page info
14551   * @returns task with annotations on the pdf page
14552   *
14553   * @public
14554   */
14555  getPageAnnotationsRaw(doc, page) {
14556    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getPageAnnotationsRaw", doc, page);
14557    this.logger.perf(
14558      LOG_SOURCE$1,
14559      LOG_CATEGORY$1,
14560      \`GetPageAnnotationsRaw\`,
14561      "Begin",
14562      \`\${doc.id}-\${page.index}\`
14563    );
14564    const ctx = this.cache.getContext(doc.id);
14565    if (!ctx) {
14566      return PdfTaskHelper.reject({
14567        code: PdfErrorCode.DocNotOpen,
14568        message: "document does not open"
14569      });
14570    }
14571    const formInfoPtr = this.pdfiumModule.PDFiumExt_OpenFormFillInfo();
14572    const formHandle = this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(ctx.docPtr, formInfoPtr);
14573    try {
14574      const out = this.readPageAnnotationsRaw(doc, ctx, page, formHandle);
14575      this.logger.perf(
14576        LOG_SOURCE$1,
14577        LOG_CATEGORY$1,
14578        \`GetPageAnnotationsRaw\`,
14579        "End",
14580        \`\${doc.id}-\${page.index}\`
14581      );
14582      this.logger.debug(
14583        LOG_SOURCE$1,
14584        LOG_CATEGORY$1,
14585        "getPageAnnotationsRaw",
14586        \`\${doc.id}-\${page.index}\`,
14587        out
14588      );
14589      return PdfTaskHelper.resolve(out);
14590    } finally {
14591      this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);
14592      this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formInfoPtr);
14593    }
14594  }
14595  /**
14596   * Read pdf annotation from pdf document
14597   *
14598   * @param doc - pdf document object
14599   * @param docPtr - pointer to pdf document
14600   * @param page - page info
14601   * @param annotationPtr - pointer to pdf annotation
14602   * @param formHandle - optional form fill handle for widget annotations
14603   * @returns pdf annotation
14604   *
14605   * @private
14606   */
14607  readPageAnnotation(doc, docPtr, page, annotationPtr, formHandle) {
14608    let index = this.getAnnotString(annotationPtr, "NM");
14609    if (!index || !isUuidV4(index)) {
14610      index = uuidV4();
14611      this.setAnnotString(annotationPtr, "NM", index);
14612    }
14613    const subType = this.pdfiumModule.FPDFAnnot_GetSubtype(
14614      annotationPtr
14615    );
14616    let annotation;
14617    switch (subType) {
14618      case PdfAnnotationSubtype.TEXT:
14619        {
14620          annotation = this.readPdfTextAnno(doc, page, annotationPtr, index);
14621        }
14622        break;
14623      case PdfAnnotationSubtype.FREETEXT:
14624        {
14625          annotation = this.readPdfFreeTextAnno(doc, page, annotationPtr, index);
14626        }
14627        break;
14628      case PdfAnnotationSubtype.LINK:
14629        {
14630          annotation = this.readPdfLinkAnno(doc, page, docPtr, annotationPtr, index);
14631        }
14632        break;
14633      case PdfAnnotationSubtype.WIDGET:
14634        {
14635          if (formHandle !== void 0) {
14636            return this.readPdfWidgetAnno(doc, page, annotationPtr, formHandle, index);
14637          }
14638        }
14639        break;
14640      case PdfAnnotationSubtype.FILEATTACHMENT:
14641        {
14642          annotation = this.readPdfFileAttachmentAnno(doc, page, annotationPtr, index);
14643        }
14644        break;
14645      case PdfAnnotationSubtype.INK:
14646        {
14647          annotation = this.readPdfInkAnno(doc, page, annotationPtr, index);
14648        }
14649        break;
14650      case PdfAnnotationSubtype.POLYGON:
14651        {
14652          annotation = this.readPdfPolygonAnno(doc, page, annotationPtr, index);
14653        }
14654        break;
14655      case PdfAnnotationSubtype.POLYLINE:
14656        {
14657          annotation = this.readPdfPolylineAnno(doc, page, annotationPtr, index);
14658        }
14659        break;
14660      case PdfAnnotationSubtype.LINE:
14661        {
14662          annotation = this.readPdfLineAnno(doc, page, annotationPtr, index);
14663        }
14664        break;
14665      case PdfAnnotationSubtype.HIGHLIGHT:
14666        annotation = this.readPdfHighlightAnno(doc, page, annotationPtr, index);
14667        break;
14668      case PdfAnnotationSubtype.STAMP:
14669        {
14670          annotation = this.readPdfStampAnno(doc, page, annotationPtr, index);
14671        }
14672        break;
14673      case PdfAnnotationSubtype.SQUARE:
14674        {
14675          annotation = this.readPdfSquareAnno(doc, page, annotationPtr, index);
14676        }
14677        break;
14678      case PdfAnnotationSubtype.CIRCLE:
14679        {
14680          annotation = this.readPdfCircleAnno(doc, page, annotationPtr, index);
14681        }
14682        break;
14683      case PdfAnnotationSubtype.UNDERLINE:
14684        {
14685          annotation = this.readPdfUnderlineAnno(doc, page, annotationPtr, index);
14686        }
14687        break;
14688      case PdfAnnotationSubtype.SQUIGGLY:
14689        {
14690          annotation = this.readPdfSquigglyAnno(doc, page, annotationPtr, index);
14691        }
14692        break;
14693      case PdfAnnotationSubtype.STRIKEOUT:
14694        {
14695          annotation = this.readPdfStrikeOutAnno(doc, page, annotationPtr, index);
14696        }
14697        break;
14698      case PdfAnnotationSubtype.CARET:
14699        {
14700          annotation = this.readPdfCaretAnno(doc, page, annotationPtr, index);
14701        }
14702        break;
14703      case PdfAnnotationSubtype.REDACT:
14704        {
14705          annotation = this.readPdfRedactAnno(doc, page, annotationPtr, index);
14706        }
14707        break;
14708      default:
14709        {
14710          annotation = this.readPdfAnno(doc, page, subType, annotationPtr, index);
14711        }
14712        break;
14713    }
14714    if (annotation) {
14715      annotation = this.reverseRotateAnnotationOnLoad(annotation);
14716      const apModes = this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(annotationPtr);
14717      if (apModes) {
14718        annotation.appearanceModes = apModes;
14719      }
14720    }
14721    return annotation;
14722  }
14723  /**
14724   * On load, if a vertex-type annotation has rotation metadata in EPDFCustom,
14725   * reverse-rotate the PDF's physically rotated vertices by -rotation to recover
14726   * the unrotated vertices for runtime editing.
14727   */
14728  reverseRotateAnnotationOnLoad(annotation) {
14729    const rotation = annotation.rotation;
14730    const unrotatedRect = annotation.unrotatedRect;
14731    if (!rotation || rotation === 0 || !unrotatedRect) {
14732      return annotation;
14733    }
14734    const center = {
14735      x: unrotatedRect.origin.x + unrotatedRect.size.width / 2,
14736      y: unrotatedRect.origin.y + unrotatedRect.size.height / 2
14737    };
14738    switch (annotation.type) {
14739      case PdfAnnotationSubtype.INK: {
14740        const ink = annotation;
14741        const unrotatedInkList = ink.inkList.map((stroke) => ({
14742          points: stroke.points.map((p) => this.rotatePointForSave(p, center, -rotation))
14743        }));
14744        return { ...ink, inkList: unrotatedInkList };
14745      }
14746      case PdfAnnotationSubtype.LINE: {
14747        const line = annotation;
14748        return {
14749          ...line,
14750          linePoints: {
14751            start: this.rotatePointForSave(line.linePoints.start, center, -rotation),
14752            end: this.rotatePointForSave(line.linePoints.end, center, -rotation)
14753          }
14754        };
14755      }
14756      case PdfAnnotationSubtype.POLYGON: {
14757        const poly = annotation;
14758        return {
14759          ...poly,
14760          vertices: poly.vertices.map((v) => this.rotatePointForSave(v, center, -rotation))
14761        };
14762      }
14763      case PdfAnnotationSubtype.POLYLINE: {
14764        const polyline = annotation;
14765        return {
14766          ...polyline,
14767          vertices: polyline.vertices.map((v) => this.rotatePointForSave(v, center, -rotation))
14768        };
14769      }
14770      default:
14771        return annotation;
14772    }
14773  }
14774  /**
14775   * Return the colour stored directly in the annotation dictionary's \`/C\` entry.
14776   *
14777   * Most PDFs created by Acrobat, Microsoft Office, LaTeX, etc. include this entry.
14778   * When the key is absent (common in macOS Preview, Chrome, Drawboard) the call
14779   * fails and the function returns \`undefined\`.
14780   *
14781   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
14782   * @returns An RGBA tuple (0-255 channels) or \`undefined\` if no \`/C\` entry exists
14783   *
14784   * @private
14785   */
14786  readAnnotationColor(annotationPtr, colorType = PdfAnnotationColorType.Color) {
14787    const rPtr = this.memoryManager.malloc(4);
14788    const gPtr = this.memoryManager.malloc(4);
14789    const bPtr = this.memoryManager.malloc(4);
14790    const ok = this.pdfiumModule.EPDFAnnot_GetColor(annotationPtr, colorType, rPtr, gPtr, bPtr);
14791    let colour;
14792    if (ok) {
14793      colour = {
14794        red: this.pdfiumModule.pdfium.getValue(rPtr, "i32") & 255,
14795        green: this.pdfiumModule.pdfium.getValue(gPtr, "i32") & 255,
14796        blue: this.pdfiumModule.pdfium.getValue(bPtr, "i32") & 255
14797      };
14798    }
14799    this.memoryManager.free(rPtr);
14800    this.memoryManager.free(gPtr);
14801    this.memoryManager.free(bPtr);
14802    return colour;
14803  }
14804  /**
14805   * Get the fill/stroke colour annotation.
14806   *
14807   * @param annotationPtr - pointer to the annotation whose colour is being set
14808   * @param colorType - which colour to get (0 = fill, 1 = stroke)
14809   * @returns WebColor with hex color
14810   *
14811   * @private
14812   */
14813  getAnnotationColor(annotationPtr, colorType = PdfAnnotationColorType.Color) {
14814    const annotationColor = this.readAnnotationColor(annotationPtr, colorType);
14815    return annotationColor ? pdfColorToWebColor(annotationColor) : void 0;
14816  }
14817  /**
14818   * Set the fill/stroke colour for a **Highlight / Underline / StrikeOut / Squiggly** markup annotation.
14819   *
14820   * @param annotationPtr - pointer to the annotation whose colour is being set
14821   * @param webAlphaColor - WebAlphaColor with hex color and opacity (0-1)
14822   * @param shouldClearAP - whether to clear the /AP entry
14823   * @param which - which colour to set (0 = fill, 1 = stroke)
14824   * @returns \`true\` if the operation was successful
14825   *
14826   * @private
14827   */
14828  setAnnotationColor(annotationPtr, webColor, colorType = PdfAnnotationColorType.Color) {
14829    const pdfColor = webColorToPdfColor(webColor);
14830    return this.pdfiumModule.EPDFAnnot_SetColor(
14831      annotationPtr,
14832      colorType,
14833      pdfColor.red & 255,
14834      pdfColor.green & 255,
14835      pdfColor.blue & 255
14836    );
14837  }
14838  /**
14839   * Get the opacity of the annotation.
14840   *
14841   * @param annotationPtr - pointer to the annotation whose opacity is being set
14842   * @returns opacity (0-1)
14843   *
14844   * @private
14845   */
14846  getAnnotationOpacity(annotationPtr) {
14847    const opacityPtr = this.memoryManager.malloc(4);
14848    const ok = this.pdfiumModule.EPDFAnnot_GetOpacity(annotationPtr, opacityPtr);
14849    const opacity = ok ? this.pdfiumModule.pdfium.getValue(opacityPtr, "i32") : 255;
14850    this.memoryManager.free(opacityPtr);
14851    return pdfAlphaToWebOpacity(opacity);
14852  }
14853  /**
14854   * Set the opacity of the annotation.
14855   *
14856   * @param annotationPtr - pointer to the annotation whose opacity is being set
14857   * @param opacity - opacity (0-1)
14858   * @returns true on success
14859   *
14860   * @private
14861   */
14862  setAnnotationOpacity(annotationPtr, opacity) {
14863    const pdfOpacity = webOpacityToPdfAlpha(opacity);
14864    return this.pdfiumModule.EPDFAnnot_SetOpacity(annotationPtr, pdfOpacity & 255);
14865  }
14866  /**
14867   * Get the rotation angle (in degrees) from the annotation's /Rotate entry.
14868   * Returns 0 if no rotation is set or on error.
14869   *
14870   * @param annotationPtr - pointer to the annotation
14871   * @returns rotation in degrees (0 if not set)
14872   */
14873  getAnnotationRotation(annotationPtr) {
14874    const rotationPtr = this.memoryManager.malloc(4);
14875    const ok = this.pdfiumModule.EPDFAnnot_GetRotate(annotationPtr, rotationPtr);
14876    if (!ok) {
14877      this.memoryManager.free(rotationPtr);
14878      return 0;
14879    }
14880    const rotation = this.pdfiumModule.pdfium.getValue(rotationPtr, "float");
14881    this.memoryManager.free(rotationPtr);
14882    return rotation;
14883  }
14884  /**
14885   * Set the rotation angle (in degrees) on the annotation's /Rotate entry.
14886   * A value of 0 removes the /Rotate key.
14887   *
14888   * @param annotationPtr - pointer to the annotation
14889   * @param rotation - rotation in degrees (clockwise)
14890   * @returns true on success
14891   */
14892  setAnnotationRotation(annotationPtr, rotation) {
14893    return !!this.pdfiumModule.EPDFAnnot_SetRotate(annotationPtr, rotation);
14894  }
14895  /**
14896   * Get the EmbedPDF extended rotation (in degrees) from the annotation's
14897   * /EPDFRotate entry. Returns 0 if not set or on error.
14898   *
14899   * @param annotationPtr - pointer to the annotation
14900   * @returns rotation in degrees (0 if not set)
14901   */
14902  getAnnotExtendedRotation(annotationPtr) {
14903    const rotationPtr = this.memoryManager.malloc(4);
14904    const ok = this.pdfiumModule.EPDFAnnot_GetExtendedRotation(annotationPtr, rotationPtr);
14905    if (!ok) {
14906      this.memoryManager.free(rotationPtr);
14907      return 0;
14908    }
14909    const rotation = this.pdfiumModule.pdfium.getValue(rotationPtr, "float");
14910    this.memoryManager.free(rotationPtr);
14911    return rotation;
14912  }
14913  /**
14914   * Set the EmbedPDF extended rotation (in degrees) on the annotation's
14915   * /EPDFRotate entry. A value of 0 removes the key.
14916   *
14917   * @param annotationPtr - pointer to the annotation
14918   * @param rotation - rotation in degrees
14919   * @returns true on success
14920   */
14921  setAnnotExtendedRotation(annotationPtr, rotation) {
14922    return !!this.pdfiumModule.EPDFAnnot_SetExtendedRotation(annotationPtr, rotation);
14923  }
14924  /**
14925   * Read the EmbedPDF unrotated rect from the annotation's /EPDFUnrotatedRect
14926   * entry. Returns the raw page-space rect (same format as \`readPageAnnoRect\`)
14927   * or null if not set.
14928   *
14929   * @param annotationPtr - pointer to the annotation
14930   * @returns raw \`{ left, top, right, bottom }\` in page coords, or null
14931   */
14932  readAnnotUnrotatedRect(annotationPtr) {
14933    const rectPtr = this.memoryManager.malloc(4 * 4);
14934    const ok = this.pdfiumModule.EPDFAnnot_GetUnrotatedRect(annotationPtr, rectPtr);
14935    if (!ok) {
14936      this.memoryManager.free(rectPtr);
14937      return null;
14938    }
14939    const left = this.pdfiumModule.pdfium.getValue(rectPtr, "float");
14940    const top = this.pdfiumModule.pdfium.getValue(rectPtr + 4, "float");
14941    const right = this.pdfiumModule.pdfium.getValue(rectPtr + 8, "float");
14942    const bottom = this.pdfiumModule.pdfium.getValue(rectPtr + 12, "float");
14943    this.memoryManager.free(rectPtr);
14944    if (left === 0 && top === 0 && right === 0 && bottom === 0) {
14945      return null;
14946    }
14947    return { left, top, right, bottom };
14948  }
14949  /**
14950   * Write the EmbedPDF unrotated rect (/EPDFUnrotatedRect) for an annotation.
14951   * Accepts a device-space \`Rect\` and converts to page coordinates internally,
14952   * following the same pattern as \`setPageAnnoRect\`.
14953   *
14954   * @param doc  - pdf document object
14955   * @param page - pdf page object
14956   * @param annotPtr - pointer to the annotation
14957   * @param rect - device-space rect to store as the unrotated rect
14958   * @returns true on success
14959   */
14960  setAnnotUnrotatedRect(doc, page, annotPtr, rect) {
14961    const x0d = rect.origin.x;
14962    const y0d = rect.origin.y;
14963    const x1d = rect.origin.x + rect.size.width;
14964    const y1d = rect.origin.y + rect.size.height;
14965    const TL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y0d });
14966    const TR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y0d });
14967    const BR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y1d });
14968    const BL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y1d });
14969    let left = Math.min(TL.x, TR.x, BR.x, BL.x);
14970    let right = Math.max(TL.x, TR.x, BR.x, BL.x);
14971    let bottom = Math.min(TL.y, TR.y, BR.y, BL.y);
14972    let top = Math.max(TL.y, TR.y, BR.y, BL.y);
14973    if (left > right) [left, right] = [right, left];
14974    if (bottom > top) [bottom, top] = [top, bottom];
14975    const ptr = this.memoryManager.malloc(16);
14976    const pdf = this.pdfiumModule.pdfium;
14977    pdf.setValue(ptr + 0, left, "float");
14978    pdf.setValue(ptr + 4, top, "float");
14979    pdf.setValue(ptr + 8, right, "float");
14980    pdf.setValue(ptr + 12, bottom, "float");
14981    const ok = this.pdfiumModule.EPDFAnnot_SetUnrotatedRect(annotPtr, ptr);
14982    this.memoryManager.free(ptr);
14983    return !!ok;
14984  }
14985  /**
14986   * Fetch the \`/Q\` text-alignment value from a **FreeText** annotation.
14987   *
14988   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
14989   * @returns \`PdfTextAlignment\`
14990   */
14991  getAnnotationTextAlignment(annotationPtr) {
14992    return this.pdfiumModule.EPDFAnnot_GetTextAlignment(annotationPtr);
14993  }
14994  /**
14995   * Write the \`/Q\` text-alignment value into a **FreeText** annotation
14996   * and clear the existing appearance stream so it can be regenerated.
14997   *
14998   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
14999   * @param alignment     \`PdfTextAlignment\`
15000   * @returns \`true\` on success
15001   */
15002  setAnnotationTextAlignment(annotationPtr, alignment) {
15003    return !!this.pdfiumModule.EPDFAnnot_SetTextAlignment(annotationPtr, alignment);
15004  }
15005  /**
15006   * Fetch the \`/EPDF:VerticalAlignment\` vertical-alignment value from a **FreeText** annotation.
15007   *
15008   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15009   * @returns \`PdfVerticalAlignment\`
15010   */
15011  getAnnotationVerticalAlignment(annotationPtr) {
15012    return this.pdfiumModule.EPDFAnnot_GetVerticalAlignment(annotationPtr);
15013  }
15014  /**
15015   * Write the \`/EPDF:VerticalAlignment\` vertical-alignment value into a **FreeText** annotation
15016   * and clear the existing appearance stream so it can be regenerated.
15017   *
15018   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15019   * @param alignment     \`PdfVerticalAlignment\`
15020   * @returns \`true\` on success
15021   */
15022  setAnnotationVerticalAlignment(annotationPtr, alignment) {
15023    return !!this.pdfiumModule.EPDFAnnot_SetVerticalAlignment(annotationPtr, alignment);
15024  }
15025  /**
15026   * Get the overlay text from a Redact annotation.
15027   *
15028   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15029   * @returns overlay text string or \`undefined\` if not set
15030   *
15031   * @private
15032   */
15033  getOverlayText(annotationPtr) {
15034    const len = this.pdfiumModule.EPDFAnnot_GetOverlayText(annotationPtr, 0, 0);
15035    if (len === 0) return void 0;
15036    const bytes = (len + 1) * 2;
15037    const ptr = this.memoryManager.malloc(bytes);
15038    this.pdfiumModule.EPDFAnnot_GetOverlayText(annotationPtr, ptr, bytes);
15039    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
15040    this.memoryManager.free(ptr);
15041    return value || void 0;
15042  }
15043  /**
15044   * Set the overlay text on a Redact annotation.
15045   *
15046   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15047   * @param text overlay text to set, or undefined/empty to clear
15048   * @returns \`true\` on success
15049   *
15050   * @private
15051   */
15052  setOverlayText(annotationPtr, text) {
15053    if (!text) {
15054      return this.pdfiumModule.EPDFAnnot_SetOverlayText(annotationPtr, 0);
15055    }
15056    return this.withWString(text, (wPtr) => {
15057      return this.pdfiumModule.EPDFAnnot_SetOverlayText(annotationPtr, wPtr);
15058    });
15059  }
15060  /**
15061   * Get whether overlay text repeats in a Redact annotation.
15062   *
15063   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15064   * @returns \`true\` if overlay text repeats
15065   *
15066   * @private
15067   */
15068  getOverlayTextRepeat(annotationPtr) {
15069    return this.pdfiumModule.EPDFAnnot_GetOverlayTextRepeat(annotationPtr);
15070  }
15071  /**
15072   * Set whether overlay text repeats in a Redact annotation.
15073   *
15074   * @param annotationPtr pointer returned by \`FPDFPage_GetAnnot\`
15075   * @param repeat whether overlay text should repeat
15076   * @returns \`true\` on success
15077   *
15078   * @private
15079   */
15080  setOverlayTextRepeat(annotationPtr, repeat) {
15081    return this.pdfiumModule.EPDFAnnot_SetOverlayTextRepeat(annotationPtr, repeat);
15082  }
15083  /**
15084   * Return the **default appearance** (font, size, colour) declared in the
15085   * \`/DA\` string of a **FreeText** annotation.
15086   *
15087   * @param annotationPtr  pointer to \`FPDF_ANNOTATION\`
15088   * @returns \`{ font, fontSize, color }\` or \`undefined\` when PDFium returns false
15089   *
15090   * NOTE – \`font\` is the raw \`FPDF_STANDARD_FONT\` enum value that PDFium uses
15091   *        (same range as the C API: 0 = Courier, 12 = ZapfDingbats, …).
15092   */
15093  getAnnotationDefaultAppearance(annotationPtr) {
15094    const fontPtr = this.memoryManager.malloc(4);
15095    const sizePtr = this.memoryManager.malloc(4);
15096    const rPtr = this.memoryManager.malloc(4);
15097    const gPtr = this.memoryManager.malloc(4);
15098    const bPtr = this.memoryManager.malloc(4);
15099    const ok = !!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(
15100      annotationPtr,
15101      fontPtr,
15102      sizePtr,
15103      rPtr,
15104      gPtr,
15105      bPtr
15106    );
15107    if (!ok) {
15108      [fontPtr, sizePtr, rPtr, gPtr, bPtr].forEach((p) => this.memoryManager.free(p));
15109      return;
15110    }
15111    const pdf = this.pdfiumModule.pdfium;
15112    const font = pdf.getValue(fontPtr, "i32");
15113    const fontSize = pdf.getValue(sizePtr, "float");
15114    const red = pdf.getValue(rPtr, "i32") & 255;
15115    const green = pdf.getValue(gPtr, "i32") & 255;
15116    const blue = pdf.getValue(bPtr, "i32") & 255;
15117    [fontPtr, sizePtr, rPtr, gPtr, bPtr].forEach((p) => this.memoryManager.free(p));
15118    return {
15119      fontFamily: font,
15120      fontSize,
15121      fontColor: pdfColorToWebColor({ red, green, blue })
15122    };
15123  }
15124  /**
15125   * Write a **default appearance** (\`/DA\`) into a FreeText annotation.
15126   *
15127   * @param annotationPtr pointer to \`FPDF_ANNOTATION\`
15128   * @param font          \`FPDF_STANDARD_FONT\` enum value
15129   * @param fontSize      size in points (≥ 0)
15130   * @param color         CSS-style \`#rrggbb\` string (alpha ignored)
15131   * @returns \`true\` on success
15132   */
15133  setAnnotationDefaultAppearance(annotationPtr, font, fontSize, color) {
15134    const { red, green, blue } = webColorToPdfColor(color);
15135    return !!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(
15136      annotationPtr,
15137      font,
15138      fontSize,
15139      red & 255,
15140      green & 255,
15141      blue & 255
15142    );
15143  }
15144  /**
15145   * Border‐style + width helper
15146   *
15147   * Tries the new PDFium helper \`EPDFAnnot_GetBorderStyle()\` (patch series
15148   * 9 July 2025).
15149   *
15150   * @param  annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15151   * @returns \`{ ok, style, width }\`
15152   *          • \`ok\`     – \`true\` when the call succeeded
15153   *          • \`style\`  – \`PdfAnnotationBorderStyle\` enum
15154   *          • \`width\`  – stroke-width in points (defaults to 0 pt)
15155   */
15156  getBorderStyle(annotationPtr) {
15157    const widthPtr = this.memoryManager.malloc(4);
15158    let width = 0;
15159    let style = PdfAnnotationBorderStyle.UNKNOWN;
15160    let ok = false;
15161    style = this.pdfiumModule.EPDFAnnot_GetBorderStyle(annotationPtr, widthPtr);
15162    width = this.pdfiumModule.pdfium.getValue(widthPtr, "float");
15163    ok = style !== PdfAnnotationBorderStyle.UNKNOWN;
15164    this.memoryManager.free(widthPtr);
15165    return { ok, style, width };
15166  }
15167  setBorderStyle(annotationPtr, style, width) {
15168    return this.pdfiumModule.EPDFAnnot_SetBorderStyle(annotationPtr, style, width);
15169  }
15170  /**
15171   * Get the /Name entry of the annotation
15172   *
15173   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15174   * @returns \`PdfAnnotationName\`
15175   */
15176  getAnnotationName(annotationPtr) {
15177    return this.pdfiumModule.EPDFAnnot_GetName(annotationPtr);
15178  }
15179  /**
15180   * Set the /Name entry of the annotation
15181   *
15182   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15183   * @param name - \`PdfAnnotationName\`
15184   * @returns \`true\` on success
15185   */
15186  setAnnotationName(annotationPtr, name) {
15187    return this.pdfiumModule.EPDFAnnot_SetName(annotationPtr, name);
15188  }
15189  /**
15190   * Get the reply type of the annotation (RT property per ISO 32000-2)
15191   *
15192   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15193   * @returns \`PdfAnnotationReplyType\`
15194   */
15195  getReplyType(annotationPtr) {
15196    return this.pdfiumModule.EPDFAnnot_GetReplyType(annotationPtr);
15197  }
15198  /**
15199   * Set the reply type of the annotation (RT property per ISO 32000-2)
15200   *
15201   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15202   * @param replyType - \`PdfAnnotationReplyType\`
15203   * @returns \`true\` on success
15204   */
15205  setReplyType(annotationPtr, replyType) {
15206    return this.pdfiumModule.EPDFAnnot_SetReplyType(
15207      annotationPtr,
15208      replyType ?? PdfAnnotationReplyType.Unknown
15209    );
15210  }
15211  /**
15212   * Border-effect (“cloudy”) helper
15213   *
15214   * Calls the new PDFium function \`EPDFAnnot_GetBorderEffect()\` (July 2025).
15215   *
15216   * @param  annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15217   * @returns \`{ ok, intensity }\`
15218   *          • \`ok\`        – \`true\` when the annotation *does* have a
15219   *                          valid cloudy-border effect
15220   *          • \`intensity\` – radius/intensity value (0 when \`ok\` is false)
15221   */
15222  getBorderEffect(annotationPtr) {
15223    const intensityPtr = this.memoryManager.malloc(4);
15224    const ok = !!this.pdfiumModule.EPDFAnnot_GetBorderEffect(annotationPtr, intensityPtr);
15225    const intensity = ok ? this.pdfiumModule.pdfium.getValue(intensityPtr, "float") : 0;
15226    this.memoryManager.free(intensityPtr);
15227    return { ok, intensity };
15228  }
15229  /**
15230   * Rectangle-differences helper ( /RD array on Square / Circle annots )
15231   *
15232   * Calls \`EPDFAnnot_GetRectangleDifferences()\` introduced in July 2025.
15233   *
15234   * @param  annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15235   * @returns \`{ ok, left, top, right, bottom }\`
15236   *          • \`ok\`     – \`true\` when the annotation *has* an /RD entry
15237   *          • the four floats are 0 when \`ok\` is false
15238   */
15239  getRectangleDifferences(annotationPtr) {
15240    const lPtr = this.memoryManager.malloc(4);
15241    const tPtr = this.memoryManager.malloc(4);
15242    const rPtr = this.memoryManager.malloc(4);
15243    const bPtr = this.memoryManager.malloc(4);
15244    const ok = !!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(
15245      annotationPtr,
15246      lPtr,
15247      tPtr,
15248      rPtr,
15249      bPtr
15250    );
15251    const pdf = this.pdfiumModule.pdfium;
15252    const left = pdf.getValue(lPtr, "float");
15253    const top = pdf.getValue(tPtr, "float");
15254    const right = pdf.getValue(rPtr, "float");
15255    const bottom = pdf.getValue(bPtr, "float");
15256    this.memoryManager.free(lPtr);
15257    this.memoryManager.free(tPtr);
15258    this.memoryManager.free(rPtr);
15259    this.memoryManager.free(bPtr);
15260    return { ok, left, top, right, bottom };
15261  }
15262  /**
15263   * Sets the /RD array on an annotation.
15264   *
15265   * @param annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15266   * @param rd  the four inset values, or \`undefined\` to clear
15267   * @returns \`true\` on success
15268   */
15269  setRectangleDifferences(annotationPtr, rd) {
15270    if (!rd) {
15271      return this.pdfiumModule.EPDFAnnot_ClearRectangleDifferences(annotationPtr);
15272    }
15273    return this.pdfiumModule.EPDFAnnot_SetRectangleDifferences(
15274      annotationPtr,
15275      rd.left,
15276      rd.top,
15277      rd.right,
15278      rd.bottom
15279    );
15280  }
15281  /**
15282   * Sets or clears the /BE (border effect) dictionary on an annotation.
15283   *
15284   * @param annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15285   * @param intensity  cloudy border intensity, or \`undefined\` to clear
15286   * @returns \`true\` on success
15287   */
15288  setBorderEffect(annotationPtr, intensity) {
15289    if (intensity === void 0 || intensity <= 0) {
15290      return this.pdfiumModule.EPDFAnnot_ClearBorderEffect(annotationPtr);
15291    }
15292    return this.pdfiumModule.EPDFAnnot_SetBorderEffect(annotationPtr, intensity);
15293  }
15294  /**
15295   * Get the date of the annotation
15296   *
15297   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15298   * @param key - 'M' for modified date, 'CreationDate' for creation date
15299   * @returns \`Date\` or \`undefined\` when PDFium can't read the date
15300   */
15301  getAnnotationDate(annotationPtr, key) {
15302    const raw = this.getAnnotString(annotationPtr, key);
15303    return raw ? pdfDateToDate(raw) : void 0;
15304  }
15305  /**
15306   * Set the date of the annotation
15307   *
15308   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15309   * @param key - 'M' for modified date, 'CreationDate' for creation date
15310   * @param date - \`Date\` to set
15311   * @returns \`true\` on success
15312   */
15313  setAnnotationDate(annotationPtr, key, date) {
15314    const raw = dateToPdfDate(date);
15315    return this.setAnnotString(annotationPtr, key, raw);
15316  }
15317  /**
15318   * Get the date of the attachment
15319   *
15320   * @param attachmentPtr - pointer to an \`FPDF_ATTACHMENT\`
15321   * @param key - 'ModDate' for modified date, 'CreationDate' for creation date
15322   * @returns \`Date\` or \`undefined\` when PDFium can't read the date
15323   */
15324  getAttachmentDate(attachmentPtr, key) {
15325    const raw = this.getAttachmentString(attachmentPtr, key);
15326    return raw ? pdfDateToDate(raw) : void 0;
15327  }
15328  /**
15329   * Set the date of the attachment
15330   *
15331   * @param attachmentPtr - pointer to an \`FPDF_ATTACHMENT\`
15332   * @param key - 'ModDate' for modified date, 'CreationDate' for creation date
15333   * @param date - \`Date\` to set
15334   * @returns \`true\` on success
15335   */
15336  setAttachmentDate(attachmentPtr, key, date) {
15337    const raw = dateToPdfDate(date);
15338    return this.setAttachmentString(attachmentPtr, key, raw);
15339  }
15340  /**
15341   * Dash-pattern helper ( /BS → /D array, dashed borders only )
15342   *
15343   * Uses the two new PDFium helpers:
15344   *   • \`EPDFAnnot_GetBorderDashPatternCount\`
15345   *   • \`EPDFAnnot_GetBorderDashPattern\`
15346   *
15347   * @param  annotationPtr  pointer to an \`FPDF_ANNOTATION\`
15348   * @returns \`{ ok, pattern }\`
15349   *          • \`ok\`       – \`true\` when the annot is dashed *and* the array
15350   *                          was retrieved successfully
15351   *          • \`pattern\`  – numeric array of dash/space lengths (empty when \`ok\` is false)
15352   */
15353  getBorderDashPattern(annotationPtr) {
15354    const count = this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(annotationPtr);
15355    if (count === 0) {
15356      return { ok: false, pattern: [] };
15357    }
15358    const arrPtr = this.memoryManager.malloc(4 * count);
15359    const okNative = !!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(
15360      annotationPtr,
15361      arrPtr,
15362      count
15363    );
15364    const pattern = [];
15365    if (okNative) {
15366      const pdf = this.pdfiumModule.pdfium;
15367      for (let i = 0; i < count; i++) {
15368        pattern.push(pdf.getValue(arrPtr + 4 * i, "float"));
15369      }
15370    }
15371    this.memoryManager.free(arrPtr);
15372    return { ok: okNative, pattern };
15373  }
15374  /**
15375   * Write the /BS /D dash pattern array for an annotation border.
15376   *
15377   * @param annotationPtr Pointer to FPDF_ANNOTATION
15378   * @param pattern       Array of dash/space lengths in *points* (e.g. [3, 2])
15379   *                      Empty array clears the pattern (solid line).
15380   * @returns true on success
15381   *
15382   * @private
15383   */
15384  setBorderDashPattern(annotationPtr, pattern) {
15385    if (!pattern || pattern.length === 0) {
15386      return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(annotationPtr, 0, 0);
15387    }
15388    const clean = pattern.map((n) => Number.isFinite(n) && n > 0 ? n : 0).filter((n) => n > 0);
15389    if (clean.length === 0) {
15390      return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(annotationPtr, 0, 0);
15391    }
15392    const bytes = 4 * clean.length;
15393    const bufPtr = this.memoryManager.malloc(bytes);
15394    for (let i = 0; i < clean.length; i++) {
15395      this.pdfiumModule.pdfium.setValue(bufPtr + 4 * i, clean[i], "float");
15396    }
15397    const ok = !!this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(
15398      annotationPtr,
15399      bufPtr,
15400      clean.length
15401    );
15402    this.memoryManager.free(bufPtr);
15403    return ok;
15404  }
15405  /**
15406   * Return the \`/LE\` array (start/end line-ending styles) for a LINE / POLYLINE annot.
15407   *
15408   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15409   * @returns \`{ start, end }\` or \`undefined\` when PDFium can't read them
15410   *
15411   * @private
15412   */
15413  getLineEndings(annotationPtr) {
15414    const startPtr = this.memoryManager.malloc(4);
15415    const endPtr = this.memoryManager.malloc(4);
15416    const ok = !!this.pdfiumModule.EPDFAnnot_GetLineEndings(annotationPtr, startPtr, endPtr);
15417    if (!ok) {
15418      this.memoryManager.free(startPtr);
15419      this.memoryManager.free(endPtr);
15420      return void 0;
15421    }
15422    const start = this.pdfiumModule.pdfium.getValue(startPtr, "i32");
15423    const end = this.pdfiumModule.pdfium.getValue(endPtr, "i32");
15424    this.memoryManager.free(startPtr);
15425    this.memoryManager.free(endPtr);
15426    return { start, end };
15427  }
15428  /**
15429   * Write the \`/LE\` array (start/end line-ending styles) for a LINE / POLYLINE annot.
15430   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15431   * @param start - start line ending style
15432   * @param end - end line ending style
15433   * @returns \`true\` on success
15434   */
15435  setLineEndings(annotationPtr, start, end) {
15436    return !!this.pdfiumModule.EPDFAnnot_SetLineEndings(annotationPtr, start, end);
15437  }
15438  /**
15439   * Get the start and end points of a LINE / POLYLINE annot.
15440   * @param doc - pdf document object
15441   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
15442   * @param page - logical page info object (\`PdfPageObject\`)
15443   * @returns \`{ start, end }\` or \`undefined\` when PDFium can't read them
15444   */
15445  getLinePoints(doc, page, annotationPtr) {
15446    const startPtr = this.memoryManager.malloc(8);
15447    const endPtr = this.memoryManager.malloc(8);
15448    const ok = this.pdfiumModule.FPDFAnnot_GetLine(annotationPtr, startPtr, endPtr);
15449    if (!ok) {
15450      this.memoryManager.free(startPtr);
15451      this.memoryManager.free(endPtr);
15452      return void 0;
15453    }
15454    const pdf = this.pdfiumModule.pdfium;
15455    const sx = pdf.getValue(startPtr + 0, "float");
15456    const sy = pdf.getValue(startPtr + 4, "float");
15457    const ex = pdf.getValue(endPtr + 0, "float");
15458    const ey = pdf.getValue(endPtr + 4, "float");
15459    this.memoryManager.free(startPtr);
15460    this.memoryManager.free(endPtr);
15461    const start = this.convertPagePointToDevicePoint(doc, page, { x: sx, y: sy });
15462    const end = this.convertPagePointToDevicePoint(doc, page, { x: ex, y: ey });
15463    return { start, end };
15464  }
15465  /**
15466   * Set the two end‑points of a **Line** annotation
15467   * by writing a new /L array \`[ x1 y1 x2 y2 ]\`.
15468   * @param doc - pdf document object
15469   * @param page - logical page info object (\`PdfPageObject\`)
15470   * @param annotPtr - pointer to the annotation whose line points are needed
15471   * @param start - start point
15472   * @param end - end point
15473   * @returns true on success
15474   */
15475  setLinePoints(doc, page, annotPtr, start, end) {
15476    const p1 = this.convertDevicePointToPagePoint(doc, page, start);
15477    const p2 = this.convertDevicePointToPagePoint(doc, page, end);
15478    if (!p1 || !p2) return false;
15479    const buf = this.memoryManager.malloc(16);
15480    const pdf = this.pdfiumModule.pdfium;
15481    pdf.setValue(buf + 0, p1.x, "float");
15482    pdf.setValue(buf + 4, p1.y, "float");
15483    pdf.setValue(buf + 8, p2.x, "float");
15484    pdf.setValue(buf + 12, p2.y, "float");
15485    const ok = this.pdfiumModule.EPDFAnnot_SetLine(annotPtr, buf, buf + 8);
15486    this.memoryManager.free(buf);
15487    return !!ok;
15488  }
15489  /**
15490   * Read \`/QuadPoints\` from any annotation and convert each quadrilateral to
15491   * device-space coordinates.
15492   *
15493   * The four points are returned in natural reading order:
15494   *   \`p1 → p2\` (top edge) and \`p4 → p3\` (bottom edge).
15495   * This preserves the true shape for rotated / skewed text, whereas callers
15496   * that only need axis-aligned boxes can collapse each quad themselves.
15497   *
15498   * @param doc           - pdf document object
15499   * @param page          - logical page info object (\`PdfPageObject\`)
15500   * @param annotationPtr - pointer to the annotation whose quads are needed
15501   * @returns Array of \`Rect\` objects (\`[]\` if the annotation has no quads)
15502   *
15503   * @private
15504   */
15505  getQuadPointsAnno(doc, page, annotationPtr) {
15506    const quadCount = this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(annotationPtr);
15507    if (quadCount === 0) return [];
15508    const FS_QUADPOINTSF_SIZE = 8 * 4;
15509    const quads = [];
15510    for (let qi = 0; qi < quadCount; qi++) {
15511      const quadPtr = this.memoryManager.malloc(FS_QUADPOINTSF_SIZE);
15512      const ok = this.pdfiumModule.FPDFAnnot_GetAttachmentPoints(annotationPtr, qi, quadPtr);
15513      if (ok) {
15514        const xs = [];
15515        const ys = [];
15516        for (let i = 0; i < 4; i++) {
15517          const base = quadPtr + i * 8;
15518          xs.push(this.pdfiumModule.pdfium.getValue(base, "float"));
15519          ys.push(this.pdfiumModule.pdfium.getValue(base + 4, "float"));
15520        }
15521        const p1 = this.convertPagePointToDevicePoint(doc, page, { x: xs[0], y: ys[0] });
15522        const p2 = this.convertPagePointToDevicePoint(doc, page, { x: xs[1], y: ys[1] });
15523        const p3 = this.convertPagePointToDevicePoint(doc, page, { x: xs[2], y: ys[2] });
15524        const p4 = this.convertPagePointToDevicePoint(doc, page, { x: xs[3], y: ys[3] });
15525        quads.push({ p1, p2, p3, p4 });
15526      }
15527      this.memoryManager.free(quadPtr);
15528    }
15529    return quads.map(quadToRect);
15530  }
15531  /**
15532   * Set the quadrilaterals for a **Highlight / Underline / StrikeOut / Squiggly** markup annotation.
15533   *
15534   * @param doc           - pdf document object
15535   * @param page          - logical page info object (\`PdfPageObject\`)
15536   * @param annotationPtr - pointer to the annotation whose quads are needed
15537   * @param rects         - array of \`Rect\` objects (\`[]\` if the annotation has no quads)
15538   * @returns \`true\` if the operation was successful
15539   *
15540   * @private
15541   */
15542  syncQuadPointsAnno(doc, page, annotPtr, rects) {
15543    const FS_QUADPOINTSF_SIZE = 8 * 4;
15544    const pdf = this.pdfiumModule.pdfium;
15545    const count = this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(annotPtr);
15546    const buf = this.memoryManager.malloc(FS_QUADPOINTSF_SIZE);
15547    const writeQuad = (r) => {
15548      const q = rectToQuad(r);
15549      const p1 = this.convertDevicePointToPagePoint(doc, page, q.p1);
15550      const p2 = this.convertDevicePointToPagePoint(doc, page, q.p2);
15551      const p3 = this.convertDevicePointToPagePoint(doc, page, q.p3);
15552      const p4 = this.convertDevicePointToPagePoint(doc, page, q.p4);
15553      pdf.setValue(buf + 0, p1.x, "float");
15554      pdf.setValue(buf + 4, p1.y, "float");
15555      pdf.setValue(buf + 8, p2.x, "float");
15556      pdf.setValue(buf + 12, p2.y, "float");
15557      pdf.setValue(buf + 16, p4.x, "float");
15558      pdf.setValue(buf + 20, p4.y, "float");
15559      pdf.setValue(buf + 24, p3.x, "float");
15560      pdf.setValue(buf + 28, p3.y, "float");
15561    };
15562    const min = Math.min(count, rects.length);
15563    for (let i = 0; i < min; i++) {
15564      writeQuad(rects[i]);
15565      if (!this.pdfiumModule.FPDFAnnot_SetAttachmentPoints(annotPtr, i, buf)) {
15566        this.memoryManager.free(buf);
15567        return false;
15568      }
15569    }
15570    for (let i = count; i < rects.length; i++) {
15571      writeQuad(rects[i]);
15572      if (!this.pdfiumModule.FPDFAnnot_AppendAttachmentPoints(annotPtr, buf)) {
15573        this.memoryManager.free(buf);
15574        return false;
15575      }
15576    }
15577    this.memoryManager.free(buf);
15578    return true;
15579  }
15580  /**
15581   * Redact text that intersects ANY of the provided **quads** (device-space).
15582   * Returns \`true\` if the page changed. Always regenerates the page stream.
15583   */
15584  redactTextInRects(doc, page, rects, options) {
15585    const { recurseForms = true, drawBlackBoxes = false } = options ?? {};
15586    this.logger.debug(
15587      "PDFiumEngine",
15588      "Engine",
15589      "redactTextInQuads",
15590      doc.id,
15591      page.index,
15592      rects.length
15593    );
15594    const label = "RedactTextInQuads";
15595    this.logger.perf("PDFiumEngine", "Engine", label, "Begin", \`\${doc.id}-\${page.index}\`);
15596    const ctx = this.cache.getContext(doc.id);
15597    if (!ctx) {
15598      this.logger.perf("PDFiumEngine", "Engine", label, "End", \`\${doc.id}-\${page.index}\`);
15599      return PdfTaskHelper.reject({
15600        code: PdfErrorCode.DocNotOpen,
15601        message: "document does not open"
15602      });
15603    }
15604    const clean = (rects ?? []).filter(
15605      (r) => {
15606        var _a, _b, _c, _d;
15607        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;
15608      }
15609    );
15610    if (clean.length === 0) {
15611      this.logger.perf("PDFiumEngine", "Engine", label, "End", \`\${doc.id}-\${page.index}\`);
15612      return PdfTaskHelper.resolve(false);
15613    }
15614    const pageCtx = ctx.acquirePage(page.index);
15615    const { ptr, count } = this.allocFSQuadsBufferFromRects(doc, page, clean);
15616    let ok = false;
15617    try {
15618      ok = !!this.pdfiumModule.EPDFText_RedactInQuads(
15619        pageCtx.pagePtr,
15620        ptr,
15621        count,
15622        recurseForms ? true : false,
15623        false
15624      );
15625    } finally {
15626      this.memoryManager.free(ptr);
15627    }
15628    if (ok) {
15629      ok = !!this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
15630    }
15631    pageCtx.disposeImmediate();
15632    this.logger.perf("PDFiumEngine", "Engine", label, "End", \`\${doc.id}-\${page.index}\`);
15633    return PdfTaskHelper.resolve(!!ok);
15634  }
15635  /**
15636   * Apply a single redaction annotation, permanently removing content underneath
15637   * and flattening the RO (Redact Overlay) appearance stream if present.
15638   * The annotation is removed after successful application.
15639   *
15640   * @param doc - document object
15641   * @param page - page object
15642   * @param annotation - the redact annotation to apply
15643   * @returns true if successful
15644   */
15645  applyRedaction(doc, page, annotation) {
15646    this.logger.debug(
15647      LOG_SOURCE$1,
15648      LOG_CATEGORY$1,
15649      "applyRedaction",
15650      doc.id,
15651      page.index,
15652      annotation.id
15653    );
15654    const label = "ApplyRedaction";
15655    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15656    const ctx = this.cache.getContext(doc.id);
15657    if (!ctx) {
15658      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15659      return PdfTaskHelper.reject({
15660        code: PdfErrorCode.DocNotOpen,
15661        message: "document does not open"
15662      });
15663    }
15664    const pageCtx = ctx.acquirePage(page.index);
15665    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
15666    if (!annotPtr) {
15667      pageCtx.release();
15668      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15669      return PdfTaskHelper.reject({
15670        code: PdfErrorCode.NotFound,
15671        message: "annotation not found"
15672      });
15673    }
15674    const ok = this.pdfiumModule.EPDFAnnot_ApplyRedaction(pageCtx.pagePtr, annotPtr);
15675    this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
15676    if (ok) {
15677      this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
15678    }
15679    pageCtx.disposeImmediate();
15680    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15681    return PdfTaskHelper.resolve(!!ok);
15682  }
15683  /**
15684   * Apply all redaction annotations on a page, permanently removing content
15685   * underneath each one and flattening RO streams if present.
15686   * All redact annotations are removed after successful application.
15687   *
15688   * @param doc - document object
15689   * @param page - page object
15690   * @returns true if any redactions were applied
15691   */
15692  applyAllRedactions(doc, page) {
15693    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "applyAllRedactions", doc.id, page.index);
15694    const label = "ApplyAllRedactions";
15695    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15696    const ctx = this.cache.getContext(doc.id);
15697    if (!ctx) {
15698      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15699      return PdfTaskHelper.reject({
15700        code: PdfErrorCode.DocNotOpen,
15701        message: "document does not open"
15702      });
15703    }
15704    const pageCtx = ctx.acquirePage(page.index);
15705    const ok = this.pdfiumModule.EPDFPage_ApplyRedactions(pageCtx.pagePtr);
15706    if (ok) {
15707      this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
15708    }
15709    pageCtx.disposeImmediate();
15710    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15711    return PdfTaskHelper.resolve(!!ok);
15712  }
15713  /**
15714   * Flatten an annotation's appearance (AP/N) to page content.
15715   * The annotation's visual appearance becomes part of the page itself.
15716   * The annotation is automatically removed after flattening.
15717   *
15718   * @param doc - document object
15719   * @param page - page object
15720   * @param annotation - the annotation to flatten
15721   * @returns true if successful
15722   */
15723  flattenAnnotation(doc, page, annotation) {
15724    this.logger.debug(
15725      LOG_SOURCE$1,
15726      LOG_CATEGORY$1,
15727      "flattenAnnotation",
15728      doc.id,
15729      page.index,
15730      annotation.id
15731    );
15732    const label = "FlattenAnnotation";
15733    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15734    const ctx = this.cache.getContext(doc.id);
15735    if (!ctx) {
15736      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15737      return PdfTaskHelper.reject({
15738        code: PdfErrorCode.DocNotOpen,
15739        message: "document does not open"
15740      });
15741    }
15742    const pageCtx = ctx.acquirePage(page.index);
15743    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
15744    if (!annotPtr) {
15745      pageCtx.release();
15746      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15747      return PdfTaskHelper.reject({
15748        code: PdfErrorCode.NotFound,
15749        message: "annotation not found"
15750      });
15751    }
15752    const ok = this.pdfiumModule.EPDFAnnot_Flatten(pageCtx.pagePtr, annotPtr);
15753    this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
15754    if (ok) {
15755      this.pdfiumModule.FPDFPage_GenerateContent(pageCtx.pagePtr);
15756    }
15757    pageCtx.disposeImmediate();
15758    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15759    return PdfTaskHelper.resolve(!!ok);
15760  }
15761  /**
15762   * Export an annotation's appearance as a standalone single-page PDF.
15763   *
15764   * @param doc - document object
15765   * @param page - page object
15766   * @param annotation - the annotation to export
15767   * @returns a PDF buffer containing the annotation appearance
15768   */
15769  exportAnnotationAppearanceAsPdf(doc, page, annotation) {
15770    this.logger.debug(
15771      LOG_SOURCE$1,
15772      LOG_CATEGORY$1,
15773      "exportAnnotationAppearanceAsPdf",
15774      doc.id,
15775      page.index,
15776      annotation.id
15777    );
15778    const label = "ExportAnnotationAppearanceAsPdf";
15779    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15780    const ctx = this.cache.getContext(doc.id);
15781    if (!ctx) {
15782      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15783      return PdfTaskHelper.reject({
15784        code: PdfErrorCode.DocNotOpen,
15785        message: "document does not open"
15786      });
15787    }
15788    const pageCtx = ctx.acquirePage(page.index);
15789    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
15790    if (!annotPtr) {
15791      pageCtx.release();
15792      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15793      return PdfTaskHelper.reject({
15794        code: PdfErrorCode.NotFound,
15795        message: "annotation not found"
15796      });
15797    }
15798    const exportedDocPtr = this.pdfiumModule.EPDFAnnot_ExportAppearanceAsDocument(annotPtr);
15799    this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
15800    if (!exportedDocPtr) {
15801      pageCtx.release();
15802      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15803      return PdfTaskHelper.reject({
15804        code: PdfErrorCode.CantCreateNewDoc,
15805        message: "can not export annotation as pdf"
15806      });
15807    }
15808    try {
15809      return PdfTaskHelper.resolve(this.saveDocument(exportedDocPtr));
15810    } finally {
15811      this.pdfiumModule.FPDF_CloseDocument(exportedDocPtr);
15812      pageCtx.release();
15813      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15814    }
15815  }
15816  /**
15817   * Export multiple annotations' appearances as a standalone single-page PDF.
15818   * All annotations must be on the same page. The resulting page is sized to
15819   * the union of all annotation rects, with each appearance positioned correctly.
15820   *
15821   * @param doc - document object
15822   * @param page - page object
15823   * @param annotations - the annotations to export
15824   * @returns a PDF buffer containing the combined appearances
15825   */
15826  exportAnnotationsAppearanceAsPdf(doc, page, annotations) {
15827    this.logger.debug(
15828      LOG_SOURCE$1,
15829      LOG_CATEGORY$1,
15830      "exportAnnotationsAppearanceAsPdf",
15831      doc.id,
15832      page.index,
15833      annotations.map((a) => a.id)
15834    );
15835    const label = "ExportAnnotationsAppearanceAsPdf";
15836    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "Begin", \`\${doc.id}-\${page.index}\`);
15837    const ctx = this.cache.getContext(doc.id);
15838    if (!ctx) {
15839      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15840      return PdfTaskHelper.reject({
15841        code: PdfErrorCode.DocNotOpen,
15842        message: "document does not open"
15843      });
15844    }
15845    if (annotations.length === 0) {
15846      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15847      return PdfTaskHelper.reject({
15848        code: PdfErrorCode.NotFound,
15849        message: "no annotations provided"
15850      });
15851    }
15852    const pageCtx = ctx.acquirePage(page.index);
15853    const annotPtrs = [];
15854    for (const annotation of annotations) {
15855      const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
15856      if (!annotPtr) {
15857        for (const ptr of annotPtrs) {
15858          this.pdfiumModule.FPDFPage_CloseAnnot(ptr);
15859        }
15860        pageCtx.release();
15861        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15862        return PdfTaskHelper.reject({
15863          code: PdfErrorCode.NotFound,
15864          message: \`annotation not found: \${annotation.id}\`
15865        });
15866      }
15867      annotPtrs.push(annotPtr);
15868    }
15869    const ptrArraySize = annotPtrs.length * 4;
15870    const ptrArrayPtr = this.memoryManager.malloc(ptrArraySize);
15871    for (let i = 0; i < annotPtrs.length; i++) {
15872      this.pdfiumModule.pdfium.setValue(ptrArrayPtr + i * 4, annotPtrs[i], "i32");
15873    }
15874    const exportedDocPtr = this.pdfiumModule.EPDFAnnot_ExportMultipleAppearancesAsDocument(
15875      ptrArrayPtr,
15876      annotPtrs.length
15877    );
15878    this.memoryManager.free(ptrArrayPtr);
15879    for (const ptr of annotPtrs) {
15880      this.pdfiumModule.FPDFPage_CloseAnnot(ptr);
15881    }
15882    if (!exportedDocPtr) {
15883      pageCtx.release();
15884      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15885      return PdfTaskHelper.reject({
15886        code: PdfErrorCode.CantCreateNewDoc,
15887        message: "can not export annotations as pdf"
15888      });
15889    }
15890    try {
15891      return PdfTaskHelper.resolve(this.saveDocument(exportedDocPtr));
15892    } finally {
15893      this.pdfiumModule.FPDF_CloseDocument(exportedDocPtr);
15894      pageCtx.release();
15895      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, label, "End", \`\${doc.id}-\${page.index}\`);
15896    }
15897  }
15898  /** Pack device-space Rects into an FS_QUADPOINTSF[] buffer (page space). */
15899  allocFSQuadsBufferFromRects(doc, page, rects) {
15900    const STRIDE = 32;
15901    const count = rects.length;
15902    const ptr = this.memoryManager.malloc(STRIDE * count);
15903    const pdf = this.pdfiumModule.pdfium;
15904    for (let i = 0; i < count; i++) {
15905      const r = rects[i];
15906      const q = rectToQuad(r);
15907      const p1 = this.convertDevicePointToPagePoint(doc, page, q.p1);
15908      const p2 = this.convertDevicePointToPagePoint(doc, page, q.p2);
15909      const p3 = this.convertDevicePointToPagePoint(doc, page, q.p3);
15910      const p4 = this.convertDevicePointToPagePoint(doc, page, q.p4);
15911      const base = ptr + i * STRIDE;
15912      pdf.setValue(base + 0, p1.x, "float");
15913      pdf.setValue(base + 4, p1.y, "float");
15914      pdf.setValue(base + 8, p2.x, "float");
15915      pdf.setValue(base + 12, p2.y, "float");
15916      pdf.setValue(base + 16, p4.x, "float");
15917      pdf.setValue(base + 20, p4.y, "float");
15918      pdf.setValue(base + 24, p3.x, "float");
15919      pdf.setValue(base + 28, p3.y, "float");
15920    }
15921    return { ptr, count };
15922  }
15923  /**
15924   * Read ink list from annotation
15925   * @param doc - pdf document object
15926   * @param page  - logical page info object (\`PdfPageObject\`)
15927   * @param pagePtr - pointer to the page
15928   * @param annotationPtr - pointer to the annotation whose ink list is needed
15929   * @returns ink list
15930   */
15931  getInkList(doc, page, annotationPtr) {
15932    const inkList = [];
15933    const pathCount = this.pdfiumModule.FPDFAnnot_GetInkListCount(annotationPtr);
15934    if (pathCount <= 0) return inkList;
15935    const pdf = this.pdfiumModule.pdfium;
15936    const POINT_STRIDE = 8;
15937    for (let i = 0; i < pathCount; i++) {
15938      const points = [];
15939      const n = this.pdfiumModule.FPDFAnnot_GetInkListPath(annotationPtr, i, 0, 0);
15940      if (n > 0) {
15941        const buf = this.memoryManager.malloc(n * POINT_STRIDE);
15942        this.pdfiumModule.FPDFAnnot_GetInkListPath(annotationPtr, i, buf, n);
15943        for (let j = 0; j < n; j++) {
15944          const base = buf + j * POINT_STRIDE;
15945          const px = pdf.getValue(base + 0, "float");
15946          const py = pdf.getValue(base + 4, "float");
15947          const d = this.convertPagePointToDevicePoint(doc, page, { x: px, y: py });
15948          points.push({ x: d.x, y: d.y });
15949        }
15950        this.memoryManager.free(buf);
15951      }
15952      inkList.push({ points });
15953    }
15954    return inkList;
15955  }
15956  /**
15957   * Add ink list to annotation
15958   * @param doc - pdf document object
15959   * @param page  - logical page info object (\`PdfPageObject\`)
15960   * @param pagePtr - pointer to the page
15961   * @param annotationPtr - pointer to the annotation whose ink list is needed
15962   * @param inkList - ink list array of \`PdfInkListObject\`
15963   * @returns \`true\` if the operation was successful
15964   */
15965  setInkList(doc, page, annotationPtr, inkList) {
15966    const pdf = this.pdfiumModule.pdfium;
15967    const POINT_STRIDE = 8;
15968    for (const stroke of inkList) {
15969      const n = stroke.points.length;
15970      if (n === 0) continue;
15971      const buf = this.memoryManager.malloc(n * POINT_STRIDE);
15972      for (let i = 0; i < n; i++) {
15973        const pDev = stroke.points[i];
15974        const pPage = this.convertDevicePointToPagePoint(doc, page, pDev);
15975        pdf.setValue(buf + i * POINT_STRIDE + 0, pPage.x, "float");
15976        pdf.setValue(buf + i * POINT_STRIDE + 4, pPage.y, "float");
15977      }
15978      const idx = this.pdfiumModule.FPDFAnnot_AddInkStroke(annotationPtr, buf, n);
15979      this.memoryManager.free(buf);
15980      if (idx === -1) {
15981        return false;
15982      }
15983    }
15984    return true;
15985  }
15986  /**
15987   * Read pdf text annotation
15988   * @param page  - pdf page infor
15989   * @param annotationPtr - pointer to pdf annotation
15990   * @param index  - index of annotation in the pdf page
15991   * @returns pdf text annotation
15992   *
15993   * @private
15994   */
15995  readPdfTextAnno(doc, page, annotationPtr, index) {
15996    const annoRect = this.readPageAnnoRect(annotationPtr);
15997    const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);
15998    const state = this.getAnnotString(annotationPtr, "State");
15999    const stateModel = this.getAnnotString(annotationPtr, "StateModel");
16000    const color = this.getAnnotationColor(annotationPtr);
16001    const opacity = this.getAnnotationOpacity(annotationPtr);
16002    const name = this.getAnnotationName(annotationPtr);
16003    return {
16004      pageIndex: page.index,
16005      id: index,
16006      type: PdfAnnotationSubtype.TEXT,
16007      rect,
16008      strokeColor: color ?? "#FFFF00",
16009      color: color ?? "#FFFF00",
16010      opacity,
16011      state,
16012      stateModel,
16013      name,
16014      icon: name,
16015      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16016    };
16017  }
16018  /**
16019   * Read pdf freetext annotation
16020   * @param page  - pdf page infor
16021   * @param annotationPtr - pointer to pdf annotation
16022   * @param index  - index of annotation in the pdf page
16023   * @returns pdf freetext annotation
16024   *
16025   * @private
16026   */
16027  readPdfFreeTextAnno(doc, page, annotationPtr, index) {
16028    const annoRect = this.readPageAnnoRect(annotationPtr);
16029    const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);
16030    const defaultStyle = this.getAnnotString(annotationPtr, "DS");
16031    const da = this.getAnnotationDefaultAppearance(annotationPtr);
16032    const bgColor = this.getAnnotationColor(annotationPtr);
16033    const textAlign = this.getAnnotationTextAlignment(annotationPtr);
16034    const verticalAlign = this.getAnnotationVerticalAlignment(annotationPtr);
16035    const opacity = this.getAnnotationOpacity(annotationPtr);
16036    const richContent = this.getAnnotRichContent(annotationPtr);
16037    const rd = this.getRectangleDifferences(annotationPtr);
16038    return {
16039      pageIndex: page.index,
16040      id: index,
16041      type: PdfAnnotationSubtype.FREETEXT,
16042      rect,
16043      fontFamily: (da == null ? void 0 : da.fontFamily) ?? PdfStandardFont.Unknown,
16044      fontSize: (da == null ? void 0 : da.fontSize) ?? 12,
16045      fontColor: (da == null ? void 0 : da.fontColor) ?? "#000000",
16046      verticalAlign,
16047      color: bgColor,
16048      // fill color (matches shape convention)
16049      backgroundColor: bgColor,
16050      // deprecated alias
16051      opacity,
16052      textAlign,
16053      defaultStyle,
16054      richContent,
16055      ...rd.ok && {
16056        rectangleDifferences: {
16057          left: rd.left,
16058          top: rd.top,
16059          right: rd.right,
16060          bottom: rd.bottom
16061        }
16062      },
16063      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16064    };
16065  }
16066  /**
16067   * Read pdf link annotation from pdf document
16068   * @param page  - pdf page infor
16069   * @param docPtr - pointer to pdf document object
16070   * @param annotationPtr - pointer to pdf annotation
16071   * @param index  - index of annotation in the pdf page
16072   * @returns pdf link annotation
16073   *
16074   * @private
16075   */
16076  readPdfLinkAnno(doc, page, docPtr, annotationPtr, index) {
16077    const linkPtr = this.pdfiumModule.FPDFAnnot_GetLink(annotationPtr);
16078    if (!linkPtr) {
16079      return;
16080    }
16081    const annoRect = this.readPageAnnoRect(annotationPtr);
16082    const rect = this.convertPageRectToDeviceRect(doc, page, annoRect);
16083    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16084    const strokeColor = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.Color);
16085    let strokeDashArray;
16086    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16087      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16088      if (ok) {
16089        strokeDashArray = pattern;
16090      }
16091    }
16092    const target = this.readPdfLinkAnnoTarget(
16093      docPtr,
16094      () => {
16095        return this.pdfiumModule.FPDFLink_GetAction(linkPtr);
16096      },
16097      () => {
16098        return this.pdfiumModule.FPDFLink_GetDest(docPtr, linkPtr);
16099      }
16100    );
16101    return {
16102      pageIndex: page.index,
16103      id: index,
16104      type: PdfAnnotationSubtype.LINK,
16105      rect,
16106      target,
16107      strokeColor,
16108      strokeWidth,
16109      strokeStyle,
16110      strokeDashArray,
16111      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16112    };
16113  }
16114  /**
16115   * Read pdf widget annotation
16116   * @param page  - pdf page infor
16117   * @param annotationPtr - pointer to pdf annotation
16118   * @param formHandle - form handle
16119   * @param index  - index of annotation in the pdf page
16120   * @returns pdf widget annotation
16121   *
16122   * @private
16123   */
16124  readPdfWidgetAnno(doc, page, annotationPtr, formHandle, index) {
16125    const pageRect = this.readPageAnnoRect(annotationPtr);
16126    this.getAnnotationFlags(annotationPtr);
16127    const da = this.getAnnotationDefaultAppearance(annotationPtr);
16128    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16129    const field = this.readPdfWidgetAnnoField(formHandle, annotationPtr);
16130    const exportValue = this.readButtonExportValue(annotationPtr);
16131    const strokeColor = this.getMKColor(annotationPtr, 0);
16132    const color = this.getMKColor(annotationPtr, 1);
16133    const { width: strokeWidth } = this.getBorderStyle(annotationPtr);
16134    return {
16135      pageIndex: page.index,
16136      id: index,
16137      type: PdfAnnotationSubtype.WIDGET,
16138      fontFamily: (da == null ? void 0 : da.fontFamily) ?? PdfStandardFont.Unknown,
16139      fontSize: (da == null ? void 0 : da.fontSize) ?? 12,
16140      fontColor: (da == null ? void 0 : da.fontColor) ?? "#000000",
16141      rect,
16142      field,
16143      ...exportValue !== void 0 && { exportValue },
16144      strokeWidth,
16145      strokeColor: strokeColor ?? "transparent",
16146      color: color ?? "transparent",
16147      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16148    };
16149  }
16150  /**
16151   * Read pdf file attachment annotation
16152   * @param page  - pdf page infor
16153   * @param annotationPtr - pointer to pdf annotation
16154   * @param index  - index of annotation in the pdf page
16155   * @returns pdf file attachment annotation
16156   *
16157   * @private
16158   */
16159  readPdfFileAttachmentAnno(doc, page, annotationPtr, index) {
16160    const pageRect = this.readPageAnnoRect(annotationPtr);
16161    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16162    return {
16163      pageIndex: page.index,
16164      id: index,
16165      type: PdfAnnotationSubtype.FILEATTACHMENT,
16166      rect,
16167      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16168    };
16169  }
16170  /**
16171   * Read pdf ink annotation
16172   * @param page  - pdf page infor
16173   * @param annotationPtr - pointer to pdf annotation
16174   * @param index  - index of annotation in the pdf page
16175   * @returns pdf ink annotation
16176   *
16177   * @private
16178   */
16179  readPdfInkAnno(doc, page, annotationPtr, index) {
16180    const pageRect = this.readPageAnnoRect(annotationPtr);
16181    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16182    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";
16183    const opacity = this.getAnnotationOpacity(annotationPtr);
16184    const { width: strokeWidth } = this.getBorderStyle(annotationPtr);
16185    const inkList = this.getInkList(doc, page, annotationPtr);
16186    const intent = this.getAnnotIntent(annotationPtr);
16187    return {
16188      pageIndex: page.index,
16189      id: index,
16190      type: PdfAnnotationSubtype.INK,
16191      rect,
16192      ...intent && { intent },
16193      strokeColor,
16194      color: strokeColor,
16195      // deprecated alias
16196      opacity,
16197      strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,
16198      inkList,
16199      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16200    };
16201  }
16202  /**
16203   * Read pdf polygon annotation
16204   * @param page  - pdf page infor
16205   * @param annotationPtr - pointer to pdf annotation
16206   * @param index  - index of annotation in the pdf page
16207   * @returns pdf polygon annotation
16208   *
16209   * @private
16210   */
16211  readPdfPolygonAnno(doc, page, annotationPtr, index) {
16212    const pageRect = this.readPageAnnoRect(annotationPtr);
16213    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16214    const vertices = this.readPdfAnnoVertices(doc, page, annotationPtr);
16215    const strokeColor = this.getAnnotationColor(annotationPtr);
16216    const interiorColor = this.getAnnotationColor(
16217      annotationPtr,
16218      PdfAnnotationColorType.InteriorColor
16219    );
16220    const opacity = this.getAnnotationOpacity(annotationPtr);
16221    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16222    let strokeDashArray;
16223    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16224      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16225      if (ok) {
16226        strokeDashArray = pattern;
16227      }
16228    }
16229    if (vertices.length > 1) {
16230      const first = vertices[0];
16231      const last = vertices[vertices.length - 1];
16232      if (first.x === last.x && first.y === last.y) {
16233        vertices.pop();
16234      }
16235    }
16236    const rd = this.getRectangleDifferences(annotationPtr);
16237    const be = this.getBorderEffect(annotationPtr);
16238    return {
16239      pageIndex: page.index,
16240      id: index,
16241      type: PdfAnnotationSubtype.POLYGON,
16242      rect,
16243      strokeColor: strokeColor ?? "#FF0000",
16244      color: interiorColor ?? "transparent",
16245      opacity,
16246      strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,
16247      strokeStyle,
16248      strokeDashArray,
16249      vertices,
16250      ...be.ok && { cloudyBorderIntensity: be.intensity },
16251      ...rd.ok && {
16252        rectangleDifferences: {
16253          left: rd.left,
16254          top: rd.top,
16255          right: rd.right,
16256          bottom: rd.bottom
16257        }
16258      },
16259      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16260    };
16261  }
16262  /**
16263   * Read pdf polyline annotation
16264   * @param page  - pdf page infor
16265   * @param annotationPtr - pointer to pdf annotation
16266   * @param index  - index of annotation in the pdf page
16267   * @returns pdf polyline annotation
16268   *
16269   * @private
16270   */
16271  readPdfPolylineAnno(doc, page, annotationPtr, index) {
16272    const pageRect = this.readPageAnnoRect(annotationPtr);
16273    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16274    const vertices = this.readPdfAnnoVertices(doc, page, annotationPtr);
16275    const strokeColor = this.getAnnotationColor(annotationPtr);
16276    const interiorColor = this.getAnnotationColor(
16277      annotationPtr,
16278      PdfAnnotationColorType.InteriorColor
16279    );
16280    const opacity = this.getAnnotationOpacity(annotationPtr);
16281    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16282    let strokeDashArray;
16283    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16284      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16285      if (ok) {
16286        strokeDashArray = pattern;
16287      }
16288    }
16289    const lineEndings = this.getLineEndings(annotationPtr);
16290    return {
16291      pageIndex: page.index,
16292      id: index,
16293      type: PdfAnnotationSubtype.POLYLINE,
16294      rect,
16295      strokeColor: strokeColor ?? "#FF0000",
16296      color: interiorColor ?? "transparent",
16297      opacity,
16298      strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,
16299      strokeStyle,
16300      strokeDashArray,
16301      lineEndings,
16302      vertices,
16303      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16304    };
16305  }
16306  /**
16307   * Read pdf line annotation
16308   * @param page  - pdf page infor
16309   * @param annotationPtr - pointer to pdf annotation
16310   * @param index  - index of annotation in the pdf page
16311   * @returns pdf line annotation
16312   *
16313   * @private
16314   */
16315  readPdfLineAnno(doc, page, annotationPtr, index) {
16316    const pageRect = this.readPageAnnoRect(annotationPtr);
16317    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16318    const linePoints = this.getLinePoints(doc, page, annotationPtr);
16319    const lineEndings = this.getLineEndings(annotationPtr);
16320    const strokeColor = this.getAnnotationColor(annotationPtr);
16321    const interiorColor = this.getAnnotationColor(
16322      annotationPtr,
16323      PdfAnnotationColorType.InteriorColor
16324    );
16325    const opacity = this.getAnnotationOpacity(annotationPtr);
16326    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16327    let strokeDashArray;
16328    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16329      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16330      if (ok) {
16331        strokeDashArray = pattern;
16332      }
16333    }
16334    return {
16335      pageIndex: page.index,
16336      id: index,
16337      type: PdfAnnotationSubtype.LINE,
16338      rect,
16339      strokeWidth: strokeWidth === 0 ? 1 : strokeWidth,
16340      strokeStyle,
16341      strokeDashArray,
16342      strokeColor: strokeColor ?? "#FF0000",
16343      color: interiorColor ?? "transparent",
16344      opacity,
16345      linePoints: linePoints || { start: { x: 0, y: 0 }, end: { x: 0, y: 0 } },
16346      lineEndings: lineEndings || {
16347        start: PdfAnnotationLineEnding.None,
16348        end: PdfAnnotationLineEnding.None
16349      },
16350      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16351    };
16352  }
16353  /**
16354   * Read pdf highlight annotation
16355   * @param page  - pdf page infor
16356   * @param annotationPtr - pointer to pdf annotation
16357   * @param index  - index of annotation in the pdf page
16358   * @returns pdf highlight annotation
16359   *
16360   * @private
16361   */
16362  readPdfHighlightAnno(doc, page, annotationPtr, index) {
16363    const pageRect = this.readPageAnnoRect(annotationPtr);
16364    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16365    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16366    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FFFF00";
16367    const opacity = this.getAnnotationOpacity(annotationPtr);
16368    return {
16369      pageIndex: page.index,
16370      id: index,
16371      type: PdfAnnotationSubtype.HIGHLIGHT,
16372      rect,
16373      segmentRects,
16374      strokeColor,
16375      color: strokeColor,
16376      // deprecated alias
16377      opacity,
16378      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16379    };
16380  }
16381  /**
16382   * Read pdf underline annotation
16383   * @param page  - pdf page infor
16384   * @param annotationPtr - pointer to pdf annotation
16385   * @param index  - index of annotation in the pdf page
16386   * @returns pdf underline annotation
16387   *
16388   * @private
16389   */
16390  readPdfUnderlineAnno(doc, page, annotationPtr, index) {
16391    const pageRect = this.readPageAnnoRect(annotationPtr);
16392    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16393    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16394    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";
16395    const opacity = this.getAnnotationOpacity(annotationPtr);
16396    return {
16397      pageIndex: page.index,
16398      id: index,
16399      type: PdfAnnotationSubtype.UNDERLINE,
16400      rect,
16401      segmentRects,
16402      strokeColor,
16403      color: strokeColor,
16404      // deprecated alias
16405      opacity,
16406      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16407    };
16408  }
16409  /**
16410   * Read strikeout annotation
16411   * @param page  - pdf page infor
16412   * @param annotationPtr - pointer to pdf annotation
16413   * @param index  - index of annotation in the pdf page
16414   * @returns pdf strikeout annotation
16415   *
16416   * @private
16417   */
16418  readPdfStrikeOutAnno(doc, page, annotationPtr, index) {
16419    const pageRect = this.readPageAnnoRect(annotationPtr);
16420    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16421    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16422    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";
16423    const opacity = this.getAnnotationOpacity(annotationPtr);
16424    return {
16425      pageIndex: page.index,
16426      id: index,
16427      type: PdfAnnotationSubtype.STRIKEOUT,
16428      rect,
16429      segmentRects,
16430      strokeColor,
16431      color: strokeColor,
16432      // deprecated alias
16433      opacity,
16434      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16435    };
16436  }
16437  /**
16438   * Read pdf squiggly annotation
16439   * @param page  - pdf page infor
16440   * @param annotationPtr - pointer to pdf annotation
16441   * @param index  - index of annotation in the pdf page
16442   * @returns pdf squiggly annotation
16443   *
16444   * @private
16445   */
16446  readPdfSquigglyAnno(doc, page, annotationPtr, index) {
16447    const pageRect = this.readPageAnnoRect(annotationPtr);
16448    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16449    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16450    const strokeColor = this.getAnnotationColor(annotationPtr) ?? "#FF0000";
16451    const opacity = this.getAnnotationOpacity(annotationPtr);
16452    return {
16453      pageIndex: page.index,
16454      id: index,
16455      type: PdfAnnotationSubtype.SQUIGGLY,
16456      rect,
16457      segmentRects,
16458      strokeColor,
16459      color: strokeColor,
16460      // deprecated alias
16461      opacity,
16462      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16463    };
16464  }
16465  /**
16466   * Read pdf caret annotation
16467   * @param page  - pdf page infor
16468   * @param annotationPtr - pointer to pdf annotation
16469   * @param index  - index of annotation in the pdf page
16470   * @returns pdf caret annotation
16471   *
16472   * @private
16473   */
16474  readPdfCaretAnno(doc, page, annotationPtr, index) {
16475    const pageRect = this.readPageAnnoRect(annotationPtr);
16476    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16477    const strokeColor = this.getAnnotationColor(annotationPtr);
16478    const opacity = this.getAnnotationOpacity(annotationPtr);
16479    const intent = this.getAnnotIntent(annotationPtr);
16480    const rd = this.getRectangleDifferences(annotationPtr);
16481    return {
16482      pageIndex: page.index,
16483      id: index,
16484      type: PdfAnnotationSubtype.CARET,
16485      rect,
16486      strokeColor,
16487      opacity,
16488      intent,
16489      ...rd.ok && {
16490        rectangleDifferences: {
16491          left: rd.left,
16492          top: rd.top,
16493          right: rd.right,
16494          bottom: rd.bottom
16495        }
16496      },
16497      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16498    };
16499  }
16500  /**
16501   * Read pdf redact annotation
16502   * @param page  - pdf page info
16503   * @param annotationPtr - pointer to pdf annotation
16504   * @param index  - index of annotation in the pdf page
16505   * @returns pdf redact annotation
16506   *
16507   * @private
16508   */
16509  readPdfRedactAnno(doc, page, annotationPtr, index) {
16510    const pageRect = this.readPageAnnoRect(annotationPtr);
16511    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16512    const segmentRects = this.getQuadPointsAnno(doc, page, annotationPtr);
16513    const color = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.InteriorColor);
16514    const overlayColor = this.getAnnotationColor(
16515      annotationPtr,
16516      PdfAnnotationColorType.OverlayColor
16517    );
16518    const strokeColor = this.getAnnotationColor(annotationPtr, PdfAnnotationColorType.Color);
16519    const opacity = this.getAnnotationOpacity(annotationPtr);
16520    const overlayText = this.getOverlayText(annotationPtr);
16521    const overlayTextRepeat = this.getOverlayTextRepeat(annotationPtr);
16522    const da = this.getAnnotationDefaultAppearance(annotationPtr);
16523    const textAlign = this.getAnnotationTextAlignment(annotationPtr);
16524    return {
16525      pageIndex: page.index,
16526      id: index,
16527      type: PdfAnnotationSubtype.REDACT,
16528      rect,
16529      segmentRects,
16530      color,
16531      overlayColor,
16532      strokeColor,
16533      opacity,
16534      overlayText,
16535      overlayTextRepeat,
16536      fontFamily: da == null ? void 0 : da.fontFamily,
16537      fontSize: da == null ? void 0 : da.fontSize,
16538      fontColor: da == null ? void 0 : da.fontColor,
16539      textAlign,
16540      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16541    };
16542  }
16543  /**
16544   * Read pdf stamp annotation
16545   * @param page  - pdf page infor
16546   * @param annotationPtr - pointer to pdf annotation
16547   * @param index  - index of annotation in the pdf page
16548   * @returns pdf stamp annotation
16549   *
16550   * @private
16551   */
16552  readPdfStampAnno(doc, page, annotationPtr, index) {
16553    const pageRect = this.readPageAnnoRect(annotationPtr);
16554    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16555    const name = this.getAnnotationName(annotationPtr);
16556    return {
16557      pageIndex: page.index,
16558      id: index,
16559      type: PdfAnnotationSubtype.STAMP,
16560      rect,
16561      name,
16562      icon: name,
16563      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16564    };
16565  }
16566  /**
16567   * Read pdf object in pdf page
16568   * @param pageObjectPtr  - pointer to pdf object in page
16569   * @returns pdf object in page
16570   *
16571   * @private
16572   */
16573  readPdfPageObject(pageObjectPtr) {
16574    const type = this.pdfiumModule.FPDFPageObj_GetType(pageObjectPtr);
16575    switch (type) {
16576      case PdfPageObjectType.PATH:
16577        return this.readPathObject(pageObjectPtr);
16578      case PdfPageObjectType.IMAGE:
16579        return this.readImageObject(pageObjectPtr);
16580      case PdfPageObjectType.FORM:
16581        return this.readFormObject(pageObjectPtr);
16582    }
16583  }
16584  /**
16585   * Read pdf path object
16586   * @param pathObjectPtr  - pointer to pdf path object in page
16587   * @returns pdf path object
16588   *
16589   * @private
16590   */
16591  readPathObject(pathObjectPtr) {
16592    const segmentCount = this.pdfiumModule.FPDFPath_CountSegments(pathObjectPtr);
16593    const leftPtr = this.memoryManager.malloc(4);
16594    const bottomPtr = this.memoryManager.malloc(4);
16595    const rightPtr = this.memoryManager.malloc(4);
16596    const topPtr = this.memoryManager.malloc(4);
16597    this.pdfiumModule.FPDFPageObj_GetBounds(pathObjectPtr, leftPtr, bottomPtr, rightPtr, topPtr);
16598    const left = this.pdfiumModule.pdfium.getValue(leftPtr, "float");
16599    const bottom = this.pdfiumModule.pdfium.getValue(bottomPtr, "float");
16600    const right = this.pdfiumModule.pdfium.getValue(rightPtr, "float");
16601    const top = this.pdfiumModule.pdfium.getValue(topPtr, "float");
16602    const bounds = { left, bottom, right, top };
16603    this.memoryManager.free(leftPtr);
16604    this.memoryManager.free(bottomPtr);
16605    this.memoryManager.free(rightPtr);
16606    this.memoryManager.free(topPtr);
16607    const segments = [];
16608    for (let i = 0; i < segmentCount; i++) {
16609      const segment = this.readPdfSegment(pathObjectPtr, i);
16610      segments.push(segment);
16611    }
16612    const matrix = this.readPdfPageObjectTransformMatrix(pathObjectPtr);
16613    return {
16614      type: PdfPageObjectType.PATH,
16615      bounds,
16616      segments,
16617      matrix
16618    };
16619  }
16620  /**
16621   * Read segment of pdf path object
16622   * @param annotationObjectPtr - pointer to pdf path object
16623   * @param segmentIndex - index of segment
16624   * @returns pdf segment in pdf path
16625   *
16626   * @private
16627   */
16628  readPdfSegment(annotationObjectPtr, segmentIndex) {
16629    const segmentPtr = this.pdfiumModule.FPDFPath_GetPathSegment(annotationObjectPtr, segmentIndex);
16630    const segmentType = this.pdfiumModule.FPDFPathSegment_GetType(segmentPtr);
16631    const isClosed = this.pdfiumModule.FPDFPathSegment_GetClose(segmentPtr);
16632    const pointXPtr = this.memoryManager.malloc(4);
16633    const pointYPtr = this.memoryManager.malloc(4);
16634    this.pdfiumModule.FPDFPathSegment_GetPoint(segmentPtr, pointXPtr, pointYPtr);
16635    const pointX = this.pdfiumModule.pdfium.getValue(pointXPtr, "float");
16636    const pointY = this.pdfiumModule.pdfium.getValue(pointYPtr, "float");
16637    this.memoryManager.free(pointXPtr);
16638    this.memoryManager.free(pointYPtr);
16639    return {
16640      type: segmentType,
16641      point: { x: pointX, y: pointY },
16642      isClosed
16643    };
16644  }
16645  /**
16646   * Read pdf image object from pdf document
16647   * @param pageObjectPtr  - pointer to pdf image object in page
16648   * @returns pdf image object
16649   *
16650   * @private
16651   */
16652  readImageObject(imageObjectPtr) {
16653    const bitmapPtr = this.pdfiumModule.FPDFImageObj_GetBitmap(imageObjectPtr);
16654    const bitmapBufferPtr = this.pdfiumModule.FPDFBitmap_GetBuffer(bitmapPtr);
16655    const bitmapWidth = this.pdfiumModule.FPDFBitmap_GetWidth(bitmapPtr);
16656    const bitmapHeight = this.pdfiumModule.FPDFBitmap_GetHeight(bitmapPtr);
16657    const format = this.pdfiumModule.FPDFBitmap_GetFormat(bitmapPtr);
16658    const pixelCount = bitmapWidth * bitmapHeight;
16659    const bytesPerPixel = 4;
16660    const array = new Uint8ClampedArray(pixelCount * bytesPerPixel);
16661    for (let i = 0; i < pixelCount; i++) {
16662      switch (format) {
16663        case 2:
16664          {
16665            const blue = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3, "i8");
16666            const green = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3 + 1, "i8");
16667            const red = this.pdfiumModule.pdfium.getValue(bitmapBufferPtr + i * 3 + 2, "i8");
16668            array[i * bytesPerPixel] = red;
16669            array[i * bytesPerPixel + 1] = green;
16670            array[i * bytesPerPixel + 2] = blue;
16671            array[i * bytesPerPixel + 3] = 100;
16672          }
16673          break;
16674      }
16675    }
16676    const imageDataLike = {
16677      data: array,
16678      width: bitmapWidth,
16679      height: bitmapHeight
16680    };
16681    const matrix = this.readPdfPageObjectTransformMatrix(imageObjectPtr);
16682    return {
16683      type: PdfPageObjectType.IMAGE,
16684      imageData: imageDataLike,
16685      matrix
16686    };
16687  }
16688  /**
16689   * Read form object from pdf document
16690   * @param formObjectPtr  - pointer to pdf form object in page
16691   * @returns pdf form object
16692   *
16693   * @private
16694   */
16695  readFormObject(formObjectPtr) {
16696    const objectCount = this.pdfiumModule.FPDFFormObj_CountObjects(formObjectPtr);
16697    const objects = [];
16698    for (let i = 0; i < objectCount; i++) {
16699      const pageObjectPtr = this.pdfiumModule.FPDFFormObj_GetObject(formObjectPtr, i);
16700      const pageObj = this.readPdfPageObject(pageObjectPtr);
16701      if (pageObj) {
16702        objects.push(pageObj);
16703      }
16704    }
16705    const matrix = this.readPdfPageObjectTransformMatrix(formObjectPtr);
16706    return {
16707      type: PdfPageObjectType.FORM,
16708      objects,
16709      matrix
16710    };
16711  }
16712  /**
16713   * Read pdf object in pdf page
16714   * @param pageObjectPtr  - pointer to pdf object in page
16715   * @returns pdf object in page
16716   *
16717   * @private
16718   */
16719  readPdfPageObjectTransformMatrix(pageObjectPtr) {
16720    const matrixPtr = this.memoryManager.malloc(4 * 6);
16721    if (this.pdfiumModule.FPDFPageObj_GetMatrix(pageObjectPtr, matrixPtr)) {
16722      const a = this.pdfiumModule.pdfium.getValue(matrixPtr, "float");
16723      const b = this.pdfiumModule.pdfium.getValue(matrixPtr + 4, "float");
16724      const c = this.pdfiumModule.pdfium.getValue(matrixPtr + 8, "float");
16725      const d = this.pdfiumModule.pdfium.getValue(matrixPtr + 12, "float");
16726      const e = this.pdfiumModule.pdfium.getValue(matrixPtr + 16, "float");
16727      const f = this.pdfiumModule.pdfium.getValue(matrixPtr + 20, "float");
16728      this.memoryManager.free(matrixPtr);
16729      return { a, b, c, d, e, f };
16730    }
16731    this.memoryManager.free(matrixPtr);
16732    return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
16733  }
16734  /**
16735   * Read contents of a stamp annotation
16736   * @param annotationPtr - pointer to pdf annotation
16737   * @returns contents of the stamp annotation
16738   *
16739   * @private
16740   */
16741  readStampAnnotationContents(annotationPtr) {
16742    const contents = [];
16743    const objectCount = this.pdfiumModule.FPDFAnnot_GetObjectCount(annotationPtr);
16744    for (let i = 0; i < objectCount; i++) {
16745      const annotationObjectPtr = this.pdfiumModule.FPDFAnnot_GetObject(annotationPtr, i);
16746      const pageObj = this.readPdfPageObject(annotationObjectPtr);
16747      if (pageObj) {
16748        contents.push(pageObj);
16749      }
16750    }
16751    return contents;
16752  }
16753  /**
16754   * Return the stroke-width declared in the annotation’s /Border or /BS entry.
16755   * Falls back to 1 pt when nothing is defined.
16756   *
16757   * @param annotationPtr - pointer to pdf annotation
16758   * @returns stroke-width
16759   *
16760   * @private
16761   */
16762  getStrokeWidth(annotationPtr) {
16763    const hPtr = this.memoryManager.malloc(4);
16764    const vPtr = this.memoryManager.malloc(4);
16765    const wPtr = this.memoryManager.malloc(4);
16766    const ok = this.pdfiumModule.FPDFAnnot_GetBorder(annotationPtr, hPtr, vPtr, wPtr);
16767    const width = ok ? this.pdfiumModule.pdfium.getValue(wPtr, "float") : 1;
16768    this.memoryManager.free(hPtr);
16769    this.memoryManager.free(vPtr);
16770    this.memoryManager.free(wPtr);
16771    return width;
16772  }
16773  /**
16774   * Fetches the \`/F\` flag bit-field from an annotation.
16775   *
16776   * @param annotationPtr pointer to an \`FPDF_ANNOTATION\`
16777   * @returns \`{ raw, flags }\`
16778   *          • \`raw\`   – the 32-bit integer returned by PDFium
16779   *          • \`flags\` – object with individual booleans
16780   */
16781  getAnnotationFlags(annotationPtr) {
16782    const rawFlags = this.pdfiumModule.FPDFAnnot_GetFlags(annotationPtr);
16783    return flagsToNames(rawFlags);
16784  }
16785  setAnnotationFlags(annotationPtr, flags) {
16786    const rawFlags = namesToFlags(flags);
16787    return this.pdfiumModule.FPDFAnnot_SetFlags(annotationPtr, rawFlags);
16788  }
16789  /**
16790   * Read circle annotation
16791   * @param page  - pdf page infor
16792   * @param annotationPtr - pointer to pdf annotation
16793   * @param index  - index of annotation in the pdf page
16794   * @returns pdf circle annotation
16795   *
16796   * @private
16797   */
16798  readPdfCircleAnno(doc, page, annotationPtr, index) {
16799    const pageRect = this.readPageAnnoRect(annotationPtr);
16800    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16801    const interiorColor = this.getAnnotationColor(
16802      annotationPtr,
16803      PdfAnnotationColorType.InteriorColor
16804    );
16805    const strokeColor = this.getAnnotationColor(annotationPtr);
16806    const opacity = this.getAnnotationOpacity(annotationPtr);
16807    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16808    let strokeDashArray;
16809    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16810      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16811      if (ok) {
16812        strokeDashArray = pattern;
16813      }
16814    }
16815    const rd = this.getRectangleDifferences(annotationPtr);
16816    const be = this.getBorderEffect(annotationPtr);
16817    return {
16818      pageIndex: page.index,
16819      id: index,
16820      type: PdfAnnotationSubtype.CIRCLE,
16821      rect,
16822      color: interiorColor ?? "transparent",
16823      opacity,
16824      strokeWidth,
16825      strokeColor: strokeColor ?? "#FF0000",
16826      strokeStyle,
16827      ...strokeDashArray !== void 0 && { strokeDashArray },
16828      ...be.ok && { cloudyBorderIntensity: be.intensity },
16829      ...rd.ok && {
16830        rectangleDifferences: {
16831          left: rd.left,
16832          top: rd.top,
16833          right: rd.right,
16834          bottom: rd.bottom
16835        }
16836      },
16837      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16838    };
16839  }
16840  /**
16841   * Read square annotation
16842   * @param page  - pdf page infor
16843   * @param annotationPtr - pointer to pdf annotation
16844   * @param index  - index of annotation in the pdf page
16845   * @returns pdf square annotation
16846   *
16847   * @private
16848   */
16849  readPdfSquareAnno(doc, page, annotationPtr, index) {
16850    const pageRect = this.readPageAnnoRect(annotationPtr);
16851    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16852    const interiorColor = this.getAnnotationColor(
16853      annotationPtr,
16854      PdfAnnotationColorType.InteriorColor
16855    );
16856    const strokeColor = this.getAnnotationColor(annotationPtr);
16857    const opacity = this.getAnnotationOpacity(annotationPtr);
16858    const { style: strokeStyle, width: strokeWidth } = this.getBorderStyle(annotationPtr);
16859    let strokeDashArray;
16860    if (strokeStyle === PdfAnnotationBorderStyle.DASHED) {
16861      const { ok, pattern } = this.getBorderDashPattern(annotationPtr);
16862      if (ok) {
16863        strokeDashArray = pattern;
16864      }
16865    }
16866    const rd = this.getRectangleDifferences(annotationPtr);
16867    const be = this.getBorderEffect(annotationPtr);
16868    return {
16869      pageIndex: page.index,
16870      id: index,
16871      type: PdfAnnotationSubtype.SQUARE,
16872      rect,
16873      color: interiorColor ?? "transparent",
16874      opacity,
16875      strokeColor: strokeColor ?? "#FF0000",
16876      strokeWidth,
16877      strokeStyle,
16878      ...strokeDashArray !== void 0 && { strokeDashArray },
16879      ...be.ok && { cloudyBorderIntensity: be.intensity },
16880      ...rd.ok && {
16881        rectangleDifferences: {
16882          left: rd.left,
16883          top: rd.top,
16884          right: rd.right,
16885          bottom: rd.bottom
16886        }
16887      },
16888      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16889    };
16890  }
16891  /**
16892   * Read basic info of unsupported pdf annotation
16893   * @param page  - pdf page infor
16894   * @param type - type of annotation
16895   * @param annotationPtr - pointer to pdf annotation
16896   * @param index  - index of annotation in the pdf page
16897   * @returns pdf annotation
16898   *
16899   * @private
16900   */
16901  readPdfAnno(doc, page, type, annotationPtr, index) {
16902    const pageRect = this.readPageAnnoRect(annotationPtr);
16903    const rect = this.convertPageRectToDeviceRect(doc, page, pageRect);
16904    return {
16905      pageIndex: page.index,
16906      id: index,
16907      type,
16908      rect,
16909      ...this.readBaseAnnotationProperties(doc, page, annotationPtr)
16910    };
16911  }
16912  /**
16913   * Resolve \`/IRT\` → parent-annotation index on the same page.
16914   *
16915   * @param pagePtr        - pointer to FPDF_PAGE
16916   * @param annotationPtr  - pointer to FPDF_ANNOTATION
16917   * @returns index (\`0…count-1\`) or \`undefined\` when the annotation is *not* a reply
16918   *
16919   * @private
16920   */
16921  getInReplyToId(annotationPtr) {
16922    const parentPtr = this.pdfiumModule.FPDFAnnot_GetLinkedAnnot(annotationPtr, "IRT");
16923    if (!parentPtr) return;
16924    let nm = this.getAnnotString(parentPtr, "NM");
16925    if (!nm || !isUuidV4(nm)) {
16926      nm = uuidV4();
16927      this.setAnnotString(parentPtr, "NM", nm);
16928    }
16929    this.pdfiumModule.FPDFPage_CloseAnnot(parentPtr);
16930    return nm;
16931  }
16932  /**
16933   * Set the in reply to id of the annotation
16934   *
16935   * @param annotationPtr - pointer to an \`FPDF_ANNOTATION\`
16936   * @param id - the id of the parent annotation
16937   * @returns \`true\` on success
16938   */
16939  setInReplyToId(pagePtr, annotationPtr, id) {
16940    if (!id) {
16941      return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(annotationPtr, "IRT", 0);
16942    }
16943    const parentPtr = this.getAnnotationByName(pagePtr, id);
16944    if (!parentPtr) return false;
16945    return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(annotationPtr, "IRT", parentPtr);
16946  }
16947  /**
16948   * Rotate a point around a center by the given angle in degrees.
16949   * Used to rotate vertices for PDF storage.
16950   */
16951  rotatePointForSave(point, center, angleDegrees) {
16952    const rad = angleDegrees * Math.PI / 180;
16953    const cos = Math.cos(rad);
16954    const sin = Math.sin(rad);
16955    const dx = point.x - center.x;
16956    const dy = point.y - center.y;
16957    return {
16958      x: center.x + dx * cos - dy * sin,
16959      y: center.y + dx * sin + dy * cos
16960    };
16961  }
16962  /**
16963   * Prepare an annotation for saving to PDF.
16964   * For vertex types (ink, line, polygon, polyline) with rotation,
16965   * physically rotates the vertices by +rotation so that other PDF viewers
16966   * see the correct visual result. Our viewer reverse-rotates on load.
16967   */
16968  prepareAnnotationForSave(annotation) {
16969    const rotation = annotation.rotation;
16970    const unrotatedRect = annotation.unrotatedRect;
16971    if (!rotation || rotation === 0 || !unrotatedRect) {
16972      return annotation;
16973    }
16974    const center = {
16975      x: unrotatedRect.origin.x + unrotatedRect.size.width / 2,
16976      y: unrotatedRect.origin.y + unrotatedRect.size.height / 2
16977    };
16978    switch (annotation.type) {
16979      case PdfAnnotationSubtype.INK: {
16980        const ink = annotation;
16981        const rotatedInkList = ink.inkList.map((stroke) => ({
16982          points: stroke.points.map((p) => this.rotatePointForSave(p, center, rotation))
16983        }));
16984        return { ...ink, inkList: rotatedInkList };
16985      }
16986      case PdfAnnotationSubtype.LINE: {
16987        const line = annotation;
16988        return {
16989          ...line,
16990          linePoints: {
16991            start: this.rotatePointForSave(line.linePoints.start, center, rotation),
16992            end: this.rotatePointForSave(line.linePoints.end, center, rotation)
16993          }
16994        };
16995      }
16996      case PdfAnnotationSubtype.POLYGON: {
16997        const poly = annotation;
16998        return {
16999          ...poly,
17000          vertices: poly.vertices.map((v) => this.rotatePointForSave(v, center, rotation))
17001        };
17002      }
17003      case PdfAnnotationSubtype.POLYLINE: {
17004        const polyline = annotation;
17005        return {
17006          ...polyline,
17007          vertices: polyline.vertices.map((v) => this.rotatePointForSave(v, center, rotation))
17008        };
17009      }
17010      default:
17011        return annotation;
17012    }
17013  }
17014  /**
17015   * Apply all base annotation properties from PdfAnnotationObjectBase.
17016   * The setInReplyToId and setReplyType functions handle clearing when undefined.
17017   *
17018   * @param pagePtr - pointer to page object
17019   * @param annotationPtr - pointer to annotation object
17020   * @param annotation - the annotation object containing properties to apply
17021   * @returns \`true\` on success
17022   */
17023  applyBaseAnnotationProperties(doc, page, pagePtr, annotationPtr, annotation) {
17024    if (!this.setAnnotString(annotationPtr, "T", annotation.author || "")) {
17025      return false;
17026    }
17027    if (!this.setAnnotString(annotationPtr, "Contents", annotation.contents ?? "")) {
17028      return false;
17029    }
17030    if (annotation.subject && !this.setAnnotString(annotationPtr, "Subj", annotation.subject)) {
17031      return false;
17032    }
17033    if (annotation.modified) {
17034      if (!this.setAnnotationDate(annotationPtr, "M", annotation.modified)) {
17035        return false;
17036      }
17037    }
17038    if (annotation.created) {
17039      if (!this.setAnnotationDate(annotationPtr, "CreationDate", annotation.created)) {
17040        return false;
17041      }
17042    }
17043    if (annotation.flags) {
17044      if (!this.setAnnotationFlags(annotationPtr, annotation.flags)) {
17045        return false;
17046      }
17047    }
17048    const existingCustom = this.getAnnotCustom(annotationPtr) ?? {};
17049    const customData = {
17050      ...existingCustom,
17051      ...annotation.custom ?? {}
17052    };
17053    delete customData.unrotatedRect;
17054    delete customData.rotation;
17055    const hasCustomData = Object.keys(customData).length > 0;
17056    if (hasCustomData) {
17057      if (!this.setAnnotCustom(annotationPtr, customData)) {
17058        return false;
17059      }
17060    } else if (Object.keys(existingCustom).length > 0) {
17061      if (!this.setAnnotCustom(annotationPtr, null)) {
17062        return false;
17063      }
17064    }
17065    if (annotation.rotation !== void 0) {
17066      const pdfRotation = annotation.rotation ? (360 - annotation.rotation) % 360 : 0;
17067      this.setAnnotExtendedRotation(annotationPtr, pdfRotation);
17068    }
17069    if (annotation.unrotatedRect) {
17070      this.setAnnotUnrotatedRect(doc, page, annotationPtr, annotation.unrotatedRect);
17071    } else if (annotation.rotation && annotation.rotation !== 0) {
17072      this.setAnnotUnrotatedRect(doc, page, annotationPtr, annotation.rect);
17073    }
17074    if (!this.setInReplyToId(pagePtr, annotationPtr, annotation.inReplyToId)) {
17075      return false;
17076    }
17077    if (!this.setReplyType(annotationPtr, annotation.replyType)) {
17078      return false;
17079    }
17080    return true;
17081  }
17082  /**
17083   * Read all base annotation properties from PdfAnnotationObjectBase.
17084   * Returns an object that can be spread into the annotation return value.
17085   *
17086   * @param doc - pdf document object
17087   * @param page - pdf page object
17088   * @param annotationPtr - pointer to annotation object
17089   * @returns object with base annotation properties
17090   */
17091  readBaseAnnotationProperties(doc, page, annotationPtr) {
17092    const author = this.getAnnotString(annotationPtr, "T");
17093    const contents = this.getAnnotString(annotationPtr, "Contents") || "";
17094    const modified = this.getAnnotationDate(annotationPtr, "M");
17095    const created = this.getAnnotationDate(annotationPtr, "CreationDate");
17096    const subject = this.getAnnotString(annotationPtr, "Subj");
17097    const flags = this.getAnnotationFlags(annotationPtr);
17098    const custom = this.getAnnotCustom(annotationPtr);
17099    const inReplyToId = this.getInReplyToId(annotationPtr);
17100    const replyType = this.getReplyType(annotationPtr);
17101    const blendMode = this.pdfiumModule.EPDFAnnot_GetBlendMode(annotationPtr);
17102    const pdfRotation = this.getAnnotExtendedRotation(annotationPtr);
17103    const rotation = pdfRotation !== 0 ? (360 - pdfRotation) % 360 : 0;
17104    const rawUnrotatedRect = this.readAnnotUnrotatedRect(annotationPtr);
17105    const unrotatedRect = rawUnrotatedRect ? this.convertPageRectToDeviceRect(doc, page, rawUnrotatedRect) : void 0;
17106    return {
17107      author,
17108      contents,
17109      modified,
17110      created,
17111      flags,
17112      custom,
17113      blendMode,
17114      ...subject && { subject },
17115      // Only include IRT if present
17116      ...inReplyToId && { inReplyToId },
17117      // Only include RT if present and not the default (Reply)
17118      ...replyType && replyType !== PdfAnnotationReplyType.Reply && { replyType },
17119      ...rotation !== 0 && { rotation },
17120      ...unrotatedRect !== void 0 && { unrotatedRect }
17121    };
17122  }
17123  /**
17124   * Fetch a string value (\`/T\`, \`/M\`, \`/State\`, …) from an annotation.
17125   *
17126   * @returns decoded UTF-8 string or \`undefined\` when the key is absent
17127   *
17128   * @private
17129   */
17130  getAnnotString(annotationPtr, key) {
17131    const len = this.pdfiumModule.FPDFAnnot_GetStringValue(annotationPtr, key, 0, 0);
17132    if (len === 0) return;
17133    const bytes = (len + 1) * 2;
17134    const ptr = this.memoryManager.malloc(bytes);
17135    this.pdfiumModule.FPDFAnnot_GetStringValue(annotationPtr, key, ptr, bytes);
17136    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17137    this.memoryManager.free(ptr);
17138    return value || void 0;
17139  }
17140  readButtonExportValue(annotationPtr) {
17141    const len = this.pdfiumModule.EPDFAnnot_GetButtonExportValue(annotationPtr, 0, 0);
17142    if (len === 0) return;
17143    const bytes = (len + 1) * 2;
17144    const ptr = this.memoryManager.malloc(bytes);
17145    this.pdfiumModule.EPDFAnnot_GetButtonExportValue(annotationPtr, ptr, bytes);
17146    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17147    this.memoryManager.free(ptr);
17148    return value || void 0;
17149  }
17150  /**
17151   * Get a string value (\`/T\`, \`/M\`, \`/State\`, …) from an attachment.
17152   *
17153   * @returns decoded UTF-8 string or \`undefined\` when the key is absent
17154   *
17155   * @private
17156   */
17157  getAttachmentString(attachmentPtr, key) {
17158    const len = this.pdfiumModule.FPDFAttachment_GetStringValue(attachmentPtr, key, 0, 0);
17159    if (len === 0) return;
17160    const bytes = (len + 1) * 2;
17161    const ptr = this.memoryManager.malloc(bytes);
17162    this.pdfiumModule.FPDFAttachment_GetStringValue(attachmentPtr, key, ptr, bytes);
17163    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17164    this.memoryManager.free(ptr);
17165    return value || void 0;
17166  }
17167  /**
17168   * Get a number value (\`/Size\`) from an attachment.
17169   *
17170   * @returns number or \`null\` when the key is absent
17171   *
17172   * @private
17173   */
17174  getAttachmentNumber(attachmentPtr, key) {
17175    const outPtr = this.memoryManager.malloc(4);
17176    try {
17177      const ok = this.pdfiumModule.EPDFAttachment_GetIntegerValue(
17178        attachmentPtr,
17179        key,
17180        // FPDF_BYTESTRING → ASCII JS string is fine in your glue
17181        outPtr
17182      );
17183      if (!ok) return void 0;
17184      return this.pdfiumModule.pdfium.getValue(outPtr, "i32") >>> 0;
17185    } finally {
17186      this.memoryManager.free(outPtr);
17187    }
17188  }
17189  /**
17190   * Get custom data of the annotation
17191   * @param annotationPtr - pointer to pdf annotation
17192   * @returns custom data of the annotation
17193   *
17194   * @private
17195   */
17196  getAnnotCustom(annotationPtr) {
17197    const custom = this.getAnnotString(annotationPtr, "EPDFCustom");
17198    if (!custom) return;
17199    try {
17200      return JSON.parse(custom);
17201    } catch (error) {
17202      console.warn("Failed to parse annotation custom data as JSON:", error);
17203      console.warn("Invalid JSON string:", custom);
17204      return void 0;
17205    }
17206  }
17207  /**
17208   * Sets custom data for an annotation by safely stringifying and storing JSON
17209   * @private
17210   */
17211  setAnnotCustom(annotationPtr, data) {
17212    if (data === void 0 || data === null) {
17213      return this.setAnnotString(annotationPtr, "EPDFCustom", "");
17214    }
17215    try {
17216      const jsonString = JSON.stringify(data);
17217      return this.setAnnotString(annotationPtr, "EPDFCustom", jsonString);
17218    } catch (error) {
17219      console.warn("Failed to stringify annotation custom data as JSON:", error);
17220      console.warn("Invalid data object:", data);
17221      return false;
17222    }
17223  }
17224  /**
17225   * Fetches the /IT (Intent) name from an annotation as a UTF-8 JS string.
17226   *
17227   * Mirrors getAnnotString(): calls EPDFAnnot_GetIntent twice (length probe + copy).
17228   * Returns \`undefined\` if no intent present.
17229   */
17230  getAnnotIntent(annotationPtr) {
17231    const len = this.pdfiumModule.EPDFAnnot_GetIntent(annotationPtr, 0, 0);
17232    if (len === 0) return;
17233    const codeUnits = len + 1;
17234    const bytes = codeUnits * 2;
17235    const ptr = this.memoryManager.malloc(bytes);
17236    this.pdfiumModule.EPDFAnnot_GetIntent(annotationPtr, ptr, bytes);
17237    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17238    this.memoryManager.free(ptr);
17239    return value && value !== "undefined" ? value : void 0;
17240  }
17241  /**
17242   * Write the \`/IT\` (Intent) name into an annotation dictionary.
17243   *
17244   * Mirrors EPDFAnnot_SetIntent in PDFium (expects a UTF‑8 FPDF_BYTESTRING).
17245   *
17246   * @param annotationPtr Pointer returned by FPDFPage_GetAnnot
17247   * @param intent        Name without leading slash, e.g. \`"PolygonCloud"\`
17248   *                      A leading “/” will be stripped for convenience.
17249   * @returns             true on success, false otherwise
17250   */
17251  setAnnotIntent(annotationPtr, intent) {
17252    return this.pdfiumModule.EPDFAnnot_SetIntent(annotationPtr, intent);
17253  }
17254  /**
17255   * Returns the rich‑content string stored in the annotation’s \`/RC\` entry.
17256   *
17257   * Works like \`getAnnotIntent()\`: first probe for length, then copy.
17258   * \`undefined\` when the annotation has no rich content.
17259   */
17260  getAnnotRichContent(annotationPtr) {
17261    const len = this.pdfiumModule.EPDFAnnot_GetRichContent(annotationPtr, 0, 0);
17262    if (len === 0) return;
17263    const codeUnits = len + 1;
17264    const bytes = codeUnits * 2;
17265    const ptr = this.memoryManager.malloc(bytes);
17266    this.pdfiumModule.EPDFAnnot_GetRichContent(annotationPtr, ptr, bytes);
17267    const value = this.pdfiumModule.pdfium.UTF16ToString(ptr);
17268    this.memoryManager.free(ptr);
17269    return value || void 0;
17270  }
17271  /**
17272   * Get annotation by name
17273   * @param pagePtr - pointer to pdf page object
17274   * @param name - name of annotation
17275   * @returns pointer to pdf annotation
17276   *
17277   * @private
17278   */
17279  getAnnotationByName(pagePtr, name) {
17280    return this.withWString(name, (wNamePtr) => {
17281      return this.pdfiumModule.EPDFPage_GetAnnotByName(pagePtr, wNamePtr);
17282    });
17283  }
17284  /**
17285   * Remove annotation by name
17286   * @param pagePtr - pointer to pdf page object
17287   * @param name - name of annotation
17288   * @returns true on success
17289   *
17290   * @private
17291   */
17292  removeAnnotationByName(pagePtr, name) {
17293    return this.withWString(name, (wNamePtr) => {
17294      return this.pdfiumModule.EPDFPage_RemoveAnnotByName(pagePtr, wNamePtr);
17295    });
17296  }
17297  /**
17298   * Set a string value (\`/T\`, \`/M\`, \`/State\`, …) to an annotation.
17299   *
17300   * @returns \`true\` if the operation was successful
17301   *
17302   * @private
17303   */
17304  setAnnotString(annotationPtr, key, value) {
17305    return this.withWString(value, (wValPtr) => {
17306      return this.pdfiumModule.FPDFAnnot_SetStringValue(annotationPtr, key, wValPtr);
17307    });
17308  }
17309  /**
17310   * Set a string value (\`/T\`, \`/M\`, \`/State\`, …) to an attachment.
17311   *
17312   * @returns \`true\` if the operation was successful
17313   *
17314   * @private
17315   */
17316  setAttachmentString(attachmentPtr, key, value) {
17317    return this.withWString(value, (wValPtr) => {
17318      return this.pdfiumModule.FPDFAttachment_SetStringValue(attachmentPtr, key, wValPtr);
17319    });
17320  }
17321  /**
17322   * Read vertices of pdf annotation
17323   * @param doc - pdf document object
17324   * @param page  - pdf page infor
17325   * @param annotationPtr - pointer to pdf annotation
17326   * @returns vertices of pdf annotation
17327   *
17328   * @private
17329   */
17330  readPdfAnnoVertices(doc, page, annotationPtr) {
17331    const vertices = [];
17332    const count = this.pdfiumModule.FPDFAnnot_GetVertices(annotationPtr, 0, 0);
17333    const pointMemorySize = 8;
17334    const pointsPtr = this.memoryManager.malloc(count * pointMemorySize);
17335    this.pdfiumModule.FPDFAnnot_GetVertices(annotationPtr, pointsPtr, count);
17336    for (let i = 0; i < count; i++) {
17337      const pointX = this.pdfiumModule.pdfium.getValue(pointsPtr + i * pointMemorySize, "float");
17338      const pointY = this.pdfiumModule.pdfium.getValue(
17339        pointsPtr + i * pointMemorySize + 4,
17340        "float"
17341      );
17342      const { x, y } = this.convertPagePointToDevicePoint(doc, page, {
17343        x: pointX,
17344        y: pointY
17345      });
17346      const last = vertices[vertices.length - 1];
17347      if (!last || last.x !== x || last.y !== y) {
17348        vertices.push({ x, y });
17349      }
17350    }
17351    this.memoryManager.free(pointsPtr);
17352    return vertices;
17353  }
17354  /**
17355   * Sync the vertices of a polygon or polyline annotation.
17356   *
17357   * @param doc - pdf document object
17358   * @param page  - pdf page infor
17359   * @param annotPtr - pointer to pdf annotation
17360   * @param vertices - the vertices to be set
17361   * @returns true on success
17362   *
17363   * @private
17364   */
17365  setPdfAnnoVertices(doc, page, annotPtr, vertices) {
17366    const pdf = this.pdfiumModule.pdfium;
17367    const FS_POINTF_SIZE = 8;
17368    const buf = this.memoryManager.malloc(FS_POINTF_SIZE * vertices.length);
17369    vertices.forEach((v, i) => {
17370      const pagePt = this.convertDevicePointToPagePoint(doc, page, v);
17371      pdf.setValue(buf + i * FS_POINTF_SIZE + 0, pagePt.x, "float");
17372      pdf.setValue(buf + i * FS_POINTF_SIZE + 4, pagePt.y, "float");
17373    });
17374    const ok = this.pdfiumModule.EPDFAnnot_SetVertices(annotPtr, buf, vertices.length);
17375    this.memoryManager.free(buf);
17376    return ok;
17377  }
17378  /**
17379   * Read the target of pdf bookmark
17380   * @param docPtr - pointer to pdf document object
17381   * @param getActionPtr - callback function to retrive the pointer of action
17382   * @param getDestinationPtr - callback function to retrive the pointer of destination
17383   * @returns target of pdf bookmark
17384   *
17385   * @private
17386   */
17387  readPdfBookmarkTarget(docPtr, getActionPtr, getDestinationPtr) {
17388    const actionPtr = getActionPtr();
17389    if (actionPtr) {
17390      const action = this.readPdfAction(docPtr, actionPtr);
17391      return {
17392        type: "action",
17393        action
17394      };
17395    } else {
17396      const destinationPtr = getDestinationPtr();
17397      if (destinationPtr) {
17398        const destination = this.readPdfDestination(docPtr, destinationPtr);
17399        return {
17400          type: "destination",
17401          destination
17402        };
17403      }
17404    }
17405  }
17406  /**
17407   * Read field of pdf widget annotation
17408   * @param formHandle - form handle
17409   * @param annotationPtr - pointer to pdf annotation
17410   * @returns field of pdf widget annotation
17411   *
17412   * @private
17413   */
17414  readPdfWidgetAnnoField(formHandle, annotationPtr) {
17415    const flag = this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(
17416      formHandle,
17417      annotationPtr
17418    );
17419    const type = this.pdfiumModule.FPDFAnnot_GetFormFieldType(
17420      formHandle,
17421      annotationPtr
17422    );
17423    const name = readString(
17424      this.pdfiumModule.pdfium,
17425      (buffer, bufferLength) => {
17426        return this.pdfiumModule.FPDFAnnot_GetFormFieldName(
17427          formHandle,
17428          annotationPtr,
17429          buffer,
17430          bufferLength
17431        );
17432      },
17433      this.pdfiumModule.pdfium.UTF16ToString
17434    );
17435    const alternateName = readString(
17436      this.pdfiumModule.pdfium,
17437      (buffer, bufferLength) => {
17438        return this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(
17439          formHandle,
17440          annotationPtr,
17441          buffer,
17442          bufferLength
17443        );
17444      },
17445      this.pdfiumModule.pdfium.UTF16ToString
17446    );
17447    const value = readString(
17448      this.pdfiumModule.pdfium,
17449      (buffer, bufferLength) => {
17450        return this.pdfiumModule.EPDFAnnot_GetFormFieldRawValue(
17451          formHandle,
17452          annotationPtr,
17453          buffer,
17454          bufferLength
17455        );
17456      },
17457      this.pdfiumModule.pdfium.UTF16ToString
17458    );
17459    const fieldObjectId = this.pdfiumModule.EPDFAnnot_GetFormFieldObjectNumber(
17460      formHandle,
17461      annotationPtr
17462    );
17463    const base = {
17464      flag,
17465      name,
17466      alternateName,
17467      value,
17468      fieldObjectId: fieldObjectId > 0 ? fieldObjectId : void 0
17469    };
17470    switch (type) {
17471      case PDF_FORM_FIELD_TYPE.TEXTFIELD: {
17472        let maxLen;
17473        const floatPtr = this.memoryManager.malloc(4);
17474        const ok = this.pdfiumModule.FPDFAnnot_GetNumberValue(annotationPtr, "MaxLen", floatPtr);
17475        if (ok) {
17476          maxLen = this.pdfiumModule.pdfium.getValue(floatPtr, "float");
17477        }
17478        this.memoryManager.free(floatPtr);
17479        return { ...base, type, maxLen };
17480      }
17481      case PDF_FORM_FIELD_TYPE.CHECKBOX:
17482        return { ...base, type };
17483      case PDF_FORM_FIELD_TYPE.RADIOBUTTON:
17484        return {
17485          ...base,
17486          type,
17487          options: this.readWidgetOptions(formHandle, annotationPtr)
17488        };
17489      case PDF_FORM_FIELD_TYPE.COMBOBOX:
17490        return { ...base, type, options: this.readWidgetOptions(formHandle, annotationPtr) };
17491      case PDF_FORM_FIELD_TYPE.LISTBOX:
17492        return { ...base, type, options: this.readWidgetOptions(formHandle, annotationPtr) };
17493      case PDF_FORM_FIELD_TYPE.PUSHBUTTON:
17494        return { ...base, type };
17495      case PDF_FORM_FIELD_TYPE.SIGNATURE:
17496        return { ...base, type };
17497      default:
17498        return { ...base, type };
17499    }
17500  }
17501  readWidgetOptions(formHandle, annotationPtr) {
17502    const options = [];
17503    const count = this.pdfiumModule.FPDFAnnot_GetOptionCount(formHandle, annotationPtr);
17504    for (let i = 0; i < count; i++) {
17505      const label = readString(
17506        this.pdfiumModule.pdfium,
17507        (buffer, bufferLength) => {
17508          return this.pdfiumModule.FPDFAnnot_GetOptionLabel(
17509            formHandle,
17510            annotationPtr,
17511            i,
17512            buffer,
17513            bufferLength
17514          );
17515        },
17516        this.pdfiumModule.pdfium.UTF16ToString
17517      );
17518      const isSelected = this.pdfiumModule.FPDFAnnot_IsOptionSelected(formHandle, annotationPtr, i);
17519      options.push({ label, isSelected });
17520    }
17521    return options;
17522  }
17523  /**
17524   * {@inheritDoc @embedpdf/models!PdfEngine.renderAnnotation}
17525   *
17526   * @public
17527   */
17528  renderPageAnnotationRaw(doc, page, annotation, options) {
17529    const {
17530      scaleFactor = 1,
17531      rotation = Rotation.Degree0,
17532      dpr = 1,
17533      mode = AppearanceMode.Normal
17534    } = options ?? {};
17535    this.logger.debug(
17536      LOG_SOURCE$1,
17537      LOG_CATEGORY$1,
17538      "renderPageAnnotation",
17539      doc,
17540      page,
17541      annotation,
17542      options
17543    );
17544    this.logger.perf(
17545      LOG_SOURCE$1,
17546      LOG_CATEGORY$1,
17547      \`RenderPageAnnotation\`,
17548      "Begin",
17549      \`\${doc.id}-\${page.index}-\${annotation.id}\`
17550    );
17551    const task = new Task();
17552    const ctx = this.cache.getContext(doc.id);
17553    if (!ctx) {
17554      this.logger.perf(
17555        LOG_SOURCE$1,
17556        LOG_CATEGORY$1,
17557        \`RenderPageAnnotation\`,
17558        "End",
17559        \`\${doc.id}-\${page.index}-\${annotation.id}\`
17560      );
17561      return PdfTaskHelper.reject({
17562        code: PdfErrorCode.DocNotOpen,
17563        message: "document does not open"
17564      });
17565    }
17566    const pageCtx = ctx.acquirePage(page.index);
17567    const annotPtr = this.getAnnotationByName(pageCtx.pagePtr, annotation.id);
17568    if (!annotPtr) {
17569      this.logger.perf(
17570        LOG_SOURCE$1,
17571        LOG_CATEGORY$1,
17572        \`RenderPageAnnotation\`,
17573        "End",
17574        \`\${doc.id}-\${page.index}-\${annotation.id}\`
17575      );
17576      pageCtx.release();
17577      return PdfTaskHelper.reject({ code: PdfErrorCode.NotFound, message: "annotation not found" });
17578    }
17579    let hasAP = !!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(annotPtr, mode);
17580    if (!hasAP && annotation.type === PdfAnnotationSubtype.WIDGET) {
17581      if (!this.pdfiumModule.FPDFAnnot_HasKey(annotPtr, "AP")) {
17582        this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotPtr);
17583        hasAP = !!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(annotPtr, mode);
17584      }
17585    }
17586    if (!hasAP) {
17587      this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
17588      pageCtx.release();
17589      this.logger.perf(
17590        LOG_SOURCE$1,
17591        LOG_CATEGORY$1,
17592        \`RenderPageAnnotation\`,
17593        "End",
17594        \`\${doc.id}-\${page.index}-\${annotation.id}\`
17595      );
17596      task.resolve({ data: new Uint8ClampedArray(4), width: 1, height: 1 });
17597      return task;
17598    }
17599    const finalScale = Math.max(0.01, scaleFactor * dpr);
17600    const unrotated = !!(options == null ? void 0 : options.unrotated) && !!annotation.unrotatedRect;
17601    const renderRect = unrotated ? annotation.unrotatedRect : annotation.rect;
17602    const devRect = toIntRect(transformRect(page.size, renderRect, rotation, finalScale));
17603    const wDev = Math.max(1, devRect.size.width);
17604    const hDev = Math.max(1, devRect.size.height);
17605    const stride = wDev * 4;
17606    const bytes = stride * hDev;
17607    const heapPtr = this.memoryManager.malloc(bytes);
17608    const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(
17609      wDev,
17610      hDev,
17611      4,
17612      heapPtr,
17613      stride
17614    );
17615    this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, 0);
17616    const M = buildUserToDeviceMatrix(renderRect, rotation, wDev, hDev);
17617    const mPtr = this.memoryManager.malloc(6 * 4);
17618    const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);
17619    mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);
17620    const FLAGS = 16;
17621    let ok = false;
17622    try {
17623      if (unrotated) {
17624        ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmapUnrotated(
17625          bitmapPtr,
17626          pageCtx.pagePtr,
17627          annotPtr,
17628          mode,
17629          mPtr,
17630          FLAGS
17631        );
17632      } else {
17633        ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmap(
17634          bitmapPtr,
17635          pageCtx.pagePtr,
17636          annotPtr,
17637          mode,
17638          mPtr,
17639          FLAGS
17640        );
17641      }
17642    } finally {
17643      this.memoryManager.free(mPtr);
17644      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
17645      this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
17646      pageCtx.release();
17647    }
17648    if (!ok) {
17649      this.memoryManager.free(heapPtr);
17650      this.logger.perf(
17651        LOG_SOURCE$1,
17652        LOG_CATEGORY$1,
17653        \`RenderPageAnnotation\`,
17654        "End",
17655        \`\${doc.id}-\${page.index}-\${annotation.id}\`
17656      );
17657      return PdfTaskHelper.reject({
17658        code: PdfErrorCode.Unknown,
17659        message: "EPDF_RenderAnnotBitmap failed"
17660      });
17661    }
17662    const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);
17663    const imageDataLike = {
17664      data: new Uint8ClampedArray(data),
17665      width: wDev,
17666      height: hDev
17667    };
17668    task.resolve(imageDataLike);
17669    this.memoryManager.free(heapPtr);
17670    return task;
17671  }
17672  /**
17673   * Batch-render all annotation appearance streams for a page in one call.
17674   * Returns a map of annotation ID -> rendered appearances (Normal/Rollover/Down).
17675   * Skips annotations that have rotation + unrotatedRect (EmbedPDF-rotated)
17676   * and annotations without any appearance stream.
17677   *
17678   * @public
17679   */
17680  renderPageAnnotationsRaw(doc, page, options) {
17681    const { scaleFactor = 1, rotation = Rotation.Degree0, dpr = 1 } = options ?? {};
17682    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "renderPageAnnotationsRaw", doc, page, options);
17683    this.logger.perf(
17684      LOG_SOURCE$1,
17685      LOG_CATEGORY$1,
17686      "RenderPageAnnotationsRaw",
17687      "Begin",
17688      \`\${doc.id}-\${page.index}\`
17689    );
17690    const ctx = this.cache.getContext(doc.id);
17691    if (!ctx) {
17692      this.logger.perf(
17693        LOG_SOURCE$1,
17694        LOG_CATEGORY$1,
17695        "RenderPageAnnotationsRaw",
17696        "End",
17697        \`\${doc.id}-\${page.index}\`
17698      );
17699      return PdfTaskHelper.reject({
17700        code: PdfErrorCode.DocNotOpen,
17701        message: "document does not open"
17702      });
17703    }
17704    const pageCtx = ctx.acquirePage(page.index);
17705    const result = {};
17706    const finalScale = Math.max(0.01, scaleFactor * dpr);
17707    const annotCount = this.pdfiumModule.FPDFPage_GetAnnotCount(pageCtx.pagePtr);
17708    for (let i = 0; i < annotCount; i++) {
17709      const annotPtr = this.pdfiumModule.FPDFPage_GetAnnot(pageCtx.pagePtr, i);
17710      if (!annotPtr) continue;
17711      try {
17712        const nm = this.getAnnotString(annotPtr, "NM");
17713        if (!nm) continue;
17714        const extRotation = this.getAnnotExtendedRotation(annotPtr);
17715        if (extRotation !== 0) {
17716          const unrotatedRaw = this.readAnnotUnrotatedRect(annotPtr);
17717          if (unrotatedRaw) continue;
17718        }
17719        const apModes = this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(annotPtr);
17720        if (!apModes) continue;
17721        const appearances = {};
17722        const modesToRender = [
17723          { bit: AP_MODE_NORMAL, mode: AppearanceMode.Normal, key: "normal" },
17724          { bit: AP_MODE_ROLLOVER, mode: AppearanceMode.Rollover, key: "rollover" },
17725          { bit: AP_MODE_DOWN, mode: AppearanceMode.Down, key: "down" }
17726        ];
17727        for (const { bit, mode, key } of modesToRender) {
17728          if (!(apModes & bit)) continue;
17729          const rendered = this.renderSingleAnnotAppearance(
17730            doc,
17731            page,
17732            pageCtx,
17733            annotPtr,
17734            mode,
17735            rotation,
17736            finalScale
17737          );
17738          if (rendered) {
17739            appearances[key] = rendered;
17740          }
17741        }
17742        if (appearances.normal || appearances.rollover || appearances.down) {
17743          result[nm] = appearances;
17744        }
17745      } finally {
17746        this.pdfiumModule.FPDFPage_CloseAnnot(annotPtr);
17747      }
17748    }
17749    pageCtx.release();
17750    this.logger.perf(
17751      LOG_SOURCE$1,
17752      LOG_CATEGORY$1,
17753      "RenderPageAnnotationsRaw",
17754      "End",
17755      \`\${doc.id}-\${page.index}\`
17756    );
17757    const task = new Task();
17758    task.resolve(result);
17759    return task;
17760  }
17761  /**
17762   * Render a single annotation's appearance for a given mode.
17763   * Returns the image data and rect, or null on failure.
17764   * @private
17765   */
17766  renderSingleAnnotAppearance(doc, page, pageCtx, annotPtr, mode, rotation, finalScale) {
17767    if (!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(annotPtr, mode)) {
17768      const subtype = this.pdfiumModule.FPDFAnnot_GetSubtype(annotPtr);
17769      if (subtype === PdfAnnotationSubtype.WIDGET && !this.pdfiumModule.FPDFAnnot_HasKey(annotPtr, "AP")) {
17770        this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(annotPtr);
17771        if (!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(annotPtr, mode)) {
17772          return null;
17773        }
17774      } else {
17775        return null;
17776      }
17777    }
17778    const pageRect = this.readPageAnnoRect(annotPtr);
17779    const annotRect = this.convertPageRectToDeviceRect(doc, page, pageRect);
17780    const devRect = toIntRect(transformRect(page.size, annotRect, rotation, finalScale));
17781    const wDev = Math.max(1, devRect.size.width);
17782    const hDev = Math.max(1, devRect.size.height);
17783    const stride = wDev * 4;
17784    const bytes = stride * hDev;
17785    const heapPtr = this.memoryManager.malloc(bytes);
17786    const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(
17787      wDev,
17788      hDev,
17789      4,
17790      heapPtr,
17791      stride
17792    );
17793    this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, 0);
17794    const M = buildUserToDeviceMatrix(annotRect, rotation, wDev, hDev);
17795    const mPtr = this.memoryManager.malloc(6 * 4);
17796    const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);
17797    mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);
17798    const FLAGS = 16;
17799    let ok = false;
17800    try {
17801      ok = !!this.pdfiumModule.EPDF_RenderAnnotBitmap(
17802        bitmapPtr,
17803        pageCtx.pagePtr,
17804        annotPtr,
17805        mode,
17806        mPtr,
17807        FLAGS
17808      );
17809    } finally {
17810      this.memoryManager.free(mPtr);
17811      this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
17812    }
17813    if (!ok) {
17814      this.memoryManager.free(heapPtr);
17815      return null;
17816    }
17817    const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);
17818    const imageData = {
17819      data: new Uint8ClampedArray(data),
17820      width: wDev,
17821      height: hDev
17822    };
17823    this.memoryManager.free(heapPtr);
17824    return { data: imageData, rect: annotRect };
17825  }
17826  renderRectEncoded(doc, page, rect, options) {
17827    const task = new Task();
17828    const rotation = (options == null ? void 0 : options.rotation) ?? Rotation.Degree0;
17829    const ctx = this.cache.getContext(doc.id);
17830    if (!ctx) {
17831      return PdfTaskHelper.reject({
17832        code: PdfErrorCode.DocNotOpen,
17833        message: "document does not open"
17834      });
17835    }
17836    const scale = Math.max(0.01, (options == null ? void 0 : options.scaleFactor) ?? 1);
17837    const dpr = Math.max(1, (options == null ? void 0 : options.dpr) ?? 1);
17838    const finalScale = scale * dpr;
17839    const baseW = rect.size.width;
17840    const baseH = rect.size.height;
17841    const swap2 = (rotation & 1) === 1;
17842    const wDev = Math.max(1, Math.round((swap2 ? baseH : baseW) * finalScale));
17843    const hDev = Math.max(1, Math.round((swap2 ? baseW : baseH) * finalScale));
17844    const stride = wDev * 4;
17845    const bytes = stride * hDev;
17846    const pageCtx = ctx.acquirePage(page.index);
17847    const shouldRenderForms = (options == null ? void 0 : options.withForms) ?? false;
17848    const heapPtr = this.memoryManager.malloc(bytes);
17849    const bitmapPtr = this.pdfiumModule.FPDFBitmap_CreateEx(
17850      wDev,
17851      hDev,
17852      4,
17853      heapPtr,
17854      stride
17855    );
17856    const bgColor = (options == null ? void 0 : options.transparentBackground) ? 0 : 4294967295;
17857    this.pdfiumModule.FPDFBitmap_FillRect(bitmapPtr, 0, 0, wDev, hDev, bgColor);
17858    const M = buildUserToDeviceMatrix(rect, rotation, wDev, hDev);
17859    const mPtr = this.memoryManager.malloc(6 * 4);
17860    const mView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, mPtr, 6);
17861    mView.set([M.a, M.b, M.c, M.d, M.e, M.f]);
17862    const clipPtr = this.memoryManager.malloc(4 * 4);
17863    const clipView = new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer, clipPtr, 4);
17864    clipView.set([0, 0, wDev, hDev]);
17865    let flags = 16;
17866    if ((options == null ? void 0 : options.withAnnotations) ?? false) flags |= 1;
17867    try {
17868      this.pdfiumModule.FPDF_RenderPageBitmapWithMatrix(
17869        bitmapPtr,
17870        pageCtx.pagePtr,
17871        mPtr,
17872        clipPtr,
17873        flags
17874      );
17875      if (shouldRenderForms) {
17876        pageCtx.withFormHandle((formHandle) => {
17877          const formParams = computeFormDrawParams(M, rect, page.size, rotation);
17878          const { startX, startY, formsWidth, formsHeight } = formParams;
17879          this.pdfiumModule.FPDF_FFLDraw(
17880            formHandle,
17881            bitmapPtr,
17882            pageCtx.pagePtr,
17883            startX,
17884            startY,
17885            formsWidth,
17886            formsHeight,
17887            rotation,
17888            flags
17889          );
17890        });
17891      }
17892    } finally {
17893      pageCtx.release();
17894      this.memoryManager.free(mPtr);
17895      this.memoryManager.free(clipPtr);
17896    }
17897    this.logger.perf(
17898      LOG_SOURCE$1,
17899      LOG_CATEGORY$1,
17900      \`RenderRectEncodedData\`,
17901      "Begin",
17902      \`\${doc.id}-\${page.index}\`
17903    );
17904    const data = this.pdfiumModule.pdfium.HEAPU8.subarray(heapPtr, heapPtr + bytes);
17905    this.logger.perf(
17906      LOG_SOURCE$1,
17907      LOG_CATEGORY$1,
17908      \`RenderRectEncodedData\`,
17909      "End",
17910      \`\${doc.id}-\${page.index}\`
17911    );
17912    this.logger.perf(
17913      LOG_SOURCE$1,
17914      LOG_CATEGORY$1,
17915      \`RenderRectEncodedImageData\`,
17916      "Begin",
17917      \`\${doc.id}-\${page.index}\`
17918    );
17919    const imageDataLike = {
17920      data: new Uint8ClampedArray(data),
17921      width: wDev,
17922      height: hDev
17923    };
17924    this.logger.perf(
17925      LOG_SOURCE$1,
17926      LOG_CATEGORY$1,
17927      \`RenderRectEncodedImageData\`,
17928      "End",
17929      \`\${doc.id}-\${page.index}\`
17930    );
17931    task.resolve(imageDataLike);
17932    this.pdfiumModule.FPDFBitmap_Destroy(bitmapPtr);
17933    this.memoryManager.free(heapPtr);
17934    return task;
17935  }
17936  /**
17937   * Read the target of pdf link annotation
17938   * @param docPtr - pointer to pdf document object
17939   * @param getActionPtr - callback function to retrive the pointer of action
17940   * @param getDestinationPtr - callback function to retrive the pointer of destination
17941   * @returns target of link
17942   *
17943   * @private
17944   */
17945  readPdfLinkAnnoTarget(docPtr, getActionPtr, getDestinationPtr) {
17946    const destinationPtr = getDestinationPtr();
17947    if (destinationPtr) {
17948      const destination = this.readPdfDestination(docPtr, destinationPtr);
17949      return {
17950        type: "destination",
17951        destination
17952      };
17953    } else {
17954      const actionPtr = getActionPtr();
17955      if (actionPtr) {
17956        const action = this.readPdfAction(docPtr, actionPtr);
17957        return {
17958          type: "action",
17959          action
17960        };
17961      }
17962    }
17963  }
17964  createLocalDestPtr(docPtr, dest) {
17965    var _a, _b;
17966    const pagePtr = this.pdfiumModule.FPDF_LoadPage(docPtr, dest.pageIndex);
17967    if (!pagePtr) return 0;
17968    try {
17969      if (dest.zoom.mode === PdfZoomMode.XYZ) {
17970        const { x, y, zoom } = dest.zoom.params;
17971        return this.pdfiumModule.EPDFDest_CreateXYZ(
17972          pagePtr,
17973          /*has_left*/
17974          true,
17975          x,
17976          /*has_top*/
17977          true,
17978          y,
17979          /*has_zoom*/
17980          true,
17981          zoom
17982        );
17983      }
17984      let viewEnum;
17985      let params = [];
17986      switch (dest.zoom.mode) {
17987        case PdfZoomMode.FitPage:
17988          viewEnum = PdfZoomMode.FitPage;
17989          break;
17990        case PdfZoomMode.FitHorizontal:
17991          viewEnum = PdfZoomMode.FitHorizontal;
17992          params = [((_a = dest.view) == null ? void 0 : _a[0]) ?? 0];
17993          break;
17994        case PdfZoomMode.FitVertical:
17995          viewEnum = PdfZoomMode.FitVertical;
17996          params = [((_b = dest.view) == null ? void 0 : _b[0]) ?? 0];
17997          break;
17998        case PdfZoomMode.FitRectangle:
17999          {
18000            const v = dest.view ?? [];
18001            params = [v[0] ?? 0, v[1] ?? 0, v[2] ?? 0, v[3] ?? 0];
18002            viewEnum = PdfZoomMode.FitRectangle;
18003          }
18004          break;
18005        case PdfZoomMode.Unknown:
18006        default:
18007          return 0;
18008      }
18009      return this.withFloatArray(
18010        params,
18011        (ptr, count) => this.pdfiumModule.EPDFDest_CreateView(pagePtr, viewEnum, ptr, count)
18012      );
18013    } finally {
18014      this.pdfiumModule.FPDF_ClosePage(pagePtr);
18015    }
18016  }
18017  applyBookmarkTarget(docPtr, bmPtr, target) {
18018    if (target.type === "destination") {
18019      const destPtr = this.createLocalDestPtr(docPtr, target.destination);
18020      if (!destPtr) return false;
18021      const ok = this.pdfiumModule.EPDFBookmark_SetDest(docPtr, bmPtr, destPtr);
18022      return !!ok;
18023    }
18024    const action = target.action;
18025    switch (action.type) {
18026      case PdfActionType.Goto: {
18027        const destPtr = this.createLocalDestPtr(docPtr, action.destination);
18028        if (!destPtr) return false;
18029        const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);
18030        if (!actPtr) return false;
18031        return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);
18032      }
18033      case PdfActionType.URI: {
18034        const actPtr = this.pdfiumModule.EPDFAction_CreateURI(docPtr, action.uri);
18035        if (!actPtr) return false;
18036        return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);
18037      }
18038      case PdfActionType.LaunchAppOrOpenFile: {
18039        const actPtr = this.withWString(
18040          action.path,
18041          (wptr) => this.pdfiumModule.EPDFAction_CreateLaunch(docPtr, wptr)
18042        );
18043        if (!actPtr) return false;
18044        return !!this.pdfiumModule.EPDFBookmark_SetAction(docPtr, bmPtr, actPtr);
18045      }
18046      case PdfActionType.RemoteGoto:
18047        return false;
18048      case PdfActionType.Unsupported:
18049      default:
18050        return false;
18051    }
18052  }
18053  /**
18054   * Apply a link target (action or destination) to a link annotation
18055   * @param docPtr - pointer to pdf document
18056   * @param annotationPtr - pointer to the link annotation
18057   * @param target - the link target to apply
18058   * @returns true if successful
18059   *
18060   * @private
18061   */
18062  applyLinkTarget(docPtr, annotationPtr, target) {
18063    if (target.type === "destination") {
18064      const destPtr = this.createLocalDestPtr(docPtr, target.destination);
18065      if (!destPtr) return false;
18066      const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);
18067      if (!actPtr) return false;
18068      return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);
18069    }
18070    const action = target.action;
18071    switch (action.type) {
18072      case PdfActionType.Goto: {
18073        const destPtr = this.createLocalDestPtr(docPtr, action.destination);
18074        if (!destPtr) return false;
18075        const actPtr = this.pdfiumModule.EPDFAction_CreateGoTo(docPtr, destPtr);
18076        if (!actPtr) return false;
18077        return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);
18078      }
18079      case PdfActionType.URI: {
18080        const actPtr = this.pdfiumModule.EPDFAction_CreateURI(docPtr, action.uri);
18081        if (!actPtr) return false;
18082        return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);
18083      }
18084      case PdfActionType.LaunchAppOrOpenFile: {
18085        const actPtr = this.withWString(
18086          action.path,
18087          (wptr) => this.pdfiumModule.EPDFAction_CreateLaunch(docPtr, wptr)
18088        );
18089        if (!actPtr) return false;
18090        return !!this.pdfiumModule.EPDFAnnot_SetAction(annotationPtr, actPtr);
18091      }
18092      case PdfActionType.RemoteGoto:
18093      case PdfActionType.Unsupported:
18094      default:
18095        return false;
18096    }
18097  }
18098  /**
18099   * Read pdf action from pdf document
18100   * @param docPtr - pointer to pdf document object
18101   * @param actionPtr - pointer to pdf action object
18102   * @returns pdf action object
18103   *
18104   * @private
18105   */
18106  readPdfAction(docPtr, actionPtr) {
18107    const actionType = this.pdfiumModule.FPDFAction_GetType(actionPtr);
18108    let action;
18109    switch (actionType) {
18110      case PdfActionType.Unsupported:
18111        action = {
18112          type: PdfActionType.Unsupported
18113        };
18114        break;
18115      case PdfActionType.Goto:
18116        {
18117          const destinationPtr = this.pdfiumModule.FPDFAction_GetDest(docPtr, actionPtr);
18118          if (destinationPtr) {
18119            const destination = this.readPdfDestination(docPtr, destinationPtr);
18120            action = {
18121              type: PdfActionType.Goto,
18122              destination
18123            };
18124          } else {
18125            action = {
18126              type: PdfActionType.Unsupported
18127            };
18128          }
18129        }
18130        break;
18131      case PdfActionType.RemoteGoto:
18132        {
18133          action = {
18134            type: PdfActionType.Unsupported
18135          };
18136        }
18137        break;
18138      case PdfActionType.URI:
18139        {
18140          const uri = readString(
18141            this.pdfiumModule.pdfium,
18142            (buffer, bufferLength) => {
18143              return this.pdfiumModule.FPDFAction_GetURIPath(
18144                docPtr,
18145                actionPtr,
18146                buffer,
18147                bufferLength
18148              );
18149            },
18150            this.pdfiumModule.pdfium.UTF8ToString
18151          );
18152          action = {
18153            type: PdfActionType.URI,
18154            uri
18155          };
18156        }
18157        break;
18158      case PdfActionType.LaunchAppOrOpenFile:
18159        {
18160          const path = readString(
18161            this.pdfiumModule.pdfium,
18162            (buffer, bufferLength) => {
18163              return this.pdfiumModule.FPDFAction_GetFilePath(actionPtr, buffer, bufferLength);
18164            },
18165            this.pdfiumModule.pdfium.UTF8ToString
18166          );
18167          action = {
18168            type: PdfActionType.LaunchAppOrOpenFile,
18169            path
18170          };
18171        }
18172        break;
18173    }
18174    return action;
18175  }
18176  /**
18177   * Read pdf destination object
18178   * @param docPtr - pointer to pdf document object
18179   * @param destinationPtr - pointer to pdf destination
18180   * @returns pdf destination object
18181   *
18182   * @private
18183   */
18184  readPdfDestination(docPtr, destinationPtr) {
18185    const pageIndex = this.pdfiumModule.FPDFDest_GetDestPageIndex(docPtr, destinationPtr);
18186    const maxParmamsCount = 4;
18187    const paramsCountPtr = this.memoryManager.malloc(maxParmamsCount);
18188    const paramsPtr = this.memoryManager.malloc(maxParmamsCount * 4);
18189    const zoomMode = this.pdfiumModule.FPDFDest_GetView(
18190      destinationPtr,
18191      paramsCountPtr,
18192      paramsPtr
18193    );
18194    const paramsCount = this.pdfiumModule.pdfium.getValue(paramsCountPtr, "i32");
18195    const view = [];
18196    for (let i = 0; i < paramsCount; i++) {
18197      const paramPtr = paramsPtr + i * 4;
18198      view.push(this.pdfiumModule.pdfium.getValue(paramPtr, "float"));
18199    }
18200    this.memoryManager.free(paramsCountPtr);
18201    this.memoryManager.free(paramsPtr);
18202    if (zoomMode === PdfZoomMode.XYZ) {
18203      const hasXPtr = this.memoryManager.malloc(1);
18204      const hasYPtr = this.memoryManager.malloc(1);
18205      const hasZPtr = this.memoryManager.malloc(1);
18206      const xPtr = this.memoryManager.malloc(4);
18207      const yPtr = this.memoryManager.malloc(4);
18208      const zPtr = this.memoryManager.malloc(4);
18209      const isSucceed = this.pdfiumModule.FPDFDest_GetLocationInPage(
18210        destinationPtr,
18211        hasXPtr,
18212        hasYPtr,
18213        hasZPtr,
18214        xPtr,
18215        yPtr,
18216        zPtr
18217      );
18218      if (isSucceed) {
18219        const hasX = this.pdfiumModule.pdfium.getValue(hasXPtr, "i8");
18220        const hasY = this.pdfiumModule.pdfium.getValue(hasYPtr, "i8");
18221        const hasZ = this.pdfiumModule.pdfium.getValue(hasZPtr, "i8");
18222        const x = hasX ? this.pdfiumModule.pdfium.getValue(xPtr, "float") : 0;
18223        const y = hasY ? this.pdfiumModule.pdfium.getValue(yPtr, "float") : 0;
18224        const zoom = hasZ ? this.pdfiumModule.pdfium.getValue(zPtr, "float") : 0;
18225        this.memoryManager.free(hasXPtr);
18226        this.memoryManager.free(hasYPtr);
18227        this.memoryManager.free(hasZPtr);
18228        this.memoryManager.free(xPtr);
18229        this.memoryManager.free(yPtr);
18230        this.memoryManager.free(zPtr);
18231        return {
18232          pageIndex,
18233          zoom: {
18234            mode: zoomMode,
18235            params: {
18236              x,
18237              y,
18238              zoom
18239            }
18240          },
18241          view
18242        };
18243      }
18244      this.memoryManager.free(hasXPtr);
18245      this.memoryManager.free(hasYPtr);
18246      this.memoryManager.free(hasZPtr);
18247      this.memoryManager.free(xPtr);
18248      this.memoryManager.free(yPtr);
18249      this.memoryManager.free(zPtr);
18250      return {
18251        pageIndex,
18252        zoom: {
18253          mode: zoomMode,
18254          params: {
18255            x: 0,
18256            y: 0,
18257            zoom: 0
18258          }
18259        },
18260        view
18261      };
18262    }
18263    return {
18264      pageIndex,
18265      zoom: {
18266        mode: zoomMode
18267      },
18268      view
18269    };
18270  }
18271  /**
18272   * Read attachmet from pdf document
18273   * @param docPtr - pointer to pdf document object
18274   * @param index - index of attachment
18275   * @returns attachment content
18276   *
18277   * @private
18278   */
18279  readPdfAttachment(docPtr, index) {
18280    const attachmentPtr = this.pdfiumModule.FPDFDoc_GetAttachment(docPtr, index);
18281    const name = readString(
18282      this.pdfiumModule.pdfium,
18283      (buffer, bufferLength) => {
18284        return this.pdfiumModule.FPDFAttachment_GetName(attachmentPtr, buffer, bufferLength);
18285      },
18286      this.pdfiumModule.pdfium.UTF16ToString
18287    );
18288    const description = readString(
18289      this.pdfiumModule.pdfium,
18290      (buffer, bufferLength) => {
18291        return this.pdfiumModule.EPDFAttachment_GetDescription(attachmentPtr, buffer, bufferLength);
18292      },
18293      this.pdfiumModule.pdfium.UTF16ToString
18294    );
18295    const mimeType = readString(
18296      this.pdfiumModule.pdfium,
18297      (buffer, bufferLength) => {
18298        return this.pdfiumModule.FPDFAttachment_GetSubtype(attachmentPtr, buffer, bufferLength);
18299      },
18300      this.pdfiumModule.pdfium.UTF16ToString
18301    );
18302    const creationDate = this.getAttachmentDate(attachmentPtr, "CreationDate");
18303    const checksum = readString(
18304      this.pdfiumModule.pdfium,
18305      (buffer, bufferLength) => {
18306        return this.pdfiumModule.FPDFAttachment_GetStringValue(
18307          attachmentPtr,
18308          "Checksum",
18309          buffer,
18310          bufferLength
18311        );
18312      },
18313      this.pdfiumModule.pdfium.UTF16ToString
18314    );
18315    const size = this.getAttachmentNumber(attachmentPtr, "Size");
18316    return {
18317      index,
18318      name,
18319      description,
18320      mimeType,
18321      size,
18322      creationDate,
18323      checksum
18324    };
18325  }
18326  /**
18327   * Convert coordinate of point from device coordinate to page coordinate
18328   * @param doc - pdf document object
18329   * @param page  - pdf page infor
18330   * @param position - position of point
18331   * @returns converted position
18332   *
18333   * @private
18334   */
18335  convertDevicePointToPagePoint(doc, page, position) {
18336    const DW = page.size.width;
18337    const DH = page.size.height;
18338    const r = doc.normalizedRotation ? 0 : page.rotation & 3;
18339    if (r === 0) {
18340      return { x: position.x, y: DH - position.y };
18341    }
18342    if (r === 1) {
18343      return { x: position.y, y: position.x };
18344    }
18345    if (r === 2) {
18346      return { x: DW - position.x, y: position.y };
18347    }
18348    {
18349      return { x: DH - position.y, y: DW - position.x };
18350    }
18351  }
18352  /**
18353   * Convert coordinate of point from page coordinate to device coordinate
18354   * @param doc - pdf document object
18355   * @param page  - pdf page infor
18356   * @param position - position of point
18357   * @returns converted position
18358   *
18359   * @private
18360   */
18361  convertPagePointToDevicePoint(doc, page, position) {
18362    const DW = page.size.width;
18363    const DH = page.size.height;
18364    const r = doc.normalizedRotation ? 0 : page.rotation & 3;
18365    if (r === 0) {
18366      return { x: position.x, y: DH - position.y };
18367    }
18368    if (r === 1) {
18369      return { x: position.y, y: position.x };
18370    }
18371    if (r === 2) {
18372      return { x: DW - position.x, y: position.y };
18373    }
18374    {
18375      return { x: DW - position.y, y: DH - position.x };
18376    }
18377  }
18378  /**
18379   * Convert coordinate of rectangle from page coordinate to device coordinate
18380   * @param doc - pdf document object
18381   * @param page  - pdf page infor
18382   * @param pagePtr - pointer to pdf page object
18383   * @param pageRect - rectangle that needs to be converted
18384   * @returns converted rectangle
18385   *
18386   * @private
18387   */
18388  convertPageRectToDeviceRect(doc, page, pageRect) {
18389    const { x, y } = this.convertPagePointToDevicePoint(doc, page, {
18390      x: pageRect.left,
18391      y: pageRect.top
18392    });
18393    const rect = {
18394      origin: {
18395        x,
18396        y
18397      },
18398      size: {
18399        width: Math.abs(pageRect.right - pageRect.left),
18400        height: Math.abs(pageRect.top - pageRect.bottom)
18401      }
18402    };
18403    return rect;
18404  }
18405  /**
18406   * Read the appearance stream of annotation
18407   * @param annotationPtr - pointer to pdf annotation
18408   * @param mode - appearance mode
18409   * @returns appearance stream
18410   *
18411   * @private
18412   */
18413  readPageAnnoAppearanceStreams(annotationPtr) {
18414    return {
18415      normal: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Normal),
18416      rollover: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Rollover),
18417      down: this.readPageAnnoAppearanceStream(annotationPtr, AppearanceMode.Down)
18418    };
18419  }
18420  /**
18421   * Read the appearance stream of annotation
18422   * @param annotationPtr - pointer to pdf annotation
18423   * @param mode - appearance mode
18424   * @returns appearance stream
18425   *
18426   * @private
18427   */
18428  readPageAnnoAppearanceStream(annotationPtr, mode = AppearanceMode.Normal) {
18429    const utf16Length = this.pdfiumModule.FPDFAnnot_GetAP(annotationPtr, mode, 0, 0);
18430    const bytesCount = (utf16Length + 1) * 2;
18431    const bufferPtr = this.memoryManager.malloc(bytesCount);
18432    this.pdfiumModule.FPDFAnnot_GetAP(annotationPtr, mode, bufferPtr, bytesCount);
18433    const ap = this.pdfiumModule.pdfium.UTF16ToString(bufferPtr);
18434    this.memoryManager.free(bufferPtr);
18435    return ap;
18436  }
18437  /**
18438   * Set the appearance stream of annotation
18439   * @param annotationPtr - pointer to pdf annotation
18440   * @param mode - appearance mode
18441   * @param apContent - appearance stream content (null to remove)
18442   * @returns whether the appearance stream was set successfully
18443   *
18444   * @private
18445   */
18446  setPageAnnoAppearanceStream(annotationPtr, mode = AppearanceMode.Normal, apContent) {
18447    const bytes = 2 * (apContent.length + 1);
18448    const ptr = this.memoryManager.malloc(bytes);
18449    try {
18450      this.pdfiumModule.pdfium.stringToUTF16(apContent, ptr, bytes);
18451      const ok = this.pdfiumModule.FPDFAnnot_SetAP(annotationPtr, mode, ptr);
18452      return !!ok;
18453    } finally {
18454      this.memoryManager.free(ptr);
18455    }
18456  }
18457  /**
18458   * Set the rect of specified annotation
18459   * @param doc - pdf document object
18460   * @param page - page info that the annotation is belonged to
18461   * @param annotationPtr - pointer to annotation object
18462   * @param rect - target rectangle
18463   * @returns whether the rect is setted
18464   *
18465   * @private
18466   */
18467  setPageAnnoRect(doc, page, annotPtr, rect) {
18468    const x0d = rect.origin.x;
18469    const y0d = rect.origin.y;
18470    const x1d = rect.origin.x + rect.size.width;
18471    const y1d = rect.origin.y + rect.size.height;
18472    const TL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y0d });
18473    const TR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y0d });
18474    const BR = this.convertDevicePointToPagePoint(doc, page, { x: x1d, y: y1d });
18475    const BL = this.convertDevicePointToPagePoint(doc, page, { x: x0d, y: y1d });
18476    let left = Math.min(TL.x, TR.x, BR.x, BL.x);
18477    let right = Math.max(TL.x, TR.x, BR.x, BL.x);
18478    let bottom = Math.min(TL.y, TR.y, BR.y, BL.y);
18479    let top = Math.max(TL.y, TR.y, BR.y, BL.y);
18480    if (left > right) [left, right] = [right, left];
18481    if (bottom > top) [bottom, top] = [top, bottom];
18482    const ptr = this.memoryManager.malloc(16);
18483    const pdf = this.pdfiumModule.pdfium;
18484    pdf.setValue(ptr + 0, left, "float");
18485    pdf.setValue(ptr + 4, top, "float");
18486    pdf.setValue(ptr + 8, right, "float");
18487    pdf.setValue(ptr + 12, bottom, "float");
18488    const ok = this.pdfiumModule.FPDFAnnot_SetRect(annotPtr, ptr);
18489    this.memoryManager.free(ptr);
18490    return !!ok;
18491  }
18492  /**
18493   * Read the rectangle of annotation
18494   * @param annotationPtr - pointer to pdf annotation
18495   * @returns rectangle of annotation
18496   *
18497   * @private
18498   */
18499  readPageAnnoRect(annotationPtr) {
18500    const pageRectPtr = this.memoryManager.malloc(4 * 4);
18501    const pageRect = {
18502      left: 0,
18503      top: 0,
18504      right: 0,
18505      bottom: 0
18506    };
18507    if (this.pdfiumModule.EPDFAnnot_GetRect(annotationPtr, pageRectPtr)) {
18508      pageRect.left = this.pdfiumModule.pdfium.getValue(pageRectPtr, "float");
18509      pageRect.top = this.pdfiumModule.pdfium.getValue(pageRectPtr + 4, "float");
18510      pageRect.right = this.pdfiumModule.pdfium.getValue(pageRectPtr + 8, "float");
18511      pageRect.bottom = this.pdfiumModule.pdfium.getValue(pageRectPtr + 12, "float");
18512    }
18513    this.memoryManager.free(pageRectPtr);
18514    return pageRect;
18515  }
18516  /**
18517   * Get highlight rects for a specific character range (for search highlighting)
18518   * @param doc - pdf document object
18519   * @param page - pdf page info
18520   * @param pagePtr - pointer to pdf page
18521   * @param textPagePtr - pointer to pdf text page
18522   * @param startIndex - starting character index
18523   * @param charCount - number of characters in the range
18524   * @returns array of rectangles for highlighting the specified character range
18525   *
18526   * @private
18527   */
18528  getHighlightRects(doc, page, textPagePtr, startIndex, charCount) {
18529    const rectsCount = this.pdfiumModule.FPDFText_CountRects(textPagePtr, startIndex, charCount);
18530    const highlightRects = [];
18531    const l = this.memoryManager.malloc(8);
18532    const t = this.memoryManager.malloc(8);
18533    const r = this.memoryManager.malloc(8);
18534    const b = this.memoryManager.malloc(8);
18535    for (let i = 0; i < rectsCount; i++) {
18536      const ok = this.pdfiumModule.FPDFText_GetRect(textPagePtr, i, l, t, r, b);
18537      if (!ok) continue;
18538      const left = this.pdfiumModule.pdfium.getValue(l, "double");
18539      const top = this.pdfiumModule.pdfium.getValue(t, "double");
18540      const right = this.pdfiumModule.pdfium.getValue(r, "double");
18541      const bottom = this.pdfiumModule.pdfium.getValue(b, "double");
18542      const p1 = this.convertPagePointToDevicePoint(doc, page, { x: left, y: top });
18543      const p2 = this.convertPagePointToDevicePoint(doc, page, { x: right, y: top });
18544      const p3 = this.convertPagePointToDevicePoint(doc, page, { x: right, y: bottom });
18545      const p4 = this.convertPagePointToDevicePoint(doc, page, { x: left, y: bottom });
18546      const xs = [p1.x, p2.x, p3.x, p4.x];
18547      const ys = [p1.y, p2.y, p3.y, p4.y];
18548      const x = Math.min(...xs);
18549      const y = Math.min(...ys);
18550      const width = Math.max(...xs) - x;
18551      const height = Math.max(...ys) - y;
18552      highlightRects.push({
18553        origin: { x, y },
18554        size: { width: Math.ceil(width), height: Math.ceil(height) }
18555      });
18556    }
18557    this.memoryManager.free(l);
18558    this.memoryManager.free(t);
18559    this.memoryManager.free(r);
18560    this.memoryManager.free(b);
18561    return highlightRects;
18562  }
18563  /**
18564   * {@inheritDoc @embedpdf/models!PdfEngine.searchAllPages}
18565   *
18566   * Runs inside the worker.
18567   * Emits per-page progress: { page, results }
18568   *
18569   * @public
18570   */
18571  searchInPage(doc, page, keyword, flags) {
18572    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "searchInPage", doc, page, keyword, flags);
18573    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`SearchInPage\`, "Begin", \`\${doc.id}-\${page.index}\`);
18574    const ctx = this.cache.getContext(doc.id);
18575    if (!ctx) {
18576      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18577      return PdfTaskHelper.reject({
18578        code: PdfErrorCode.DocNotOpen,
18579        message: "Document is not open"
18580      });
18581    }
18582    const length = 2 * (keyword.length + 1);
18583    const keywordPtr = this.memoryManager.malloc(length);
18584    this.pdfiumModule.pdfium.stringToUTF16(keyword, keywordPtr, length);
18585    try {
18586      const results = this.searchAllInPage(doc, ctx, page, keywordPtr, flags);
18587      return PdfTaskHelper.resolve(results);
18588    } finally {
18589      this.memoryManager.free(keywordPtr);
18590    }
18591  }
18592  /**
18593   * Get annotations for multiple pages in a single batch.
18594   * Emits progress per page for streaming updates.
18595   *
18596   * @param doc - PDF document
18597   * @param pages - Array of pages to process
18598   * @returns Task with results keyed by page index, with per-page progress
18599   *
18600   * @public
18601   */
18602  getAnnotationsBatch(doc, pages) {
18603    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "getAnnotationsBatch", doc.id, pages.length);
18604    const task = new Task();
18605    queueMicrotask(() => {
18606      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetAnnotationsBatch", "Begin", doc.id);
18607      const ctx = this.cache.getContext(doc.id);
18608      if (!ctx) {
18609        task.reject({ code: PdfErrorCode.DocNotOpen, message: "Document is not open" });
18610        return;
18611      }
18612      const results = {};
18613      const total = pages.length;
18614      const formInfoPtr = this.pdfiumModule.PDFiumExt_OpenFormFillInfo();
18615      const formHandle = this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(
18616        ctx.docPtr,
18617        formInfoPtr
18618      );
18619      try {
18620        for (let i = 0; i < pages.length; i++) {
18621          const page = pages[i];
18622          const annotations = this.readPageAnnotationsRaw(doc, ctx, page, formHandle);
18623          results[page.index] = annotations;
18624          task.progress({
18625            pageIndex: page.index,
18626            result: annotations,
18627            completed: i + 1,
18628            total
18629          });
18630        }
18631      } finally {
18632        this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(formHandle);
18633        this.pdfiumModule.PDFiumExt_CloseFormFillInfo(formInfoPtr);
18634      }
18635      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "GetAnnotationsBatch", "End", doc.id);
18636      task.resolve(results);
18637    });
18638    return task;
18639  }
18640  /**
18641   * Search across multiple pages in a single batch.
18642   * Emits progress per page for streaming updates.
18643   *
18644   * @param doc - PDF document
18645   * @param pages - Array of pages to search
18646   * @param keyword - Search keyword
18647   * @param flags - Search flags
18648   * @returns Task with results keyed by page index, with per-page progress
18649   *
18650   * @public
18651   */
18652  searchBatch(doc, pages, keyword, flags) {
18653    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "searchBatch", doc.id, pages.length, keyword);
18654    const task = new Task();
18655    queueMicrotask(() => {
18656      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SearchBatch", "Begin", doc.id);
18657      const ctx = this.cache.getContext(doc.id);
18658      if (!ctx) {
18659        task.reject({ code: PdfErrorCode.DocNotOpen, message: "Document is not open" });
18660        return;
18661      }
18662      const length = 2 * (keyword.length + 1);
18663      const keywordPtr = this.memoryManager.malloc(length);
18664      this.pdfiumModule.pdfium.stringToUTF16(keyword, keywordPtr, length);
18665      try {
18666        const results = {};
18667        const total = pages.length;
18668        for (let i = 0; i < pages.length; i++) {
18669          const page = pages[i];
18670          const pageResults = this.searchAllInPage(doc, ctx, page, keywordPtr, flags);
18671          results[page.index] = pageResults;
18672          task.progress({
18673            pageIndex: page.index,
18674            result: pageResults,
18675            completed: i + 1,
18676            total
18677          });
18678        }
18679        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, "SearchBatch", "End", doc.id);
18680        task.resolve(results);
18681      } finally {
18682        this.memoryManager.free(keywordPtr);
18683      }
18684    });
18685    return task;
18686  }
18687  /**
18688   * Extract word-aligned context for a search hit.
18689   *
18690   * @param fullText      full UTF-16 page text (fetch this once per page!)
18691   * @param start         index of 1st char that matched
18692   * @param count         number of chars in the match
18693   * @param windowChars   minimum context chars to keep left & right
18694   */
18695  buildContext(fullText, start, count, windowChars = 30) {
18696    const WORD_BREAK = /[\\s\\u00A0.,;:!?()\\[\\]{}<>/\\\\\\-"'\`"”\\u2013\\u2014]/;
18697    const findWordStart = (index) => {
18698      while (index > 0 && !WORD_BREAK.test(fullText[index - 1])) index--;
18699      return index;
18700    };
18701    const findWordEnd = (index) => {
18702      while (index < fullText.length && !WORD_BREAK.test(fullText[index])) index++;
18703      return index;
18704    };
18705    let left = start;
18706    while (left > 0 && WORD_BREAK.test(fullText[left - 1])) left--;
18707    let collected = 0;
18708    while (left > 0 && collected < windowChars) {
18709      left--;
18710      if (!WORD_BREAK.test(fullText[left])) collected++;
18711    }
18712    left = findWordStart(left);
18713    let right = start + count;
18714    while (right < fullText.length && WORD_BREAK.test(fullText[right])) right++;
18715    collected = 0;
18716    while (right < fullText.length && collected < windowChars) {
18717      if (!WORD_BREAK.test(fullText[right])) collected++;
18718      right++;
18719    }
18720    right = findWordEnd(right);
18721    const before = fullText.slice(left, start).replace(/\\s+/g, " ").trimStart();
18722    const match = fullText.slice(start, start + count);
18723    const after = fullText.slice(start + count, right).replace(/\\s+/g, " ").trimEnd();
18724    return {
18725      before: this.tidy(before),
18726      match: this.tidy(match),
18727      after: this.tidy(after),
18728      truncatedLeft: left > 0,
18729      truncatedRight: right < fullText.length
18730    };
18731  }
18732  /**
18733   * Tidy the text to remove any non-printable characters and whitespace
18734   * @param s - text to tidy
18735   * @returns tidied text
18736   *
18737   * @private
18738   */
18739  tidy(s) {
18740    return s.replace(/-\\uFFFE\\s*/g, "").replace(/[\\uFFFE\\u00AD\\u200B\\u2060\\uFEFF]/g, "").replace(/\\s+/g, " ");
18741  }
18742  /**
18743   * Search for all occurrences of a keyword on a single page
18744   * This method efficiently loads the page only once and finds all matches
18745   *
18746   * @param docPtr - pointer to pdf document
18747   * @param page - pdf page object
18748   * @param pageIndex - index of the page
18749   * @param keywordPtr - pointer to the search keyword
18750   * @param flag - search flags
18751   * @returns array of search results on this page
18752   *
18753   * @private
18754   */
18755  searchAllInPage(doc, ctx, page, keywordPtr, flag) {
18756    return ctx.borrowPage(page.index, (pageCtx) => {
18757      const textPagePtr = pageCtx.getTextPage();
18758      const total = this.pdfiumModule.FPDFText_CountChars(textPagePtr);
18759      const bufPtr = this.memoryManager.malloc(2 * (total + 1));
18760      this.pdfiumModule.FPDFText_GetText(textPagePtr, 0, total, bufPtr);
18761      const fullText = this.pdfiumModule.pdfium.UTF16ToString(bufPtr);
18762      this.memoryManager.free(bufPtr);
18763      const pageResults = [];
18764      const searchHandle = this.pdfiumModule.FPDFText_FindStart(
18765        textPagePtr,
18766        keywordPtr,
18767        flag,
18768        0
18769        // Start from the beginning of the page
18770      );
18771      while (this.pdfiumModule.FPDFText_FindNext(searchHandle)) {
18772        const charIndex = this.pdfiumModule.FPDFText_GetSchResultIndex(searchHandle);
18773        const charCount = this.pdfiumModule.FPDFText_GetSchCount(searchHandle);
18774        const rects = this.getHighlightRects(doc, page, textPagePtr, charIndex, charCount);
18775        const context = this.buildContext(fullText, charIndex, charCount);
18776        pageResults.push({
18777          pageIndex: page.index,
18778          charIndex,
18779          charCount,
18780          rects,
18781          context
18782        });
18783      }
18784      this.pdfiumModule.FPDFText_FindClose(searchHandle);
18785      return pageResults;
18786    });
18787  }
18788  /**
18789   * {@inheritDoc @embedpdf/models!PdfEngine.preparePrintDocument}
18790   *
18791   * Prepares a PDF document for printing with specified options.
18792   * Creates a new document with selected pages and optionally removes annotations
18793   * for optimal printing performance.
18794   *
18795   * @public
18796   */
18797  preparePrintDocument(doc, options) {
18798    const { includeAnnotations = true, pageRange = null } = options ?? {};
18799    this.logger.debug(LOG_SOURCE$1, LOG_CATEGORY$1, "preparePrintDocument", doc, options);
18800    this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "Begin", doc.id);
18801    const ctx = this.cache.getContext(doc.id);
18802    if (!ctx) {
18803      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18804      return PdfTaskHelper.reject({
18805        code: PdfErrorCode.DocNotOpen,
18806        message: "Document is not open"
18807      });
18808    }
18809    const printDocPtr = this.pdfiumModule.FPDF_CreateNewDocument();
18810    if (!printDocPtr) {
18811      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18812      return PdfTaskHelper.reject({
18813        code: PdfErrorCode.CantCreateNewDoc,
18814        message: "Cannot create print document"
18815      });
18816    }
18817    try {
18818      const sanitizedPageRange = this.sanitizePageRange(pageRange, doc.pageCount);
18819      if (!this.pdfiumModule.FPDF_ImportPages(
18820        printDocPtr,
18821        ctx.docPtr,
18822        sanitizedPageRange ?? "",
18823        0
18824        // Insert at beginning
18825      )) {
18826        this.pdfiumModule.FPDF_CloseDocument(printDocPtr);
18827        this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "Failed to import pages for printing");
18828        this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18829        return PdfTaskHelper.reject({
18830          code: PdfErrorCode.CantImportPages,
18831          message: "Failed to import pages for printing"
18832        });
18833      }
18834      if (!includeAnnotations) {
18835        const removalResult = this.removeAnnotationsFromPrintDocument(printDocPtr);
18836        if (!removalResult.success) {
18837          this.pdfiumModule.FPDF_CloseDocument(printDocPtr);
18838          this.logger.error(
18839            LOG_SOURCE$1,
18840            LOG_CATEGORY$1,
18841            \`Failed to remove annotations: \${removalResult.error}\`
18842          );
18843          this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18844          return PdfTaskHelper.reject({
18845            code: PdfErrorCode.Unknown,
18846            message: \`Failed to prepare print document: \${removalResult.error}\`
18847          });
18848        }
18849        this.logger.debug(
18850          LOG_SOURCE$1,
18851          LOG_CATEGORY$1,
18852          \`Removed \${removalResult.annotationsRemoved} annotations from \${removalResult.pagesProcessed} pages\`
18853        );
18854      }
18855      const buffer = this.saveDocument(printDocPtr);
18856      this.pdfiumModule.FPDF_CloseDocument(printDocPtr);
18857      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18858      return PdfTaskHelper.resolve(buffer);
18859    } catch (error) {
18860      if (printDocPtr) {
18861        this.pdfiumModule.FPDF_CloseDocument(printDocPtr);
18862      }
18863      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, "preparePrintDocument failed", error);
18864      this.logger.perf(LOG_SOURCE$1, LOG_CATEGORY$1, \`PreparePrintDocument\`, "End", doc.id);
18865      return PdfTaskHelper.reject({
18866        code: PdfErrorCode.Unknown,
18867        message: error instanceof Error ? error.message : "Failed to prepare print document"
18868      });
18869    }
18870  }
18871  /**
18872   * Removes all annotations from a print document using fast raw annotation functions.
18873   * This method is optimized for performance by avoiding full page loading.
18874   *
18875   * @param printDocPtr - Pointer to the print document
18876   * @returns Result object with success status and statistics
18877   *
18878   * @private
18879   */
18880  removeAnnotationsFromPrintDocument(printDocPtr) {
18881    let totalAnnotationsRemoved = 0;
18882    let pagesProcessed = 0;
18883    try {
18884      const pageCount = this.pdfiumModule.FPDF_GetPageCount(printDocPtr);
18885      for (let pageIndex = 0; pageIndex < pageCount; pageIndex++) {
18886        const annotCount = this.pdfiumModule.EPDFPage_GetAnnotCountRaw(printDocPtr, pageIndex);
18887        if (annotCount <= 0) {
18888          pagesProcessed++;
18889          continue;
18890        }
18891        let annotationsRemovedFromPage = 0;
18892        for (let annotIndex = annotCount - 1; annotIndex >= 0; annotIndex--) {
18893          const removed = this.pdfiumModule.EPDFPage_RemoveAnnotRaw(
18894            printDocPtr,
18895            pageIndex,
18896            annotIndex
18897          );
18898          if (removed) {
18899            annotationsRemovedFromPage++;
18900            totalAnnotationsRemoved++;
18901          } else {
18902            this.logger.warn(
18903              LOG_SOURCE$1,
18904              LOG_CATEGORY$1,
18905              \`Failed to remove annotation \${annotIndex} from page \${pageIndex}\`
18906            );
18907          }
18908        }
18909        if (annotationsRemovedFromPage > 0) {
18910          const pagePtr = this.pdfiumModule.FPDF_LoadPage(printDocPtr, pageIndex);
18911          if (pagePtr) {
18912            this.pdfiumModule.FPDFPage_GenerateContent(pagePtr);
18913            this.pdfiumModule.FPDF_ClosePage(pagePtr);
18914          }
18915        }
18916        pagesProcessed++;
18917      }
18918      return {
18919        success: true,
18920        annotationsRemoved: totalAnnotationsRemoved,
18921        pagesProcessed
18922      };
18923    } catch (error) {
18924      return {
18925        success: false,
18926        annotationsRemoved: totalAnnotationsRemoved,
18927        pagesProcessed,
18928        error: error instanceof Error ? error.message : "Unknown error during annotation removal"
18929      };
18930    }
18931  }
18932  /**
18933   * Sanitizes and validates a page range string.
18934   * Ensures page numbers are within valid bounds and properly formatted.
18935   *
18936   * @param pageRange - Page range string (e.g., "1,3,5-7") or null for all pages
18937   * @param totalPages - Total number of pages in the document
18938   * @returns Sanitized page range string or null for all pages
18939   *
18940   * @private
18941   */
18942  sanitizePageRange(pageRange, totalPages) {
18943    if (!pageRange || pageRange.trim() === "") {
18944      return null;
18945    }
18946    try {
18947      const sanitized = [];
18948      const parts = pageRange.split(",");
18949      for (const part of parts) {
18950        const trimmed = part.trim();
18951        if (trimmed.includes("-")) {
18952          const [startStr, endStr] = trimmed.split("-").map((s) => s.trim());
18953          const start = parseInt(startStr, 10);
18954          const end = parseInt(endStr, 10);
18955          if (isNaN(start) || isNaN(end)) {
18956            this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, \`Invalid range: \${trimmed}\`);
18957            continue;
18958          }
18959          const validStart = Math.max(1, Math.min(start, totalPages));
18960          const validEnd = Math.max(1, Math.min(end, totalPages));
18961          for (let i = validStart; i <= validEnd; i++) {
18962            if (!sanitized.includes(i)) {
18963              sanitized.push(i);
18964            }
18965          }
18966        } else {
18967          const pageNum = parseInt(trimmed, 10);
18968          if (isNaN(pageNum)) {
18969            this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, \`Invalid page number: \${trimmed}\`);
18970            continue;
18971          }
18972          const validPageNum = Math.max(1, Math.min(pageNum, totalPages));
18973          if (!sanitized.includes(validPageNum)) {
18974            sanitized.push(validPageNum);
18975          }
18976        }
18977      }
18978      if (sanitized.length === 0) {
18979        this.logger.warn(LOG_SOURCE$1, LOG_CATEGORY$1, "No valid pages in range, using all pages");
18980        return null;
18981      }
18982      sanitized.sort((a, b) => a - b);
18983      const optimized = [];
18984      let rangeStart = sanitized[0];
18985      let rangeEnd = sanitized[0];
18986      for (let i = 1; i < sanitized.length; i++) {
18987        if (sanitized[i] === rangeEnd + 1) {
18988          rangeEnd = sanitized[i];
18989        } else {
18990          if (rangeStart === rangeEnd) {
18991            optimized.push(rangeStart.toString());
18992          } else if (rangeEnd - rangeStart === 1) {
18993            optimized.push(rangeStart.toString());
18994            optimized.push(rangeEnd.toString());
18995          } else {
18996            optimized.push(\`\${rangeStart}-\${rangeEnd}\`);
18997          }
18998          rangeStart = sanitized[i];
18999          rangeEnd = sanitized[i];
19000        }
19001      }
19002      if (rangeStart === rangeEnd) {
19003        optimized.push(rangeStart.toString());
19004      } else if (rangeEnd - rangeStart === 1) {
19005        optimized.push(rangeStart.toString());
19006        optimized.push(rangeEnd.toString());
19007      } else {
19008        optimized.push(\`\${rangeStart}-\${rangeEnd}\`);
19009      }
19010      const result = optimized.join(",");
19011      this.logger.debug(
19012        LOG_SOURCE$1,
19013        LOG_CATEGORY$1,
19014        \`Sanitized page range: "\${pageRange}" -> "\${result}"\`
19015      );
19016      return result;
19017    } catch (error) {
19018      this.logger.error(LOG_SOURCE$1, LOG_CATEGORY$1, \`Error sanitizing page range: \${error}\`);
19019      return null;
19020    }
19021  }
19022}
19023const LOG_SOURCE = "PdfiumNativeRunner";
19024const LOG_CATEGORY = "Worker";
19025class PdfiumNativeRunner {
19026  constructor(logger) {
19027    this.native = null;
19028    this.activeTasks = /* @__PURE__ */ new Map();
19029    this.logger = logger ?? new NoopLogger();
19030    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "PdfiumNativeRunner created");
19031  }
19032  /**
19033   * Initialize PDFium with WASM binary
19034   */
19035  async prepare(wasmBinary, logger) {
19036    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Preparing PDFium...");
19037    try {
19038      const module = await init({ wasmBinary });
19039      this.native = new PdfiumNative(module, { logger: logger ?? this.logger });
19040      this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "PDFium initialized successfully");
19041    } catch (error) {
19042      this.logger.error(LOG_SOURCE, LOG_CATEGORY, "Failed to initialize PDFium:", error);
19043      throw error;
19044    }
19045  }
19046  /**
19047   * Start listening for messages
19048   */
19049  listen() {
19050    self.onmessage = (evt) => {
19051      this.handle(evt);
19052    };
19053    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Listening for messages");
19054  }
19055  /**
19056   * Handle incoming messages
19057   */
19058  handle(evt) {
19059    const request = evt.data;
19060    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Received message:", request.type);
19061    try {
19062      switch (request.type) {
19063        case "init":
19064          this.handleInit(request);
19065          break;
19066        case "execute":
19067          this.handleExecute(request);
19068          break;
19069        default:
19070          this.logger.warn(LOG_SOURCE, LOG_CATEGORY, "Unknown message type:", request.type);
19071      }
19072    } catch (error) {
19073      this.logger.error(LOG_SOURCE, LOG_CATEGORY, "Error handling message:", error);
19074      this.respond({
19075        id: request.id,
19076        type: "error",
19077        error: {
19078          type: "reject",
19079          reason: { code: PdfErrorCode.Unknown, message: String(error) }
19080        }
19081      });
19082    }
19083  }
19084  /**
19085   * Handle initialization request
19086   */
19087  async handleInit(request) {
19088    if (!request.wasmUrl) {
19089      this.respond({
19090        id: request.id,
19091        type: "error",
19092        error: {
19093          type: "reject",
19094          reason: { code: PdfErrorCode.Unknown, message: "Missing wasmUrl" }
19095        }
19096      });
19097      return;
19098    }
19099    try {
19100      const response = await fetch(request.wasmUrl);
19101      const wasmBinary = await response.arrayBuffer();
19102      await this.prepare(wasmBinary);
19103      this.respond({
19104        id: request.id,
19105        type: "ready"
19106      });
19107    } catch (error) {
19108      this.respond({
19109        id: request.id,
19110        type: "error",
19111        error: {
19112          type: "reject",
19113          reason: { code: PdfErrorCode.Unknown, message: String(error) }
19114        }
19115      });
19116    }
19117  }
19118  /**
19119   * Handle method execution request
19120   */
19121  async handleExecute(request) {
19122    if (!this.native) {
19123      this.respond({
19124        id: request.id,
19125        type: "error",
19126        error: {
19127          type: "reject",
19128          reason: { code: PdfErrorCode.NotReady, message: "PDFium not initialized" }
19129        }
19130      });
19131      return;
19132    }
19133    if (!request.method) {
19134      this.respond({
19135        id: request.id,
19136        type: "error",
19137        error: {
19138          type: "reject",
19139          reason: { code: PdfErrorCode.Unknown, message: "Missing method n
19139ame" }
19140        }
19141      });
19142      return;
19143    }
19144    const method = request.method;
19145    const args = request.args ?? [];
19146    if (!(method in this.native) || typeof this.native[method] !== "function") {
19147      this.respond({
19148        id: request.id,
19149        type: "error",
19150        error: {
19151          type: "reject",
19152          reason: { code: PdfErrorCode.NotSupport, message: \`Method \${method} not supported\` }
19153        }
19154      });
19155      return;
19156    }
19157    try {
19158      this.logger.debug(LOG_SOURCE, LOG_CATEGORY, \`Executing method: \${method}\`);
19159      const result = this.native[method](...args);
19160      if (result && typeof result === "object" && "wait" in result) {
19161        const task = result;
19162        this.activeTasks.set(request.id, task);
19163        task.onProgress((progress) => {
19164          this.respond({
19165            id: request.id,
19166            type: "progress",
19167            progress
19168          });
19169        });
19170        task.wait(
19171          (data) => {
19172            this.logger.debug(LOG_SOURCE, LOG_CATEGORY, \`Method \${method} resolved\`);
19173            this.respond({
19174              id: request.id,
19175              type: "result",
19176              data
19177            });
19178            this.activeTasks.delete(request.id);
19179          },
19180          (error) => {
19181            this.logger.debug(LOG_SOURCE, LOG_CATEGORY, \`Method \${method} failed:\`, error);
19182            this.respond({
19183              id: request.id,
19184              type: "error",
19185              error
19186            });
19187            this.activeTasks.delete(request.id);
19188          }
19189        );
19190      } else {
19191        this.respond({
19192          id: request.id,
19193          type: "result",
19194          data: result
19195        });
19196      }
19197    } catch (error) {
19198      this.logger.error(LOG_SOURCE, LOG_CATEGORY, \`Error executing \${method}:\`, error);
19199      this.respond({
19200        id: request.id,
19201        type: "error",
19202        error: {
19203          type: "reject",
19204          reason: { code: PdfErrorCode.Unknown, message: String(error) }
19205        }
19206      });
19207    }
19208  }
19209  /**
19210   * Send response back to main thread
19211   */
19212  respond(response) {
19213    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Sending response:", response.type);
19214    self.postMessage(response);
19215  }
19216  /**
19217   * Ready notification
19218   */
19219  ready() {
19220    this.listen();
19221    this.respond({
19222      id: "0",
19223      type: "ready"
19224    });
19225    this.logger.debug(LOG_SOURCE, LOG_CATEGORY, "Runner is ready");
19226  }
19227}
19228class PdfiumEngineRunner extends PdfiumNativeRunner {
19229  /**
19230   * Create an instance of PdfiumEngineRunner
19231   * @param wasmBinary - wasm binary that contains the pdfium wasm file
19232   * @param logger - optional logger instance
19233   * @param fontFallback - optional font fallback configuration
19234   */
19235  constructor(wasmBinary, logger, fontFallback) {
19236    super(logger);
19237    this.wasmBinary = wasmBinary;
19238    this.fontFallback = fontFallback;
19239  }
19240  /**
19241   * Initialize runner
19242   */
19243  async prepare() {
19244    const wasmBinary = this.wasmBinary;
19245    const wasmModule = await init({ wasmBinary });
19246    this.native = new PdfiumNative(wasmModule, {
19247      logger: this.logger,
19248      fontFallback: this.fontFallback
19249    });
19250    this.ready();
19251  }
19252}
19253const fonts$6 = [
19254  { file: "NotoSansJP-Thin.otf", weight: 100 },
19255  { file: "NotoSansJP-Light.otf", weight: 300 },
19256  { file: "NotoSansJP-DemiLight.otf", weight: 350 },
19257  { file: "NotoSansJP-Regular.otf", weight: 400 },
19258  { file: "NotoSansJP-Medium.otf", weight: 500 },
19259  { file: "NotoSansJP-Bold.otf", weight: 700 },
19260  { file: "NotoSansJP-Black.otf", weight: 900 }
19261];
19262const fonts$5 = [
19263  { file: "NotoSansKR-Thin.otf", weight: 100 },
19264  { file: "NotoSansKR-Light.otf", weight: 300 },
19265  { file: "NotoSansKR-DemiLight.otf", weight: 350 },
19266  { file: "NotoSansKR-Regular.otf", weight: 400 },
19267  { file: "NotoSansKR-Medium.otf", weight: 500 },
19268  { file: "NotoSansKR-Bold.otf", weight: 700 },
19269  { file: "NotoSansKR-Black.otf", weight: 900 }
19270];
19271const fonts$4 = [
19272  { file: "NotoSansHans-Light.otf", weight: 300 },
19273  { file: "NotoSansHans-DemiLight.otf", weight: 350 },
19274  { file: "NotoSansHans-Regular.otf", weight: 400 },
19275  { file: "NotoSansHans-Medium.otf", weight: 500 },
19276  { file: "NotoSansHans-Bold.otf", weight: 700 }
19277];
19278const fonts$3 = [
19279  { file: "NotoSansHant-Thin.otf", weight: 100 },
19280  { file: "NotoSansHant-Light.otf", weight: 300 },
19281  { file: "NotoSansHant-DemiLight.otf", weight: 350 },
19282  { file: "NotoSansHant-Regular.otf", weight: 400 },
19283  { file: "NotoSansHant-Medium.otf", weight: 500 },
19284  { file: "NotoSansHant-Bold.otf", weight: 700 },
19285  { file: "NotoSansHant-Black.otf", weight: 900 }
19286];
19287const fonts$2 = [
19288  { file: "NotoNaskhArabic-Regular.ttf", weight: 400 },
19289  { file: "NotoNaskhArabic-Bold.ttf", weight: 700 }
19290];
19291const fonts$1 = [
19292  { file: "NotoSansHebrew-Regular.ttf", weight: 400 },
19293  { file: "NotoSansHebrew-Bold.ttf", weight: 700 }
19294];
19295const fonts = [
19296  // Thin (100)
19297  { file: "NotoSans-Thin.ttf", weight: 100 },
19298  { file: "NotoSans-ThinItalic.ttf", weight: 100, italic: true },
19299  // ExtraLight (200)
19300  { file: "NotoSans-ExtraLight.ttf", weight: 200 },
19301  { file: "NotoSans-ExtraLightItalic.ttf", weight: 200, italic: true },
19302  // Light (300)
19303  { file: "NotoSans-Light.ttf", weight: 300 },
19304  { file: "NotoSans-LightItalic.ttf", weight: 300, italic: true },
19305  // Regular (400)
19306  { file: "NotoSans-Regular.ttf", weight: 400 },
19307  { file: "NotoSans-Italic.ttf", weight: 400, italic: true },
19308  // Medium (500)
19309  { file: "NotoSans-Medium.ttf", weight: 500 },
19310  { file: "NotoSans-MediumItalic.ttf", weight: 500, italic: true },
19311  // SemiBold (600)
19312  { file: "NotoSans-SemiBold.ttf", weight: 600 },
19313  { file: "NotoSans-SemiBoldItalic.ttf", weight: 600, italic: true },
19314  // Bold (700)
19315  { file: "NotoSans-Bold.ttf", weight: 700 },
19316  { file: "NotoSans-BoldItalic.ttf", weight: 700, italic: true },
19317  // ExtraBold (800)
19318  { file: "NotoSans-ExtraBold.ttf", weight: 800 },
19319  { file: "NotoSans-ExtraBoldItalic.ttf", weight: 800, italic: true },
19320  // Black (900)
19321  { file: "NotoSans-Black.ttf", weight: 900 },
19322  { file: "NotoSans-BlackItalic.ttf", weight: 900, italic: true }
19323];
19324function buildCdnUrls(version = "latest") {
19325  return {
19326    jp: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-jp@\${version}/fonts\`,
19327    kr: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-kr@\${version}/fonts\`,
19328    sc: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-sc@\${version}/fonts\`,
19329    tc: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-tc@\${version}/fonts\`,
19330    arabic: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-arabic@\${version}/fonts\`,
19331    hebrew: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-hebrew@\${version}/fonts\`,
19332    latin: \`https://cdn.jsdelivr.net/npm/@embedpdf/fonts-latin@\${version}/fonts\`
19333  };
19334}
19335function toFontVariants(fonts2, baseUrl) {
19336  return fonts2.map((f) => ({
19337    url: \`\${baseUrl}/\${f.file}\`,
19338    weight: f.weight,
19339    italic: f.italic
19340  }));
19341}
19342function buildCdnFontConfig(urls) {
19343  return {
19344    fonts: {
19345      [FontCharset.SHIFTJIS]: toFontVariants(fonts$6, urls.jp),
19346      [FontCharset.HANGEUL]: toFontVariants(fonts$5, urls.kr),
19347      [FontCharset.GB2312]: toFontVariants(fonts$4, urls.sc),
19348      [FontCharset.CHINESEBIG5]: toFontVariants(fonts$3, urls.tc),
19349      [FontCharset.ARABIC]: toFontVariants(fonts$2, urls.arabic),
19350      [FontCharset.HEBREW]: toFontVariants(fonts$1, urls.hebrew),
19351      [FontCharset.CYRILLIC]: toFontVariants(fonts, urls.latin),
19352      [FontCharset.GREEK]: toFontVariants(fonts, urls.latin),
19353      [FontCharset.VIETNAMESE]: toFontVariants(fonts, urls.latin)
19354    }
19355  };
19356}
19357const FONT_CDN_URLS = buildCdnUrls("latest");
19358const cdnFontConfig = buildCdnFontConfig(FONT_CDN_URLS);
19359let runner = null;
19360self.onmessage = async (event) => {
19361  const { type, wasmUrl, logger: serializedLogger, fontFallback } = event.data;
19362  if (type === "wasmInit" && wasmUrl && !runner) {
19363    try {
19364      const response = await fetch(wasmUrl);
19365      const wasmBinary = await response.arrayBuffer();
19366      const logger = serializedLogger ? deserializeLogger(serializedLogger) : void 0;
19367      const effectiveFontFallback = fontFallback === null ? void 0 : fontFallback ?? cdnFontConfig;
19368      runner = new PdfiumEngineRunner(wasmBinary, logger, effectiveFontFallback);
19369      await runner.prepare();
19370    } catch (error) {
19371      const message = error instanceof Error ? error.message : String(error);
19372      self.postMessage({ type: "wasmError", error: message });
19373    }
19374  }
19375};
19376`],{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) {
19377  const pixels = width * height * 4;
19378  const headerLength = 66;
19379  const le32 = (v) => [v & 255, v >>> 8 & 255, v >>> 16 & 255, v >>> 24 & 255];
19380  const header = new Uint8Array([
19381    66,
19382    77,
19383    // 'BM' signature
19384    ...le32(headerLength + pixels),
19385    // file size
19386    0,
19387    0,
19388    0,
19389    0,
19390    // reserved
19391    headerLength,
19392    0,
19393    0,
19394    0,
19395    // pixel data offset
19396    40,
19397    0,
19398    0,
19399    0,
19400    // DIB header size
19401    ...le32(width),
19402    // width
19403    ...le32(-height),
19404    // height (negative = top-down)
19405    1,
19406    0,
19407    // color planes
19408    32,
19409    0,
19410    // bits per pixel
19411    3,
19412    0,
19413    0,
19414    0,
19415    // compression = BI_BITFIELDS
19416    ...le32(pixels),
19417    // image data size
19418    0,
19419    0,
19420    0,
19421    0,
19422    // h resolution
19423    0,
19424    0,
19425    0,
19426    0,
19427    // v resolution
19428    0,
19429    0,
19430    0,
19431    0,
19432    // colors in palette
19433    0,
19434    0,
19435    0,
19436    0,
19437    // important colors
19438    255,
19439    0,
19440    0,
19441    0,
19442    // R channel mask
19443    0,
19444    255,
19445    0,
19446    0,
19447    // G channel mask
19448    0,
19449    0,
19450    255,
19451    0
19452    // B channel mask
19453  ]);
19454  return new Blob(
19455    [header, new Uint8Array(rgba.buffer, rgba.byteOffset, rgba.byteLength)],
19456    { type: "image/bmp" }
19457  );
19458}
19459async function encodeImage(imageData, imageType, quality) {
19460  if (imageType === "image/bmp") {
19461    return rgbaToBmpBlob(imageData.data, imageData.width, imageData.height);
19462  }
19463  if (typeof OffscreenCanvas === "undefined") {
19464    throw new Error("OffscreenCanvas is not available in this worker environment");
19465  }
19466  const { data, width, height } = imageData;
19467  const imgData = new ImageData(new Uint8ClampedArray(data), width, height);
19468  const canvas = new OffscreenCanvas(width, height);
19469  const ctx = canvas.getContext("2d");
19470  if (!ctx) {
19471    throw new Error("Failed to get 2D context from OffscreenCanvas");
19472  }
19473  ctx.putImageData(imgData, 0, 0);
19474  return canvas.convertToBlob({ type: imageType, quality });
19475}
19476self.onmessage = async (event) => {
19477  const request = event.data;
19478  if (request.type !== "encode") {
19479    return;
19480  }
19481  try {
19482    const { imageData, imageType, quality } = request.data;
19483    const blob = await encodeImage(imageData, imageType, quality);
19484    const response = {
19485      id: request.id,
19486      type: "result",
19487      data: blob
19488    };
19489    self.postMessage(response);
19490  } catch (error) {
19491    const response = {
19492      id: request.id,
19493      type: "error",
19494      data: {
19495        message: error instanceof Error ? error.message : String(error)
19496      }
19497    };
19498    self.postMessage(response);
19499  }
19500};
19501`],{type:"application/javascript"})),h=new A(r??2,p,t);return new _(u,{imageConverter:b(h),logger:t})}export{G 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.