@clazic/kordoc 2.5.0 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -118,9 +118,9 @@ function sanitizeMeta(meta, cfg) {
118
118
  }
119
119
  return out;
120
120
  }
121
- function parsePositiveInt(input, fallback2) {
121
+ function parsePositiveInt(input, fallback) {
122
122
  const n = Number(input);
123
- if (!Number.isFinite(n) || n < 0) return fallback2;
123
+ if (!Number.isFinite(n) || n < 0) return fallback;
124
124
  return Math.floor(n);
125
125
  }
126
126
  function limitText(input, maxLen) {
@@ -289,9 +289,9 @@ var init_logger = __esm({
289
289
  }
290
290
  });
291
291
 
292
- // ../../../node_modules/cfb/cfb.js
292
+ // node_modules/cfb/cfb.js
293
293
  var require_cfb = __commonJS({
294
- "../../../node_modules/cfb/cfb.js"(exports2, module2) {
294
+ "node_modules/cfb/cfb.js"(exports2, module2) {
295
295
  "use strict";
296
296
  var Base64_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
297
297
  function Base64_encode(input) {
@@ -2467,7 +2467,7 @@ function createBatchCliProvider(mode, batchSize) {
2467
2467
  };
2468
2468
  }
2469
2469
  function spawnAsync(cmd, args, opts) {
2470
- return new Promise((resolve4, reject2) => {
2470
+ return new Promise((resolve4, reject) => {
2471
2471
  const child = (0, import_child_process3.spawn)(cmd, args, {
2472
2472
  cwd: opts.cwd,
2473
2473
  env: process.env,
@@ -2501,14 +2501,14 @@ function spawnAsync(cmd, args, opts) {
2501
2501
  child.on("close", (code) => {
2502
2502
  clearTimeout(timer);
2503
2503
  if (killed) {
2504
- reject2(new Error(`\uD0C0\uC784\uC544\uC6C3 (${Math.round(opts.timeoutMs / 1e3)}\uCD08)`));
2504
+ reject(new Error(`\uD0C0\uC784\uC544\uC6C3 (${Math.round(opts.timeoutMs / 1e3)}\uCD08)`));
2505
2505
  } else {
2506
2506
  resolve4({ stdout, stderr, exitCode: code ?? 1 });
2507
2507
  }
2508
2508
  });
2509
2509
  child.on("error", (err) => {
2510
2510
  clearTimeout(timer);
2511
- reject2(err);
2511
+ reject(err);
2512
2512
  });
2513
2513
  });
2514
2514
  }
@@ -2930,9 +2930,9 @@ async function ocrPagesBatch(doc, provider, pageFilter, effectivePageCount, warn
2930
2930
  });
2931
2931
  }
2932
2932
  } catch (err) {
2933
- const range2 = `${batchPageNums[0]}-${batchPageNums[batchPageNums.length - 1]}`;
2933
+ const range = `${batchPageNums[0]}-${batchPageNums[batchPageNums.length - 1]}`;
2934
2934
  warnings?.push({
2935
- message: `\uBC30\uCE58 OCR \uC2E4\uD328 (\uD398\uC774\uC9C0 ${range2}): ${err instanceof Error ? err.message : "\uC54C \uC218 \uC5C6\uB294 \uC624\uB958"} \u2014 \uB2E8\uC77C \uD398\uC774\uC9C0\uB85C \uC7AC\uC2DC\uB3C4`,
2935
+ message: `\uBC30\uCE58 OCR \uC2E4\uD328 (\uD398\uC774\uC9C0 ${range}): ${err instanceof Error ? err.message : "\uC54C \uC218 \uC5C6\uB294 \uC624\uB958"} \u2014 \uB2E8\uC77C \uD398\uC774\uC9C0\uB85C \uC7AC\uC2DC\uB3C4`,
2936
2936
  code: "OCR_PAGE_FAILED"
2937
2937
  });
2938
2938
  for (const { image, pageNum } of batchImages) {
@@ -2977,2320 +2977,6 @@ var init_provider = __esm({
2977
2977
  }
2978
2978
  });
2979
2979
 
2980
- // ../../../node_modules/async/dist/async.mjs
2981
- var async_exports = {};
2982
- __export(async_exports, {
2983
- all: () => every$1,
2984
- allLimit: () => everyLimit$1,
2985
- allSeries: () => everySeries$1,
2986
- any: () => some$1,
2987
- anyLimit: () => someLimit$1,
2988
- anySeries: () => someSeries$1,
2989
- apply: () => apply,
2990
- applyEach: () => applyEach,
2991
- applyEachSeries: () => applyEachSeries,
2992
- asyncify: () => asyncify,
2993
- auto: () => auto,
2994
- autoInject: () => autoInject,
2995
- cargo: () => cargo$1,
2996
- cargoQueue: () => cargo,
2997
- compose: () => compose,
2998
- concat: () => concat$1,
2999
- concatLimit: () => concatLimit$1,
3000
- concatSeries: () => concatSeries$1,
3001
- constant: () => constant$1,
3002
- default: () => index,
3003
- detect: () => detect$1,
3004
- detectLimit: () => detectLimit$1,
3005
- detectSeries: () => detectSeries$1,
3006
- dir: () => dir,
3007
- doDuring: () => doWhilst$1,
3008
- doUntil: () => doUntil,
3009
- doWhilst: () => doWhilst$1,
3010
- during: () => whilst$1,
3011
- each: () => each,
3012
- eachLimit: () => eachLimit$1,
3013
- eachOf: () => eachOf$1,
3014
- eachOfLimit: () => eachOfLimit$1,
3015
- eachOfSeries: () => eachOfSeries$1,
3016
- eachSeries: () => eachSeries$1,
3017
- ensureAsync: () => ensureAsync,
3018
- every: () => every$1,
3019
- everyLimit: () => everyLimit$1,
3020
- everySeries: () => everySeries$1,
3021
- filter: () => filter$1,
3022
- filterLimit: () => filterLimit$1,
3023
- filterSeries: () => filterSeries$1,
3024
- find: () => detect$1,
3025
- findLimit: () => detectLimit$1,
3026
- findSeries: () => detectSeries$1,
3027
- flatMap: () => concat$1,
3028
- flatMapLimit: () => concatLimit$1,
3029
- flatMapSeries: () => concatSeries$1,
3030
- foldl: () => reduce$1,
3031
- foldr: () => reduceRight,
3032
- forEach: () => each,
3033
- forEachLimit: () => eachLimit$1,
3034
- forEachOf: () => eachOf$1,
3035
- forEachOfLimit: () => eachOfLimit$1,
3036
- forEachOfSeries: () => eachOfSeries$1,
3037
- forEachSeries: () => eachSeries$1,
3038
- forever: () => forever$1,
3039
- groupBy: () => groupBy,
3040
- groupByLimit: () => groupByLimit$1,
3041
- groupBySeries: () => groupBySeries,
3042
- inject: () => reduce$1,
3043
- log: () => log,
3044
- map: () => map$1,
3045
- mapLimit: () => mapLimit$1,
3046
- mapSeries: () => mapSeries$1,
3047
- mapValues: () => mapValues,
3048
- mapValuesLimit: () => mapValuesLimit$1,
3049
- mapValuesSeries: () => mapValuesSeries,
3050
- memoize: () => memoize,
3051
- nextTick: () => nextTick,
3052
- parallel: () => parallel,
3053
- parallelLimit: () => parallelLimit,
3054
- priorityQueue: () => priorityQueue,
3055
- queue: () => queue,
3056
- race: () => race$1,
3057
- reduce: () => reduce$1,
3058
- reduceRight: () => reduceRight,
3059
- reflect: () => reflect,
3060
- reflectAll: () => reflectAll,
3061
- reject: () => reject$1,
3062
- rejectLimit: () => rejectLimit$1,
3063
- rejectSeries: () => rejectSeries$1,
3064
- retry: () => retry,
3065
- retryable: () => retryable,
3066
- select: () => filter$1,
3067
- selectLimit: () => filterLimit$1,
3068
- selectSeries: () => filterSeries$1,
3069
- seq: () => seq,
3070
- series: () => series,
3071
- setImmediate: () => setImmediate$1,
3072
- some: () => some$1,
3073
- someLimit: () => someLimit$1,
3074
- someSeries: () => someSeries$1,
3075
- sortBy: () => sortBy$1,
3076
- timeout: () => timeout,
3077
- times: () => times,
3078
- timesLimit: () => timesLimit,
3079
- timesSeries: () => timesSeries,
3080
- transform: () => transform,
3081
- tryEach: () => tryEach$1,
3082
- unmemoize: () => unmemoize,
3083
- until: () => until,
3084
- waterfall: () => waterfall$1,
3085
- whilst: () => whilst$1,
3086
- wrapSync: () => asyncify
3087
- });
3088
- function apply(fn, ...args) {
3089
- return (...callArgs) => fn(...args, ...callArgs);
3090
- }
3091
- function initialParams(fn) {
3092
- return function(...args) {
3093
- var callback = args.pop();
3094
- return fn.call(this, args, callback);
3095
- };
3096
- }
3097
- function fallback(fn) {
3098
- setTimeout(fn, 0);
3099
- }
3100
- function wrap(defer) {
3101
- return (fn, ...args) => defer(() => fn(...args));
3102
- }
3103
- function asyncify(func) {
3104
- if (isAsync(func)) {
3105
- return function(...args) {
3106
- const callback = args.pop();
3107
- const promise = func.apply(this, args);
3108
- return handlePromise(promise, callback);
3109
- };
3110
- }
3111
- return initialParams(function(args, callback) {
3112
- var result;
3113
- try {
3114
- result = func.apply(this, args);
3115
- } catch (e) {
3116
- return callback(e);
3117
- }
3118
- if (result && typeof result.then === "function") {
3119
- return handlePromise(result, callback);
3120
- } else {
3121
- callback(null, result);
3122
- }
3123
- });
3124
- }
3125
- function handlePromise(promise, callback) {
3126
- return promise.then((value) => {
3127
- invokeCallback(callback, null, value);
3128
- }, (err) => {
3129
- invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err));
3130
- });
3131
- }
3132
- function invokeCallback(callback, error, value) {
3133
- try {
3134
- callback(error, value);
3135
- } catch (err) {
3136
- setImmediate$1((e) => {
3137
- throw e;
3138
- }, err);
3139
- }
3140
- }
3141
- function isAsync(fn) {
3142
- return fn[Symbol.toStringTag] === "AsyncFunction";
3143
- }
3144
- function isAsyncGenerator(fn) {
3145
- return fn[Symbol.toStringTag] === "AsyncGenerator";
3146
- }
3147
- function isAsyncIterable(obj) {
3148
- return typeof obj[Symbol.asyncIterator] === "function";
3149
- }
3150
- function wrapAsync(asyncFn) {
3151
- if (typeof asyncFn !== "function") throw new Error("expected a function");
3152
- return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
3153
- }
3154
- function awaitify(asyncFn, arity) {
3155
- if (!arity) arity = asyncFn.length;
3156
- if (!arity) throw new Error("arity is undefined");
3157
- function awaitable(...args) {
3158
- if (typeof args[arity - 1] === "function") {
3159
- return asyncFn.apply(this, args);
3160
- }
3161
- return new Promise((resolve4, reject2) => {
3162
- args[arity - 1] = (err, ...cbArgs) => {
3163
- if (err) return reject2(err);
3164
- resolve4(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
3165
- };
3166
- asyncFn.apply(this, args);
3167
- });
3168
- }
3169
- return awaitable;
3170
- }
3171
- function applyEach$1(eachfn) {
3172
- return function applyEach2(fns, ...callArgs) {
3173
- const go = awaitify(function(callback) {
3174
- var that = this;
3175
- return eachfn(fns, (fn, cb) => {
3176
- wrapAsync(fn).apply(that, callArgs.concat(cb));
3177
- }, callback);
3178
- });
3179
- return go;
3180
- };
3181
- }
3182
- function _asyncMap(eachfn, arr, iteratee, callback) {
3183
- arr = arr || [];
3184
- var results = [];
3185
- var counter = 0;
3186
- var _iteratee = wrapAsync(iteratee);
3187
- return eachfn(arr, (value, _, iterCb) => {
3188
- var index2 = counter++;
3189
- _iteratee(value, (err, v) => {
3190
- results[index2] = v;
3191
- iterCb(err);
3192
- });
3193
- }, (err) => {
3194
- callback(err, results);
3195
- });
3196
- }
3197
- function isArrayLike(value) {
3198
- return value && typeof value.length === "number" && value.length >= 0 && value.length % 1 === 0;
3199
- }
3200
- function once(fn) {
3201
- function wrapper(...args) {
3202
- if (fn === null) return;
3203
- var callFn = fn;
3204
- fn = null;
3205
- callFn.apply(this, args);
3206
- }
3207
- Object.assign(wrapper, fn);
3208
- return wrapper;
3209
- }
3210
- function getIterator(coll) {
3211
- return coll[Symbol.iterator] && coll[Symbol.iterator]();
3212
- }
3213
- function createArrayIterator(coll) {
3214
- var i = -1;
3215
- var len = coll.length;
3216
- return function next() {
3217
- return ++i < len ? { value: coll[i], key: i } : null;
3218
- };
3219
- }
3220
- function createES2015Iterator(iterator) {
3221
- var i = -1;
3222
- return function next() {
3223
- var item = iterator.next();
3224
- if (item.done)
3225
- return null;
3226
- i++;
3227
- return { value: item.value, key: i };
3228
- };
3229
- }
3230
- function createObjectIterator(obj) {
3231
- var okeys = obj ? Object.keys(obj) : [];
3232
- var i = -1;
3233
- var len = okeys.length;
3234
- return function next() {
3235
- var key = okeys[++i];
3236
- if (key === "__proto__") {
3237
- return next();
3238
- }
3239
- return i < len ? { value: obj[key], key } : null;
3240
- };
3241
- }
3242
- function createIterator(coll) {
3243
- if (isArrayLike(coll)) {
3244
- return createArrayIterator(coll);
3245
- }
3246
- var iterator = getIterator(coll);
3247
- return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
3248
- }
3249
- function onlyOnce(fn) {
3250
- return function(...args) {
3251
- if (fn === null) throw new Error("Callback was already called.");
3252
- var callFn = fn;
3253
- fn = null;
3254
- callFn.apply(this, args);
3255
- };
3256
- }
3257
- function asyncEachOfLimit(generator, limit, iteratee, callback) {
3258
- let done = false;
3259
- let canceled = false;
3260
- let awaiting = false;
3261
- let running = 0;
3262
- let idx = 0;
3263
- function replenish() {
3264
- if (running >= limit || awaiting || done) return;
3265
- awaiting = true;
3266
- generator.next().then(({ value, done: iterDone }) => {
3267
- if (canceled || done) return;
3268
- awaiting = false;
3269
- if (iterDone) {
3270
- done = true;
3271
- if (running <= 0) {
3272
- callback(null);
3273
- }
3274
- return;
3275
- }
3276
- running++;
3277
- iteratee(value, idx, iterateeCallback);
3278
- idx++;
3279
- replenish();
3280
- }).catch(handleError);
3281
- }
3282
- function iterateeCallback(err, result) {
3283
- running -= 1;
3284
- if (canceled) return;
3285
- if (err) return handleError(err);
3286
- if (err === false) {
3287
- done = true;
3288
- canceled = true;
3289
- return;
3290
- }
3291
- if (result === breakLoop || done && running <= 0) {
3292
- done = true;
3293
- return callback(null);
3294
- }
3295
- replenish();
3296
- }
3297
- function handleError(err) {
3298
- if (canceled) return;
3299
- awaiting = false;
3300
- done = true;
3301
- callback(err);
3302
- }
3303
- replenish();
3304
- }
3305
- function eachOfLimit(coll, limit, iteratee, callback) {
3306
- return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback);
3307
- }
3308
- function eachOfArrayLike(coll, iteratee, callback) {
3309
- callback = once(callback);
3310
- var index2 = 0, completed = 0, { length } = coll, canceled = false;
3311
- if (length === 0) {
3312
- callback(null);
3313
- }
3314
- function iteratorCallback(err, value) {
3315
- if (err === false) {
3316
- canceled = true;
3317
- }
3318
- if (canceled === true) return;
3319
- if (err) {
3320
- callback(err);
3321
- } else if (++completed === length || value === breakLoop) {
3322
- callback(null);
3323
- }
3324
- }
3325
- for (; index2 < length; index2++) {
3326
- iteratee(coll[index2], index2, onlyOnce(iteratorCallback));
3327
- }
3328
- }
3329
- function eachOfGeneric(coll, iteratee, callback) {
3330
- return eachOfLimit$1(coll, Infinity, iteratee, callback);
3331
- }
3332
- function eachOf(coll, iteratee, callback) {
3333
- var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
3334
- return eachOfImplementation(coll, wrapAsync(iteratee), callback);
3335
- }
3336
- function map(coll, iteratee, callback) {
3337
- return _asyncMap(eachOf$1, coll, iteratee, callback);
3338
- }
3339
- function eachOfSeries(coll, iteratee, callback) {
3340
- return eachOfLimit$1(coll, 1, iteratee, callback);
3341
- }
3342
- function mapSeries(coll, iteratee, callback) {
3343
- return _asyncMap(eachOfSeries$1, coll, iteratee, callback);
3344
- }
3345
- function promiseCallback() {
3346
- let resolve4, reject2;
3347
- function callback(err, ...args) {
3348
- if (err) return reject2(err);
3349
- resolve4(args.length > 1 ? args : args[0]);
3350
- }
3351
- callback[PROMISE_SYMBOL] = new Promise((res, rej) => {
3352
- resolve4 = res, reject2 = rej;
3353
- });
3354
- return callback;
3355
- }
3356
- function auto(tasks, concurrency, callback) {
3357
- if (typeof concurrency !== "number") {
3358
- callback = concurrency;
3359
- concurrency = null;
3360
- }
3361
- callback = once(callback || promiseCallback());
3362
- var numTasks = Object.keys(tasks).length;
3363
- if (!numTasks) {
3364
- return callback(null);
3365
- }
3366
- if (!concurrency) {
3367
- concurrency = numTasks;
3368
- }
3369
- var results = {};
3370
- var runningTasks = 0;
3371
- var canceled = false;
3372
- var hasError = false;
3373
- var listeners = /* @__PURE__ */ Object.create(null);
3374
- var readyTasks = [];
3375
- var readyToCheck = [];
3376
- var uncheckedDependencies = {};
3377
- Object.keys(tasks).forEach((key) => {
3378
- var task = tasks[key];
3379
- if (!Array.isArray(task)) {
3380
- enqueueTask(key, [task]);
3381
- readyToCheck.push(key);
3382
- return;
3383
- }
3384
- var dependencies = task.slice(0, task.length - 1);
3385
- var remainingDependencies = dependencies.length;
3386
- if (remainingDependencies === 0) {
3387
- enqueueTask(key, task);
3388
- readyToCheck.push(key);
3389
- return;
3390
- }
3391
- uncheckedDependencies[key] = remainingDependencies;
3392
- dependencies.forEach((dependencyName) => {
3393
- if (!tasks[dependencyName]) {
3394
- throw new Error("async.auto task `" + key + "` has a non-existent dependency `" + dependencyName + "` in " + dependencies.join(", "));
3395
- }
3396
- addListener(dependencyName, () => {
3397
- remainingDependencies--;
3398
- if (remainingDependencies === 0) {
3399
- enqueueTask(key, task);
3400
- }
3401
- });
3402
- });
3403
- });
3404
- checkForDeadlocks();
3405
- processQueue();
3406
- function enqueueTask(key, task) {
3407
- readyTasks.push(() => runTask(key, task));
3408
- }
3409
- function processQueue() {
3410
- if (canceled) return;
3411
- if (readyTasks.length === 0 && runningTasks === 0) {
3412
- return callback(null, results);
3413
- }
3414
- while (readyTasks.length && runningTasks < concurrency) {
3415
- var run = readyTasks.shift();
3416
- run();
3417
- }
3418
- }
3419
- function addListener(taskName, fn) {
3420
- var taskListeners = listeners[taskName];
3421
- if (!taskListeners) {
3422
- taskListeners = listeners[taskName] = [];
3423
- }
3424
- taskListeners.push(fn);
3425
- }
3426
- function taskComplete(taskName) {
3427
- var taskListeners = listeners[taskName] || [];
3428
- taskListeners.forEach((fn) => fn());
3429
- processQueue();
3430
- }
3431
- function runTask(key, task) {
3432
- if (hasError) return;
3433
- var taskCallback = onlyOnce((err, ...result) => {
3434
- runningTasks--;
3435
- if (err === false) {
3436
- canceled = true;
3437
- return;
3438
- }
3439
- if (result.length < 2) {
3440
- [result] = result;
3441
- }
3442
- if (err) {
3443
- var safeResults = {};
3444
- Object.keys(results).forEach((rkey) => {
3445
- safeResults[rkey] = results[rkey];
3446
- });
3447
- safeResults[key] = result;
3448
- hasError = true;
3449
- listeners = /* @__PURE__ */ Object.create(null);
3450
- if (canceled) return;
3451
- callback(err, safeResults);
3452
- } else {
3453
- results[key] = result;
3454
- taskComplete(key);
3455
- }
3456
- });
3457
- runningTasks++;
3458
- var taskFn = wrapAsync(task[task.length - 1]);
3459
- if (task.length > 1) {
3460
- taskFn(results, taskCallback);
3461
- } else {
3462
- taskFn(taskCallback);
3463
- }
3464
- }
3465
- function checkForDeadlocks() {
3466
- var currentTask;
3467
- var counter = 0;
3468
- while (readyToCheck.length) {
3469
- currentTask = readyToCheck.pop();
3470
- counter++;
3471
- getDependents(currentTask).forEach((dependent) => {
3472
- if (--uncheckedDependencies[dependent] === 0) {
3473
- readyToCheck.push(dependent);
3474
- }
3475
- });
3476
- }
3477
- if (counter !== numTasks) {
3478
- throw new Error(
3479
- "async.auto cannot execute tasks due to a recursive dependency"
3480
- );
3481
- }
3482
- }
3483
- function getDependents(taskName) {
3484
- var result = [];
3485
- Object.keys(tasks).forEach((key) => {
3486
- const task = tasks[key];
3487
- if (Array.isArray(task) && task.indexOf(taskName) >= 0) {
3488
- result.push(key);
3489
- }
3490
- });
3491
- return result;
3492
- }
3493
- return callback[PROMISE_SYMBOL];
3494
- }
3495
- function stripComments(string) {
3496
- let stripped = "";
3497
- let index2 = 0;
3498
- let endBlockComment = string.indexOf("*/");
3499
- while (index2 < string.length) {
3500
- if (string[index2] === "/" && string[index2 + 1] === "/") {
3501
- let endIndex = string.indexOf("\n", index2);
3502
- index2 = endIndex === -1 ? string.length : endIndex;
3503
- } else if (endBlockComment !== -1 && string[index2] === "/" && string[index2 + 1] === "*") {
3504
- let endIndex = string.indexOf("*/", index2);
3505
- if (endIndex !== -1) {
3506
- index2 = endIndex + 2;
3507
- endBlockComment = string.indexOf("*/", index2);
3508
- } else {
3509
- stripped += string[index2];
3510
- index2++;
3511
- }
3512
- } else {
3513
- stripped += string[index2];
3514
- index2++;
3515
- }
3516
- }
3517
- return stripped;
3518
- }
3519
- function parseParams(func) {
3520
- const src = stripComments(func.toString());
3521
- let match = src.match(FN_ARGS);
3522
- if (!match) {
3523
- match = src.match(ARROW_FN_ARGS);
3524
- }
3525
- if (!match) throw new Error("could not parse args in autoInject\nSource:\n" + src);
3526
- let [, args] = match;
3527
- return args.replace(/\s/g, "").split(FN_ARG_SPLIT).map((arg) => arg.replace(FN_ARG, "").trim());
3528
- }
3529
- function autoInject(tasks, callback) {
3530
- var newTasks = {};
3531
- Object.keys(tasks).forEach((key) => {
3532
- var taskFn = tasks[key];
3533
- var params;
3534
- var fnIsAsync = isAsync(taskFn);
3535
- var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0;
3536
- if (Array.isArray(taskFn)) {
3537
- params = [...taskFn];
3538
- taskFn = params.pop();
3539
- newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
3540
- } else if (hasNoDeps) {
3541
- newTasks[key] = taskFn;
3542
- } else {
3543
- params = parseParams(taskFn);
3544
- if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {
3545
- throw new Error("autoInject task functions require explicit parameters.");
3546
- }
3547
- if (!fnIsAsync) params.pop();
3548
- newTasks[key] = params.concat(newTask);
3549
- }
3550
- function newTask(results, taskCb) {
3551
- var newArgs = params.map((name) => results[name]);
3552
- newArgs.push(taskCb);
3553
- wrapAsync(taskFn)(...newArgs);
3554
- }
3555
- });
3556
- return auto(newTasks, callback);
3557
- }
3558
- function setInitial(dll, node) {
3559
- dll.length = 1;
3560
- dll.head = dll.tail = node;
3561
- }
3562
- function queue$1(worker, concurrency, payload) {
3563
- if (concurrency == null) {
3564
- concurrency = 1;
3565
- } else if (concurrency === 0) {
3566
- throw new RangeError("Concurrency must not be zero");
3567
- }
3568
- var _worker = wrapAsync(worker);
3569
- var numRunning = 0;
3570
- var workersList = [];
3571
- const events = {
3572
- error: [],
3573
- drain: [],
3574
- saturated: [],
3575
- unsaturated: [],
3576
- empty: []
3577
- };
3578
- function on(event, handler) {
3579
- events[event].push(handler);
3580
- }
3581
- function once2(event, handler) {
3582
- const handleAndRemove = (...args) => {
3583
- off(event, handleAndRemove);
3584
- handler(...args);
3585
- };
3586
- events[event].push(handleAndRemove);
3587
- }
3588
- function off(event, handler) {
3589
- if (!event) return Object.keys(events).forEach((ev) => events[ev] = []);
3590
- if (!handler) return events[event] = [];
3591
- events[event] = events[event].filter((ev) => ev !== handler);
3592
- }
3593
- function trigger(event, ...args) {
3594
- events[event].forEach((handler) => handler(...args));
3595
- }
3596
- var processingScheduled = false;
3597
- function _insert(data, insertAtFront, rejectOnError, callback) {
3598
- if (callback != null && typeof callback !== "function") {
3599
- throw new Error("task callback must be a function");
3600
- }
3601
- q.started = true;
3602
- var res, rej;
3603
- function promiseCallback2(err, ...args) {
3604
- if (err) return rejectOnError ? rej(err) : res();
3605
- if (args.length <= 1) return res(args[0]);
3606
- res(args);
3607
- }
3608
- var item = q._createTaskItem(
3609
- data,
3610
- rejectOnError ? promiseCallback2 : callback || promiseCallback2
3611
- );
3612
- if (insertAtFront) {
3613
- q._tasks.unshift(item);
3614
- } else {
3615
- q._tasks.push(item);
3616
- }
3617
- if (!processingScheduled) {
3618
- processingScheduled = true;
3619
- setImmediate$1(() => {
3620
- processingScheduled = false;
3621
- q.process();
3622
- });
3623
- }
3624
- if (rejectOnError || !callback) {
3625
- return new Promise((resolve4, reject2) => {
3626
- res = resolve4;
3627
- rej = reject2;
3628
- });
3629
- }
3630
- }
3631
- function _createCB(tasks) {
3632
- return function(err, ...args) {
3633
- numRunning -= 1;
3634
- for (var i = 0, l = tasks.length; i < l; i++) {
3635
- var task = tasks[i];
3636
- var index2 = workersList.indexOf(task);
3637
- if (index2 === 0) {
3638
- workersList.shift();
3639
- } else if (index2 > 0) {
3640
- workersList.splice(index2, 1);
3641
- }
3642
- task.callback(err, ...args);
3643
- if (err != null) {
3644
- trigger("error", err, task.data);
3645
- }
3646
- }
3647
- if (numRunning <= q.concurrency - q.buffer) {
3648
- trigger("unsaturated");
3649
- }
3650
- if (q.idle()) {
3651
- trigger("drain");
3652
- }
3653
- q.process();
3654
- };
3655
- }
3656
- function _maybeDrain(data) {
3657
- if (data.length === 0 && q.idle()) {
3658
- setImmediate$1(() => trigger("drain"));
3659
- return true;
3660
- }
3661
- return false;
3662
- }
3663
- const eventMethod = (name) => (handler) => {
3664
- if (!handler) {
3665
- return new Promise((resolve4, reject2) => {
3666
- once2(name, (err, data) => {
3667
- if (err) return reject2(err);
3668
- resolve4(data);
3669
- });
3670
- });
3671
- }
3672
- off(name);
3673
- on(name, handler);
3674
- };
3675
- var isProcessing = false;
3676
- var q = {
3677
- _tasks: new DLL(),
3678
- _createTaskItem(data, callback) {
3679
- return {
3680
- data,
3681
- callback
3682
- };
3683
- },
3684
- *[Symbol.iterator]() {
3685
- yield* q._tasks[Symbol.iterator]();
3686
- },
3687
- concurrency,
3688
- payload,
3689
- buffer: concurrency / 4,
3690
- started: false,
3691
- paused: false,
3692
- push(data, callback) {
3693
- if (Array.isArray(data)) {
3694
- if (_maybeDrain(data)) return;
3695
- return data.map((datum) => _insert(datum, false, false, callback));
3696
- }
3697
- return _insert(data, false, false, callback);
3698
- },
3699
- pushAsync(data, callback) {
3700
- if (Array.isArray(data)) {
3701
- if (_maybeDrain(data)) return;
3702
- return data.map((datum) => _insert(datum, false, true, callback));
3703
- }
3704
- return _insert(data, false, true, callback);
3705
- },
3706
- kill() {
3707
- off();
3708
- q._tasks.empty();
3709
- },
3710
- unshift(data, callback) {
3711
- if (Array.isArray(data)) {
3712
- if (_maybeDrain(data)) return;
3713
- return data.map((datum) => _insert(datum, true, false, callback));
3714
- }
3715
- return _insert(data, true, false, callback);
3716
- },
3717
- unshiftAsync(data, callback) {
3718
- if (Array.isArray(data)) {
3719
- if (_maybeDrain(data)) return;
3720
- return data.map((datum) => _insert(datum, true, true, callback));
3721
- }
3722
- return _insert(data, true, true, callback);
3723
- },
3724
- remove(testFn) {
3725
- q._tasks.remove(testFn);
3726
- },
3727
- process() {
3728
- if (isProcessing) {
3729
- return;
3730
- }
3731
- isProcessing = true;
3732
- while (!q.paused && numRunning < q.concurrency && q._tasks.length) {
3733
- var tasks = [], data = [];
3734
- var l = q._tasks.length;
3735
- if (q.payload) l = Math.min(l, q.payload);
3736
- for (var i = 0; i < l; i++) {
3737
- var node = q._tasks.shift();
3738
- tasks.push(node);
3739
- workersList.push(node);
3740
- data.push(node.data);
3741
- }
3742
- numRunning += 1;
3743
- if (q._tasks.length === 0) {
3744
- trigger("empty");
3745
- }
3746
- if (numRunning === q.concurrency) {
3747
- trigger("saturated");
3748
- }
3749
- var cb = onlyOnce(_createCB(tasks));
3750
- _worker(data, cb);
3751
- }
3752
- isProcessing = false;
3753
- },
3754
- length() {
3755
- return q._tasks.length;
3756
- },
3757
- running() {
3758
- return numRunning;
3759
- },
3760
- workersList() {
3761
- return workersList;
3762
- },
3763
- idle() {
3764
- return q._tasks.length + numRunning === 0;
3765
- },
3766
- pause() {
3767
- q.paused = true;
3768
- },
3769
- resume() {
3770
- if (q.paused === false) {
3771
- return;
3772
- }
3773
- q.paused = false;
3774
- setImmediate$1(q.process);
3775
- }
3776
- };
3777
- Object.defineProperties(q, {
3778
- saturated: {
3779
- writable: false,
3780
- value: eventMethod("saturated")
3781
- },
3782
- unsaturated: {
3783
- writable: false,
3784
- value: eventMethod("unsaturated")
3785
- },
3786
- empty: {
3787
- writable: false,
3788
- value: eventMethod("empty")
3789
- },
3790
- drain: {
3791
- writable: false,
3792
- value: eventMethod("drain")
3793
- },
3794
- error: {
3795
- writable: false,
3796
- value: eventMethod("error")
3797
- }
3798
- });
3799
- return q;
3800
- }
3801
- function cargo$1(worker, payload) {
3802
- return queue$1(worker, 1, payload);
3803
- }
3804
- function cargo(worker, concurrency, payload) {
3805
- return queue$1(worker, concurrency, payload);
3806
- }
3807
- function reduce(coll, memo, iteratee, callback) {
3808
- callback = once(callback);
3809
- var _iteratee = wrapAsync(iteratee);
3810
- return eachOfSeries$1(coll, (x, i, iterCb) => {
3811
- _iteratee(memo, x, (err, v) => {
3812
- memo = v;
3813
- iterCb(err);
3814
- });
3815
- }, (err) => callback(err, memo));
3816
- }
3817
- function seq(...functions) {
3818
- var _functions = functions.map(wrapAsync);
3819
- return function(...args) {
3820
- var that = this;
3821
- var cb = args[args.length - 1];
3822
- if (typeof cb == "function") {
3823
- args.pop();
3824
- } else {
3825
- cb = promiseCallback();
3826
- }
3827
- reduce$1(
3828
- _functions,
3829
- args,
3830
- (newargs, fn, iterCb) => {
3831
- fn.apply(that, newargs.concat((err, ...nextargs) => {
3832
- iterCb(err, nextargs);
3833
- }));
3834
- },
3835
- (err, results) => cb(err, ...results)
3836
- );
3837
- return cb[PROMISE_SYMBOL];
3838
- };
3839
- }
3840
- function compose(...args) {
3841
- return seq(...args.reverse());
3842
- }
3843
- function mapLimit(coll, limit, iteratee, callback) {
3844
- return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback);
3845
- }
3846
- function concatLimit(coll, limit, iteratee, callback) {
3847
- var _iteratee = wrapAsync(iteratee);
3848
- return mapLimit$1(coll, limit, (val, iterCb) => {
3849
- _iteratee(val, (err, ...args) => {
3850
- if (err) return iterCb(err);
3851
- return iterCb(err, args);
3852
- });
3853
- }, (err, mapResults) => {
3854
- var result = [];
3855
- for (var i = 0; i < mapResults.length; i++) {
3856
- if (mapResults[i]) {
3857
- result = result.concat(...mapResults[i]);
3858
- }
3859
- }
3860
- return callback(err, result);
3861
- });
3862
- }
3863
- function concat(coll, iteratee, callback) {
3864
- return concatLimit$1(coll, Infinity, iteratee, callback);
3865
- }
3866
- function concatSeries(coll, iteratee, callback) {
3867
- return concatLimit$1(coll, 1, iteratee, callback);
3868
- }
3869
- function constant$1(...args) {
3870
- return function(...ignoredArgs) {
3871
- var callback = ignoredArgs.pop();
3872
- return callback(null, ...args);
3873
- };
3874
- }
3875
- function _createTester(check, getResult) {
3876
- return (eachfn, arr, _iteratee, cb) => {
3877
- var testPassed = false;
3878
- var testResult;
3879
- const iteratee = wrapAsync(_iteratee);
3880
- eachfn(arr, (value, _, callback) => {
3881
- iteratee(value, (err, result) => {
3882
- if (err || err === false) return callback(err);
3883
- if (check(result) && !testResult) {
3884
- testPassed = true;
3885
- testResult = getResult(true, value);
3886
- return callback(null, breakLoop);
3887
- }
3888
- callback();
3889
- });
3890
- }, (err) => {
3891
- if (err) return cb(err);
3892
- cb(null, testPassed ? testResult : getResult(false));
3893
- });
3894
- };
3895
- }
3896
- function detect(coll, iteratee, callback) {
3897
- return _createTester((bool) => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback);
3898
- }
3899
- function detectLimit(coll, limit, iteratee, callback) {
3900
- return _createTester((bool) => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback);
3901
- }
3902
- function detectSeries(coll, iteratee, callback) {
3903
- return _createTester((bool) => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback);
3904
- }
3905
- function consoleFunc(name) {
3906
- return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => {
3907
- if (typeof console === "object") {
3908
- if (err) {
3909
- if (console.error) {
3910
- console.error(err);
3911
- }
3912
- } else if (console[name]) {
3913
- resultArgs.forEach((x) => console[name](x));
3914
- }
3915
- }
3916
- });
3917
- }
3918
- function doWhilst(iteratee, test, callback) {
3919
- callback = onlyOnce(callback);
3920
- var _fn = wrapAsync(iteratee);
3921
- var _test = wrapAsync(test);
3922
- var results;
3923
- function next(err, ...args) {
3924
- if (err) return callback(err);
3925
- if (err === false) return;
3926
- results = args;
3927
- _test(...args, check);
3928
- }
3929
- function check(err, truth) {
3930
- if (err) return callback(err);
3931
- if (err === false) return;
3932
- if (!truth) return callback(null, ...results);
3933
- _fn(next);
3934
- }
3935
- return check(null, true);
3936
- }
3937
- function doUntil(iteratee, test, callback) {
3938
- const _test = wrapAsync(test);
3939
- return doWhilst$1(iteratee, (...args) => {
3940
- const cb = args.pop();
3941
- _test(...args, (err, truth) => cb(err, !truth));
3942
- }, callback);
3943
- }
3944
- function _withoutIndex(iteratee) {
3945
- return (value, index2, callback) => iteratee(value, callback);
3946
- }
3947
- function eachLimit$2(coll, iteratee, callback) {
3948
- return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);
3949
- }
3950
- function eachLimit(coll, limit, iteratee, callback) {
3951
- return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
3952
- }
3953
- function eachSeries(coll, iteratee, callback) {
3954
- return eachLimit$1(coll, 1, iteratee, callback);
3955
- }
3956
- function ensureAsync(fn) {
3957
- if (isAsync(fn)) return fn;
3958
- return function(...args) {
3959
- var callback = args.pop();
3960
- var sync = true;
3961
- args.push((...innerArgs) => {
3962
- if (sync) {
3963
- setImmediate$1(() => callback(...innerArgs));
3964
- } else {
3965
- callback(...innerArgs);
3966
- }
3967
- });
3968
- fn.apply(this, args);
3969
- sync = false;
3970
- };
3971
- }
3972
- function every(coll, iteratee, callback) {
3973
- return _createTester((bool) => !bool, (res) => !res)(eachOf$1, coll, iteratee, callback);
3974
- }
3975
- function everyLimit(coll, limit, iteratee, callback) {
3976
- return _createTester((bool) => !bool, (res) => !res)(eachOfLimit$2(limit), coll, iteratee, callback);
3977
- }
3978
- function everySeries(coll, iteratee, callback) {
3979
- return _createTester((bool) => !bool, (res) => !res)(eachOfSeries$1, coll, iteratee, callback);
3980
- }
3981
- function filterArray(eachfn, arr, iteratee, callback) {
3982
- var truthValues = new Array(arr.length);
3983
- eachfn(arr, (x, index2, iterCb) => {
3984
- iteratee(x, (err, v) => {
3985
- truthValues[index2] = !!v;
3986
- iterCb(err);
3987
- });
3988
- }, (err) => {
3989
- if (err) return callback(err);
3990
- var results = [];
3991
- for (var i = 0; i < arr.length; i++) {
3992
- if (truthValues[i]) results.push(arr[i]);
3993
- }
3994
- callback(null, results);
3995
- });
3996
- }
3997
- function filterGeneric(eachfn, coll, iteratee, callback) {
3998
- var results = [];
3999
- eachfn(coll, (x, index2, iterCb) => {
4000
- iteratee(x, (err, v) => {
4001
- if (err) return iterCb(err);
4002
- if (v) {
4003
- results.push({ index: index2, value: x });
4004
- }
4005
- iterCb(err);
4006
- });
4007
- }, (err) => {
4008
- if (err) return callback(err);
4009
- callback(null, results.sort((a, b) => a.index - b.index).map((v) => v.value));
4010
- });
4011
- }
4012
- function _filter(eachfn, coll, iteratee, callback) {
4013
- var filter2 = isArrayLike(coll) ? filterArray : filterGeneric;
4014
- return filter2(eachfn, coll, wrapAsync(iteratee), callback);
4015
- }
4016
- function filter(coll, iteratee, callback) {
4017
- return _filter(eachOf$1, coll, iteratee, callback);
4018
- }
4019
- function filterLimit(coll, limit, iteratee, callback) {
4020
- return _filter(eachOfLimit$2(limit), coll, iteratee, callback);
4021
- }
4022
- function filterSeries(coll, iteratee, callback) {
4023
- return _filter(eachOfSeries$1, coll, iteratee, callback);
4024
- }
4025
- function forever(fn, errback) {
4026
- var done = onlyOnce(errback);
4027
- var task = wrapAsync(ensureAsync(fn));
4028
- function next(err) {
4029
- if (err) return done(err);
4030
- if (err === false) return;
4031
- task(next);
4032
- }
4033
- return next();
4034
- }
4035
- function groupByLimit(coll, limit, iteratee, callback) {
4036
- var _iteratee = wrapAsync(iteratee);
4037
- return mapLimit$1(coll, limit, (val, iterCb) => {
4038
- _iteratee(val, (err, key) => {
4039
- if (err) return iterCb(err);
4040
- return iterCb(err, { key, val });
4041
- });
4042
- }, (err, mapResults) => {
4043
- var result = {};
4044
- var { hasOwnProperty } = Object.prototype;
4045
- for (var i = 0; i < mapResults.length; i++) {
4046
- if (mapResults[i]) {
4047
- var { key } = mapResults[i];
4048
- var { val } = mapResults[i];
4049
- if (hasOwnProperty.call(result, key)) {
4050
- result[key].push(val);
4051
- } else {
4052
- result[key] = [val];
4053
- }
4054
- }
4055
- }
4056
- return callback(err, result);
4057
- });
4058
- }
4059
- function groupBy(coll, iteratee, callback) {
4060
- return groupByLimit$1(coll, Infinity, iteratee, callback);
4061
- }
4062
- function groupBySeries(coll, iteratee, callback) {
4063
- return groupByLimit$1(coll, 1, iteratee, callback);
4064
- }
4065
- function mapValuesLimit(obj, limit, iteratee, callback) {
4066
- callback = once(callback);
4067
- var newObj = {};
4068
- var _iteratee = wrapAsync(iteratee);
4069
- return eachOfLimit$2(limit)(obj, (val, key, next) => {
4070
- _iteratee(val, key, (err, result) => {
4071
- if (err) return next(err);
4072
- newObj[key] = result;
4073
- next(err);
4074
- });
4075
- }, (err) => callback(err, newObj));
4076
- }
4077
- function mapValues(obj, iteratee, callback) {
4078
- return mapValuesLimit$1(obj, Infinity, iteratee, callback);
4079
- }
4080
- function mapValuesSeries(obj, iteratee, callback) {
4081
- return mapValuesLimit$1(obj, 1, iteratee, callback);
4082
- }
4083
- function memoize(fn, hasher = (v) => v) {
4084
- var memo = /* @__PURE__ */ Object.create(null);
4085
- var queues = /* @__PURE__ */ Object.create(null);
4086
- var _fn = wrapAsync(fn);
4087
- var memoized = initialParams((args, callback) => {
4088
- var key = hasher(...args);
4089
- if (key in memo) {
4090
- setImmediate$1(() => callback(null, ...memo[key]));
4091
- } else if (key in queues) {
4092
- queues[key].push(callback);
4093
- } else {
4094
- queues[key] = [callback];
4095
- _fn(...args, (err, ...resultArgs) => {
4096
- if (!err) {
4097
- memo[key] = resultArgs;
4098
- }
4099
- var q = queues[key];
4100
- delete queues[key];
4101
- for (var i = 0, l = q.length; i < l; i++) {
4102
- q[i](err, ...resultArgs);
4103
- }
4104
- });
4105
- }
4106
- });
4107
- memoized.memo = memo;
4108
- memoized.unmemoized = fn;
4109
- return memoized;
4110
- }
4111
- function parallel(tasks, callback) {
4112
- return _parallel(eachOf$1, tasks, callback);
4113
- }
4114
- function parallelLimit(tasks, limit, callback) {
4115
- return _parallel(eachOfLimit$2(limit), tasks, callback);
4116
- }
4117
- function queue(worker, concurrency) {
4118
- var _worker = wrapAsync(worker);
4119
- return queue$1((items, cb) => {
4120
- _worker(items[0], cb);
4121
- }, concurrency, 1);
4122
- }
4123
- function leftChi(i) {
4124
- return (i << 1) + 1;
4125
- }
4126
- function parent(i) {
4127
- return (i + 1 >> 1) - 1;
4128
- }
4129
- function smaller(x, y) {
4130
- if (x.priority !== y.priority) {
4131
- return x.priority < y.priority;
4132
- } else {
4133
- return x.pushCount < y.pushCount;
4134
- }
4135
- }
4136
- function priorityQueue(worker, concurrency) {
4137
- var q = queue(worker, concurrency);
4138
- var {
4139
- push,
4140
- pushAsync
4141
- } = q;
4142
- q._tasks = new Heap();
4143
- q._createTaskItem = ({ data, priority }, callback) => {
4144
- return {
4145
- data,
4146
- priority,
4147
- callback
4148
- };
4149
- };
4150
- function createDataItems(tasks, priority) {
4151
- if (!Array.isArray(tasks)) {
4152
- return { data: tasks, priority };
4153
- }
4154
- return tasks.map((data) => {
4155
- return { data, priority };
4156
- });
4157
- }
4158
- q.push = function(data, priority = 0, callback) {
4159
- return push(createDataItems(data, priority), callback);
4160
- };
4161
- q.pushAsync = function(data, priority = 0, callback) {
4162
- return pushAsync(createDataItems(data, priority), callback);
4163
- };
4164
- delete q.unshift;
4165
- delete q.unshiftAsync;
4166
- return q;
4167
- }
4168
- function race(tasks, callback) {
4169
- callback = once(callback);
4170
- if (!Array.isArray(tasks)) return callback(new TypeError("First argument to race must be an array of functions"));
4171
- if (!tasks.length) return callback();
4172
- for (var i = 0, l = tasks.length; i < l; i++) {
4173
- wrapAsync(tasks[i])(callback);
4174
- }
4175
- }
4176
- function reduceRight(array, memo, iteratee, callback) {
4177
- var reversed = [...array].reverse();
4178
- return reduce$1(reversed, memo, iteratee, callback);
4179
- }
4180
- function reflect(fn) {
4181
- var _fn = wrapAsync(fn);
4182
- return initialParams(function reflectOn(args, reflectCallback) {
4183
- args.push((error, ...cbArgs) => {
4184
- let retVal = {};
4185
- if (error) {
4186
- retVal.error = error;
4187
- }
4188
- if (cbArgs.length > 0) {
4189
- var value = cbArgs;
4190
- if (cbArgs.length <= 1) {
4191
- [value] = cbArgs;
4192
- }
4193
- retVal.value = value;
4194
- }
4195
- reflectCallback(null, retVal);
4196
- });
4197
- return _fn.apply(this, args);
4198
- });
4199
- }
4200
- function reflectAll(tasks) {
4201
- var results;
4202
- if (Array.isArray(tasks)) {
4203
- results = tasks.map(reflect);
4204
- } else {
4205
- results = {};
4206
- Object.keys(tasks).forEach((key) => {
4207
- results[key] = reflect.call(this, tasks[key]);
4208
- });
4209
- }
4210
- return results;
4211
- }
4212
- function reject$2(eachfn, arr, _iteratee, callback) {
4213
- const iteratee = wrapAsync(_iteratee);
4214
- return _filter(eachfn, arr, (value, cb) => {
4215
- iteratee(value, (err, v) => {
4216
- cb(err, !v);
4217
- });
4218
- }, callback);
4219
- }
4220
- function reject(coll, iteratee, callback) {
4221
- return reject$2(eachOf$1, coll, iteratee, callback);
4222
- }
4223
- function rejectLimit(coll, limit, iteratee, callback) {
4224
- return reject$2(eachOfLimit$2(limit), coll, iteratee, callback);
4225
- }
4226
- function rejectSeries(coll, iteratee, callback) {
4227
- return reject$2(eachOfSeries$1, coll, iteratee, callback);
4228
- }
4229
- function constant(value) {
4230
- return function() {
4231
- return value;
4232
- };
4233
- }
4234
- function retry(opts, task, callback) {
4235
- var options = {
4236
- times: DEFAULT_TIMES,
4237
- intervalFunc: constant(DEFAULT_INTERVAL)
4238
- };
4239
- if (arguments.length < 3 && typeof opts === "function") {
4240
- callback = task || promiseCallback();
4241
- task = opts;
4242
- } else {
4243
- parseTimes(options, opts);
4244
- callback = callback || promiseCallback();
4245
- }
4246
- if (typeof task !== "function") {
4247
- throw new Error("Invalid arguments for async.retry");
4248
- }
4249
- var _task = wrapAsync(task);
4250
- var attempt = 1;
4251
- function retryAttempt() {
4252
- _task((err, ...args) => {
4253
- if (err === false) return;
4254
- if (err && attempt++ < options.times && (typeof options.errorFilter != "function" || options.errorFilter(err))) {
4255
- setTimeout(retryAttempt, options.intervalFunc(attempt - 1));
4256
- } else {
4257
- callback(err, ...args);
4258
- }
4259
- });
4260
- }
4261
- retryAttempt();
4262
- return callback[PROMISE_SYMBOL];
4263
- }
4264
- function parseTimes(acc, t) {
4265
- if (typeof t === "object") {
4266
- acc.times = +t.times || DEFAULT_TIMES;
4267
- acc.intervalFunc = typeof t.interval === "function" ? t.interval : constant(+t.interval || DEFAULT_INTERVAL);
4268
- acc.errorFilter = t.errorFilter;
4269
- } else if (typeof t === "number" || typeof t === "string") {
4270
- acc.times = +t || DEFAULT_TIMES;
4271
- } else {
4272
- throw new Error("Invalid arguments for async.retry");
4273
- }
4274
- }
4275
- function retryable(opts, task) {
4276
- if (!task) {
4277
- task = opts;
4278
- opts = null;
4279
- }
4280
- let arity = opts && opts.arity || task.length;
4281
- if (isAsync(task)) {
4282
- arity += 1;
4283
- }
4284
- var _task = wrapAsync(task);
4285
- return initialParams((args, callback) => {
4286
- if (args.length < arity - 1 || callback == null) {
4287
- args.push(callback);
4288
- callback = promiseCallback();
4289
- }
4290
- function taskFn(cb) {
4291
- _task(...args, cb);
4292
- }
4293
- if (opts) retry(opts, taskFn, callback);
4294
- else retry(taskFn, callback);
4295
- return callback[PROMISE_SYMBOL];
4296
- });
4297
- }
4298
- function series(tasks, callback) {
4299
- return _parallel(eachOfSeries$1, tasks, callback);
4300
- }
4301
- function some(coll, iteratee, callback) {
4302
- return _createTester(Boolean, (res) => res)(eachOf$1, coll, iteratee, callback);
4303
- }
4304
- function someLimit(coll, limit, iteratee, callback) {
4305
- return _createTester(Boolean, (res) => res)(eachOfLimit$2(limit), coll, iteratee, callback);
4306
- }
4307
- function someSeries(coll, iteratee, callback) {
4308
- return _createTester(Boolean, (res) => res)(eachOfSeries$1, coll, iteratee, callback);
4309
- }
4310
- function sortBy(coll, iteratee, callback) {
4311
- var _iteratee = wrapAsync(iteratee);
4312
- return map$1(coll, (x, iterCb) => {
4313
- _iteratee(x, (err, criteria) => {
4314
- if (err) return iterCb(err);
4315
- iterCb(err, { value: x, criteria });
4316
- });
4317
- }, (err, results) => {
4318
- if (err) return callback(err);
4319
- callback(null, results.sort(comparator).map((v) => v.value));
4320
- });
4321
- function comparator(left, right) {
4322
- var a = left.criteria, b = right.criteria;
4323
- return a < b ? -1 : a > b ? 1 : 0;
4324
- }
4325
- }
4326
- function timeout(asyncFn, milliseconds, info) {
4327
- var fn = wrapAsync(asyncFn);
4328
- return initialParams((args, callback) => {
4329
- var timedOut = false;
4330
- var timer;
4331
- function timeoutCallback() {
4332
- var name = asyncFn.name || "anonymous";
4333
- var error = new Error('Callback function "' + name + '" timed out.');
4334
- error.code = "ETIMEDOUT";
4335
- if (info) {
4336
- error.info = info;
4337
- }
4338
- timedOut = true;
4339
- callback(error);
4340
- }
4341
- args.push((...cbArgs) => {
4342
- if (!timedOut) {
4343
- callback(...cbArgs);
4344
- clearTimeout(timer);
4345
- }
4346
- });
4347
- timer = setTimeout(timeoutCallback, milliseconds);
4348
- fn(...args);
4349
- });
4350
- }
4351
- function range(size) {
4352
- var result = Array(size);
4353
- while (size--) {
4354
- result[size] = size;
4355
- }
4356
- return result;
4357
- }
4358
- function timesLimit(count, limit, iteratee, callback) {
4359
- var _iteratee = wrapAsync(iteratee);
4360
- return mapLimit$1(range(count), limit, _iteratee, callback);
4361
- }
4362
- function times(n, iteratee, callback) {
4363
- return timesLimit(n, Infinity, iteratee, callback);
4364
- }
4365
- function timesSeries(n, iteratee, callback) {
4366
- return timesLimit(n, 1, iteratee, callback);
4367
- }
4368
- function transform(coll, accumulator, iteratee, callback) {
4369
- if (arguments.length <= 3 && typeof accumulator === "function") {
4370
- callback = iteratee;
4371
- iteratee = accumulator;
4372
- accumulator = Array.isArray(coll) ? [] : {};
4373
- }
4374
- callback = once(callback || promiseCallback());
4375
- var _iteratee = wrapAsync(iteratee);
4376
- eachOf$1(coll, (v, k, cb) => {
4377
- _iteratee(accumulator, v, k, cb);
4378
- }, (err) => callback(err, accumulator));
4379
- return callback[PROMISE_SYMBOL];
4380
- }
4381
- function tryEach(tasks, callback) {
4382
- var error = null;
4383
- var result;
4384
- return eachSeries$1(tasks, (task, taskCb) => {
4385
- wrapAsync(task)((err, ...args) => {
4386
- if (err === false) return taskCb(err);
4387
- if (args.length < 2) {
4388
- [result] = args;
4389
- } else {
4390
- result = args;
4391
- }
4392
- error = err;
4393
- taskCb(err ? null : {});
4394
- });
4395
- }, () => callback(error, result));
4396
- }
4397
- function unmemoize(fn) {
4398
- return (...args) => {
4399
- return (fn.unmemoized || fn)(...args);
4400
- };
4401
- }
4402
- function whilst(test, iteratee, callback) {
4403
- callback = onlyOnce(callback);
4404
- var _fn = wrapAsync(iteratee);
4405
- var _test = wrapAsync(test);
4406
- var results = [];
4407
- function next(err, ...rest) {
4408
- if (err) return callback(err);
4409
- results = rest;
4410
- if (err === false) return;
4411
- _test(check);
4412
- }
4413
- function check(err, truth) {
4414
- if (err) return callback(err);
4415
- if (err === false) return;
4416
- if (!truth) return callback(null, ...results);
4417
- _fn(next);
4418
- }
4419
- return _test(check);
4420
- }
4421
- function until(test, iteratee, callback) {
4422
- const _test = wrapAsync(test);
4423
- return whilst$1((cb) => _test((err, truth) => cb(err, !truth)), iteratee, callback);
4424
- }
4425
- function waterfall(tasks, callback) {
4426
- callback = once(callback);
4427
- if (!Array.isArray(tasks)) return callback(new Error("First argument to waterfall must be an array of functions"));
4428
- if (!tasks.length) return callback();
4429
- var taskIndex = 0;
4430
- function nextTask(args) {
4431
- var task = wrapAsync(tasks[taskIndex++]);
4432
- task(...args, onlyOnce(next));
4433
- }
4434
- function next(err, ...args) {
4435
- if (err === false) return;
4436
- if (err || taskIndex === tasks.length) {
4437
- return callback(err, ...args);
4438
- }
4439
- nextTask(args);
4440
- }
4441
- nextTask([]);
4442
- }
4443
- var hasQueueMicrotask, hasSetImmediate, hasNextTick, _defer$1, setImmediate$1, breakLoop, eachOfLimit$2, eachOfLimit$1, eachOf$1, map$1, applyEach, eachOfSeries$1, mapSeries$1, applyEachSeries, PROMISE_SYMBOL, FN_ARGS, ARROW_FN_ARGS, FN_ARG_SPLIT, FN_ARG, DLL, reduce$1, mapLimit$1, concatLimit$1, concat$1, concatSeries$1, detect$1, detectLimit$1, detectSeries$1, dir, doWhilst$1, each, eachLimit$1, eachSeries$1, every$1, everyLimit$1, everySeries$1, filter$1, filterLimit$1, filterSeries$1, forever$1, groupByLimit$1, log, mapValuesLimit$1, _defer, nextTick, _parallel, Heap, race$1, reject$1, rejectLimit$1, rejectSeries$1, DEFAULT_TIMES, DEFAULT_INTERVAL, some$1, someLimit$1, someSeries$1, sortBy$1, tryEach$1, whilst$1, waterfall$1, index;
4444
- var init_async = __esm({
4445
- "../../../node_modules/async/dist/async.mjs"() {
4446
- "use strict";
4447
- hasQueueMicrotask = typeof queueMicrotask === "function" && queueMicrotask;
4448
- hasSetImmediate = typeof setImmediate === "function" && setImmediate;
4449
- hasNextTick = typeof process === "object" && typeof process.nextTick === "function";
4450
- if (hasQueueMicrotask) {
4451
- _defer$1 = queueMicrotask;
4452
- } else if (hasSetImmediate) {
4453
- _defer$1 = setImmediate;
4454
- } else if (hasNextTick) {
4455
- _defer$1 = process.nextTick;
4456
- } else {
4457
- _defer$1 = fallback;
4458
- }
4459
- setImmediate$1 = wrap(_defer$1);
4460
- breakLoop = {};
4461
- eachOfLimit$2 = (limit) => {
4462
- return (obj, iteratee, callback) => {
4463
- callback = once(callback);
4464
- if (limit <= 0) {
4465
- throw new RangeError("concurrency limit cannot be less than 1");
4466
- }
4467
- if (!obj) {
4468
- return callback(null);
4469
- }
4470
- if (isAsyncGenerator(obj)) {
4471
- return asyncEachOfLimit(obj, limit, iteratee, callback);
4472
- }
4473
- if (isAsyncIterable(obj)) {
4474
- return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback);
4475
- }
4476
- var nextElem = createIterator(obj);
4477
- var done = false;
4478
- var canceled = false;
4479
- var running = 0;
4480
- var looping = false;
4481
- function iterateeCallback(err, value) {
4482
- if (canceled) return;
4483
- running -= 1;
4484
- if (err) {
4485
- done = true;
4486
- callback(err);
4487
- } else if (err === false) {
4488
- done = true;
4489
- canceled = true;
4490
- } else if (value === breakLoop || done && running <= 0) {
4491
- done = true;
4492
- return callback(null);
4493
- } else if (!looping) {
4494
- replenish();
4495
- }
4496
- }
4497
- function replenish() {
4498
- looping = true;
4499
- while (running < limit && !done) {
4500
- var elem = nextElem();
4501
- if (elem === null) {
4502
- done = true;
4503
- if (running <= 0) {
4504
- callback(null);
4505
- }
4506
- return;
4507
- }
4508
- running += 1;
4509
- iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
4510
- }
4511
- looping = false;
4512
- }
4513
- replenish();
4514
- };
4515
- };
4516
- eachOfLimit$1 = awaitify(eachOfLimit, 4);
4517
- eachOf$1 = awaitify(eachOf, 3);
4518
- map$1 = awaitify(map, 3);
4519
- applyEach = applyEach$1(map$1);
4520
- eachOfSeries$1 = awaitify(eachOfSeries, 3);
4521
- mapSeries$1 = awaitify(mapSeries, 3);
4522
- applyEachSeries = applyEach$1(mapSeries$1);
4523
- PROMISE_SYMBOL = /* @__PURE__ */ Symbol("promiseCallback");
4524
- FN_ARGS = /^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/;
4525
- ARROW_FN_ARGS = /^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/;
4526
- FN_ARG_SPLIT = /,/;
4527
- FN_ARG = /(=.+)?(\s*)$/;
4528
- DLL = class {
4529
- constructor() {
4530
- this.head = this.tail = null;
4531
- this.length = 0;
4532
- }
4533
- removeLink(node) {
4534
- if (node.prev) node.prev.next = node.next;
4535
- else this.head = node.next;
4536
- if (node.next) node.next.prev = node.prev;
4537
- else this.tail = node.prev;
4538
- node.prev = node.next = null;
4539
- this.length -= 1;
4540
- return node;
4541
- }
4542
- empty() {
4543
- while (this.head) this.shift();
4544
- return this;
4545
- }
4546
- insertAfter(node, newNode) {
4547
- newNode.prev = node;
4548
- newNode.next = node.next;
4549
- if (node.next) node.next.prev = newNode;
4550
- else this.tail = newNode;
4551
- node.next = newNode;
4552
- this.length += 1;
4553
- }
4554
- insertBefore(node, newNode) {
4555
- newNode.prev = node.prev;
4556
- newNode.next = node;
4557
- if (node.prev) node.prev.next = newNode;
4558
- else this.head = newNode;
4559
- node.prev = newNode;
4560
- this.length += 1;
4561
- }
4562
- unshift(node) {
4563
- if (this.head) this.insertBefore(this.head, node);
4564
- else setInitial(this, node);
4565
- }
4566
- push(node) {
4567
- if (this.tail) this.insertAfter(this.tail, node);
4568
- else setInitial(this, node);
4569
- }
4570
- shift() {
4571
- return this.head && this.removeLink(this.head);
4572
- }
4573
- pop() {
4574
- return this.tail && this.removeLink(this.tail);
4575
- }
4576
- toArray() {
4577
- return [...this];
4578
- }
4579
- *[Symbol.iterator]() {
4580
- var cur = this.head;
4581
- while (cur) {
4582
- yield cur.data;
4583
- cur = cur.next;
4584
- }
4585
- }
4586
- remove(testFn) {
4587
- var curr = this.head;
4588
- while (curr) {
4589
- var { next } = curr;
4590
- if (testFn(curr)) {
4591
- this.removeLink(curr);
4592
- }
4593
- curr = next;
4594
- }
4595
- return this;
4596
- }
4597
- };
4598
- reduce$1 = awaitify(reduce, 4);
4599
- mapLimit$1 = awaitify(mapLimit, 4);
4600
- concatLimit$1 = awaitify(concatLimit, 4);
4601
- concat$1 = awaitify(concat, 3);
4602
- concatSeries$1 = awaitify(concatSeries, 3);
4603
- detect$1 = awaitify(detect, 3);
4604
- detectLimit$1 = awaitify(detectLimit, 4);
4605
- detectSeries$1 = awaitify(detectSeries, 3);
4606
- dir = consoleFunc("dir");
4607
- doWhilst$1 = awaitify(doWhilst, 3);
4608
- each = awaitify(eachLimit$2, 3);
4609
- eachLimit$1 = awaitify(eachLimit, 4);
4610
- eachSeries$1 = awaitify(eachSeries, 3);
4611
- every$1 = awaitify(every, 3);
4612
- everyLimit$1 = awaitify(everyLimit, 4);
4613
- everySeries$1 = awaitify(everySeries, 3);
4614
- filter$1 = awaitify(filter, 3);
4615
- filterLimit$1 = awaitify(filterLimit, 4);
4616
- filterSeries$1 = awaitify(filterSeries, 3);
4617
- forever$1 = awaitify(forever, 2);
4618
- groupByLimit$1 = awaitify(groupByLimit, 4);
4619
- log = consoleFunc("log");
4620
- mapValuesLimit$1 = awaitify(mapValuesLimit, 4);
4621
- if (hasNextTick) {
4622
- _defer = process.nextTick;
4623
- } else if (hasSetImmediate) {
4624
- _defer = setImmediate;
4625
- } else {
4626
- _defer = fallback;
4627
- }
4628
- nextTick = wrap(_defer);
4629
- _parallel = awaitify((eachfn, tasks, callback) => {
4630
- var results = isArrayLike(tasks) ? [] : {};
4631
- eachfn(tasks, (task, key, taskCb) => {
4632
- wrapAsync(task)((err, ...result) => {
4633
- if (result.length < 2) {
4634
- [result] = result;
4635
- }
4636
- results[key] = result;
4637
- taskCb(err);
4638
- });
4639
- }, (err) => callback(err, results));
4640
- }, 3);
4641
- Heap = class {
4642
- constructor() {
4643
- this.heap = [];
4644
- this.pushCount = Number.MIN_SAFE_INTEGER;
4645
- }
4646
- get length() {
4647
- return this.heap.length;
4648
- }
4649
- empty() {
4650
- this.heap = [];
4651
- return this;
4652
- }
4653
- percUp(index2) {
4654
- let p;
4655
- while (index2 > 0 && smaller(this.heap[index2], this.heap[p = parent(index2)])) {
4656
- let t = this.heap[index2];
4657
- this.heap[index2] = this.heap[p];
4658
- this.heap[p] = t;
4659
- index2 = p;
4660
- }
4661
- }
4662
- percDown(index2) {
4663
- let l;
4664
- while ((l = leftChi(index2)) < this.heap.length) {
4665
- if (l + 1 < this.heap.length && smaller(this.heap[l + 1], this.heap[l])) {
4666
- l = l + 1;
4667
- }
4668
- if (smaller(this.heap[index2], this.heap[l])) {
4669
- break;
4670
- }
4671
- let t = this.heap[index2];
4672
- this.heap[index2] = this.heap[l];
4673
- this.heap[l] = t;
4674
- index2 = l;
4675
- }
4676
- }
4677
- push(node) {
4678
- node.pushCount = ++this.pushCount;
4679
- this.heap.push(node);
4680
- this.percUp(this.heap.length - 1);
4681
- }
4682
- unshift(node) {
4683
- return this.heap.push(node);
4684
- }
4685
- shift() {
4686
- let [top] = this.heap;
4687
- this.heap[0] = this.heap[this.heap.length - 1];
4688
- this.heap.pop();
4689
- this.percDown(0);
4690
- return top;
4691
- }
4692
- toArray() {
4693
- return [...this];
4694
- }
4695
- *[Symbol.iterator]() {
4696
- for (let i = 0; i < this.heap.length; i++) {
4697
- yield this.heap[i].data;
4698
- }
4699
- }
4700
- remove(testFn) {
4701
- let j = 0;
4702
- for (let i = 0; i < this.heap.length; i++) {
4703
- if (!testFn(this.heap[i])) {
4704
- this.heap[j] = this.heap[i];
4705
- j++;
4706
- }
4707
- }
4708
- this.heap.splice(j);
4709
- for (let i = parent(this.heap.length - 1); i >= 0; i--) {
4710
- this.percDown(i);
4711
- }
4712
- return this;
4713
- }
4714
- };
4715
- race$1 = awaitify(race, 2);
4716
- reject$1 = awaitify(reject, 3);
4717
- rejectLimit$1 = awaitify(rejectLimit, 4);
4718
- rejectSeries$1 = awaitify(rejectSeries, 3);
4719
- DEFAULT_TIMES = 5;
4720
- DEFAULT_INTERVAL = 0;
4721
- some$1 = awaitify(some, 3);
4722
- someLimit$1 = awaitify(someLimit, 4);
4723
- someSeries$1 = awaitify(someSeries, 3);
4724
- sortBy$1 = awaitify(sortBy, 3);
4725
- tryEach$1 = awaitify(tryEach);
4726
- whilst$1 = awaitify(whilst, 3);
4727
- waterfall$1 = awaitify(waterfall);
4728
- index = {
4729
- apply,
4730
- applyEach,
4731
- applyEachSeries,
4732
- asyncify,
4733
- auto,
4734
- autoInject,
4735
- cargo: cargo$1,
4736
- cargoQueue: cargo,
4737
- compose,
4738
- concat: concat$1,
4739
- concatLimit: concatLimit$1,
4740
- concatSeries: concatSeries$1,
4741
- constant: constant$1,
4742
- detect: detect$1,
4743
- detectLimit: detectLimit$1,
4744
- detectSeries: detectSeries$1,
4745
- dir,
4746
- doUntil,
4747
- doWhilst: doWhilst$1,
4748
- each,
4749
- eachLimit: eachLimit$1,
4750
- eachOf: eachOf$1,
4751
- eachOfLimit: eachOfLimit$1,
4752
- eachOfSeries: eachOfSeries$1,
4753
- eachSeries: eachSeries$1,
4754
- ensureAsync,
4755
- every: every$1,
4756
- everyLimit: everyLimit$1,
4757
- everySeries: everySeries$1,
4758
- filter: filter$1,
4759
- filterLimit: filterLimit$1,
4760
- filterSeries: filterSeries$1,
4761
- forever: forever$1,
4762
- groupBy,
4763
- groupByLimit: groupByLimit$1,
4764
- groupBySeries,
4765
- log,
4766
- map: map$1,
4767
- mapLimit: mapLimit$1,
4768
- mapSeries: mapSeries$1,
4769
- mapValues,
4770
- mapValuesLimit: mapValuesLimit$1,
4771
- mapValuesSeries,
4772
- memoize,
4773
- nextTick,
4774
- parallel,
4775
- parallelLimit,
4776
- priorityQueue,
4777
- queue,
4778
- race: race$1,
4779
- reduce: reduce$1,
4780
- reduceRight,
4781
- reflect,
4782
- reflectAll,
4783
- reject: reject$1,
4784
- rejectLimit: rejectLimit$1,
4785
- rejectSeries: rejectSeries$1,
4786
- retry,
4787
- retryable,
4788
- seq,
4789
- series,
4790
- setImmediate: setImmediate$1,
4791
- some: some$1,
4792
- someLimit: someLimit$1,
4793
- someSeries: someSeries$1,
4794
- sortBy: sortBy$1,
4795
- timeout,
4796
- times,
4797
- timesLimit,
4798
- timesSeries,
4799
- transform,
4800
- tryEach: tryEach$1,
4801
- unmemoize,
4802
- until,
4803
- waterfall: waterfall$1,
4804
- whilst: whilst$1,
4805
- // aliases
4806
- all: every$1,
4807
- allLimit: everyLimit$1,
4808
- allSeries: everySeries$1,
4809
- any: some$1,
4810
- anyLimit: someLimit$1,
4811
- anySeries: someSeries$1,
4812
- find: detect$1,
4813
- findLimit: detectLimit$1,
4814
- findSeries: detectSeries$1,
4815
- flatMap: concat$1,
4816
- flatMapLimit: concatLimit$1,
4817
- flatMapSeries: concatSeries$1,
4818
- forEach: each,
4819
- forEachSeries: eachSeries$1,
4820
- forEachLimit: eachLimit$1,
4821
- forEachOf: eachOf$1,
4822
- forEachOfSeries: eachOfSeries$1,
4823
- forEachOfLimit: eachOfLimit$1,
4824
- inject: reduce$1,
4825
- foldl: reduce$1,
4826
- foldr: reduceRight,
4827
- select: filter$1,
4828
- selectLimit: filterLimit$1,
4829
- selectSeries: filterSeries$1,
4830
- wrapSync: asyncify,
4831
- during: whilst$1,
4832
- doDuring: doWhilst$1
4833
- };
4834
- }
4835
- });
4836
-
4837
- // ../../../node_modules/tmp/lib/tmp.js
4838
- var require_tmp = __commonJS({
4839
- "../../../node_modules/tmp/lib/tmp.js"(exports2, module2) {
4840
- "use strict";
4841
- var fs = require("fs");
4842
- var os = require("os");
4843
- var path = require("path");
4844
- var crypto = require("crypto");
4845
- var _c = { fs: fs.constants, os: os.constants };
4846
- var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
4847
- var TEMPLATE_PATTERN = /XXXXXX/;
4848
- var DEFAULT_TRIES = 3;
4849
- var CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR);
4850
- var IS_WIN32 = os.platform() === "win32";
4851
- var EBADF = _c.EBADF || _c.os.errno.EBADF;
4852
- var ENOENT = _c.ENOENT || _c.os.errno.ENOENT;
4853
- var DIR_MODE = 448;
4854
- var FILE_MODE = 384;
4855
- var EXIT = "exit";
4856
- var _removeObjects = [];
4857
- var FN_RMDIR_SYNC = fs.rmdirSync.bind(fs);
4858
- var _gracefulCleanup = false;
4859
- function rimraf(dirPath, callback) {
4860
- return fs.rm(dirPath, { recursive: true }, callback);
4861
- }
4862
- function FN_RIMRAF_SYNC(dirPath) {
4863
- return fs.rmSync(dirPath, { recursive: true });
4864
- }
4865
- function tmpName(options, callback) {
4866
- const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
4867
- _assertAndSanitizeOptions(opts, function(err, sanitizedOptions) {
4868
- if (err) return cb(err);
4869
- let tries = sanitizedOptions.tries;
4870
- (function _getUniqueName() {
4871
- try {
4872
- const name = _generateTmpName(sanitizedOptions);
4873
- fs.stat(name, function(err2) {
4874
- if (!err2) {
4875
- if (tries-- > 0) return _getUniqueName();
4876
- return cb(new Error("Could not get a unique tmp filename, max tries reached " + name));
4877
- }
4878
- cb(null, name);
4879
- });
4880
- } catch (err2) {
4881
- cb(err2);
4882
- }
4883
- })();
4884
- });
4885
- }
4886
- function tmpNameSync(options) {
4887
- const args = _parseArguments(options), opts = args[0];
4888
- const sanitizedOptions = _assertAndSanitizeOptionsSync(opts);
4889
- let tries = sanitizedOptions.tries;
4890
- do {
4891
- const name = _generateTmpName(sanitizedOptions);
4892
- try {
4893
- fs.statSync(name);
4894
- } catch (e) {
4895
- return name;
4896
- }
4897
- } while (tries-- > 0);
4898
- throw new Error("Could not get a unique tmp filename, max tries reached");
4899
- }
4900
- function file(options, callback) {
4901
- const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
4902
- tmpName(opts, function _tmpNameCreated(err, name) {
4903
- if (err) return cb(err);
4904
- fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) {
4905
- if (err2) return cb(err2);
4906
- if (opts.discardDescriptor) {
4907
- return fs.close(fd, function _discardCallback(possibleErr) {
4908
- return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false));
4909
- });
4910
- } else {
4911
- const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
4912
- cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false));
4913
- }
4914
- });
4915
- });
4916
- }
4917
- function fileSync(options) {
4918
- const args = _parseArguments(options), opts = args[0];
4919
- const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
4920
- const name = tmpNameSync(opts);
4921
- let fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
4922
- if (opts.discardDescriptor) {
4923
- fs.closeSync(fd);
4924
- fd = void 0;
4925
- }
4926
- return {
4927
- name,
4928
- fd,
4929
- removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true)
4930
- };
4931
- }
4932
- function dir2(options, callback) {
4933
- const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
4934
- tmpName(opts, function _tmpNameCreated(err, name) {
4935
- if (err) return cb(err);
4936
- fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) {
4937
- if (err2) return cb(err2);
4938
- cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false));
4939
- });
4940
- });
4941
- }
4942
- function dirSync(options) {
4943
- const args = _parseArguments(options), opts = args[0];
4944
- const name = tmpNameSync(opts);
4945
- fs.mkdirSync(name, opts.mode || DIR_MODE);
4946
- return {
4947
- name,
4948
- removeCallback: _prepareTmpDirRemoveCallback(name, opts, true)
4949
- };
4950
- }
4951
- function _removeFileAsync(fdPath, next) {
4952
- const _handler = function(err) {
4953
- if (err && !_isENOENT(err)) {
4954
- return next(err);
4955
- }
4956
- next();
4957
- };
4958
- if (0 <= fdPath[0])
4959
- fs.close(fdPath[0], function() {
4960
- fs.unlink(fdPath[1], _handler);
4961
- });
4962
- else fs.unlink(fdPath[1], _handler);
4963
- }
4964
- function _removeFileSync(fdPath) {
4965
- let rethrownException = null;
4966
- try {
4967
- if (0 <= fdPath[0]) fs.closeSync(fdPath[0]);
4968
- } catch (e) {
4969
- if (!_isEBADF(e) && !_isENOENT(e)) throw e;
4970
- } finally {
4971
- try {
4972
- fs.unlinkSync(fdPath[1]);
4973
- } catch (e) {
4974
- if (!_isENOENT(e)) rethrownException = e;
4975
- }
4976
- }
4977
- if (rethrownException !== null) {
4978
- throw rethrownException;
4979
- }
4980
- }
4981
- function _prepareTmpFileRemoveCallback(name, fd, opts, sync) {
4982
- const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync);
4983
- const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync);
4984
- if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
4985
- return sync ? removeCallbackSync : removeCallback;
4986
- }
4987
- function _prepareTmpDirRemoveCallback(name, opts, sync) {
4988
- const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs);
4989
- const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC;
4990
- const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync);
4991
- const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync);
4992
- if (!opts.keep) _removeObjects.unshift(removeCallbackSync);
4993
- return sync ? removeCallbackSync : removeCallback;
4994
- }
4995
- function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) {
4996
- let called = false;
4997
- return function _cleanupCallback(next) {
4998
- if (!called) {
4999
- const toRemove = cleanupCallbackSync || _cleanupCallback;
5000
- const index2 = _removeObjects.indexOf(toRemove);
5001
- if (index2 >= 0) _removeObjects.splice(index2, 1);
5002
- called = true;
5003
- if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) {
5004
- return removeFunction(fileOrDirName);
5005
- } else {
5006
- return removeFunction(fileOrDirName, next || function() {
5007
- });
5008
- }
5009
- }
5010
- };
5011
- }
5012
- function _garbageCollector() {
5013
- if (!_gracefulCleanup) return;
5014
- while (_removeObjects.length) {
5015
- try {
5016
- _removeObjects[0]();
5017
- } catch (e) {
5018
- }
5019
- }
5020
- }
5021
- function _randomChars(howMany) {
5022
- let value = [], rnd = null;
5023
- try {
5024
- rnd = crypto.randomBytes(howMany);
5025
- } catch (e) {
5026
- rnd = crypto.pseudoRandomBytes(howMany);
5027
- }
5028
- for (let i = 0; i < howMany; i++) {
5029
- value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);
5030
- }
5031
- return value.join("");
5032
- }
5033
- function _isUndefined(obj) {
5034
- return typeof obj === "undefined";
5035
- }
5036
- function _parseArguments(options, callback) {
5037
- if (typeof options === "function") {
5038
- return [{}, options];
5039
- }
5040
- if (_isUndefined(options)) {
5041
- return [{}, callback];
5042
- }
5043
- const actualOptions = {};
5044
- for (const key of Object.getOwnPropertyNames(options)) {
5045
- actualOptions[key] = options[key];
5046
- }
5047
- return [actualOptions, callback];
5048
- }
5049
- function _resolvePath(name, tmpDir, cb) {
5050
- const pathToResolve = path.isAbsolute(name) ? name : path.join(tmpDir, name);
5051
- fs.stat(pathToResolve, function(err) {
5052
- if (err) {
5053
- fs.realpath(path.dirname(pathToResolve), function(err2, parentDir) {
5054
- if (err2) return cb(err2);
5055
- cb(null, path.join(parentDir, path.basename(pathToResolve)));
5056
- });
5057
- } else {
5058
- fs.realpath(pathToResolve, cb);
5059
- }
5060
- });
5061
- }
5062
- function _resolvePathSync(name, tmpDir) {
5063
- const pathToResolve = path.isAbsolute(name) ? name : path.join(tmpDir, name);
5064
- try {
5065
- fs.statSync(pathToResolve);
5066
- return fs.realpathSync(pathToResolve);
5067
- } catch (_err) {
5068
- const parentDir = fs.realpathSync(path.dirname(pathToResolve));
5069
- return path.join(parentDir, path.basename(pathToResolve));
5070
- }
5071
- }
5072
- function _generateTmpName(opts) {
5073
- const tmpDir = opts.tmpdir;
5074
- if (!_isUndefined(opts.name)) {
5075
- return path.join(tmpDir, opts.dir, opts.name);
5076
- }
5077
- if (!_isUndefined(opts.template)) {
5078
- return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6));
5079
- }
5080
- const name = [
5081
- opts.prefix ? opts.prefix : "tmp",
5082
- "-",
5083
- process.pid,
5084
- "-",
5085
- _randomChars(12),
5086
- opts.postfix ? "-" + opts.postfix : ""
5087
- ].join("");
5088
- return path.join(tmpDir, opts.dir, name);
5089
- }
5090
- function _assertOptionsBase(options) {
5091
- if (!_isUndefined(options.name)) {
5092
- const name = options.name;
5093
- if (path.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`);
5094
- const basename3 = path.basename(name);
5095
- if (basename3 === ".." || basename3 === "." || basename3 !== name)
5096
- throw new Error(`name option must not contain a path, found "${name}".`);
5097
- }
5098
- if (!_isUndefined(options.template) && !options.template.match(TEMPLATE_PATTERN)) {
5099
- throw new Error(`Invalid template, found "${options.template}".`);
5100
- }
5101
- if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) {
5102
- throw new Error(`Invalid tries, found "${options.tries}".`);
5103
- }
5104
- options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1;
5105
- options.keep = !!options.keep;
5106
- options.detachDescriptor = !!options.detachDescriptor;
5107
- options.discardDescriptor = !!options.discardDescriptor;
5108
- options.unsafeCleanup = !!options.unsafeCleanup;
5109
- options.prefix = _isUndefined(options.prefix) ? "" : options.prefix;
5110
- options.postfix = _isUndefined(options.postfix) ? "" : options.postfix;
5111
- }
5112
- function _getRelativePath(option, name, tmpDir, cb) {
5113
- if (_isUndefined(name)) return cb(null);
5114
- _resolvePath(name, tmpDir, function(err, resolvedPath) {
5115
- if (err) return cb(err);
5116
- const relativePath = path.relative(tmpDir, resolvedPath);
5117
- if (!resolvedPath.startsWith(tmpDir)) {
5118
- return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`));
5119
- }
5120
- cb(null, relativePath);
5121
- });
5122
- }
5123
- function _getRelativePathSync(option, name, tmpDir) {
5124
- if (_isUndefined(name)) return;
5125
- const resolvedPath = _resolvePathSync(name, tmpDir);
5126
- const relativePath = path.relative(tmpDir, resolvedPath);
5127
- if (!resolvedPath.startsWith(tmpDir)) {
5128
- throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`);
5129
- }
5130
- return relativePath;
5131
- }
5132
- function _assertAndSanitizeOptions(options, cb) {
5133
- _getTmpDir(options, function(err, tmpDir) {
5134
- if (err) return cb(err);
5135
- options.tmpdir = tmpDir;
5136
- try {
5137
- _assertOptionsBase(options, tmpDir);
5138
- } catch (err2) {
5139
- return cb(err2);
5140
- }
5141
- _getRelativePath("dir", options.dir, tmpDir, function(err2, dir3) {
5142
- if (err2) return cb(err2);
5143
- options.dir = _isUndefined(dir3) ? "" : dir3;
5144
- _getRelativePath("template", options.template, tmpDir, function(err3, template) {
5145
- if (err3) return cb(err3);
5146
- options.template = template;
5147
- cb(null, options);
5148
- });
5149
- });
5150
- });
5151
- }
5152
- function _assertAndSanitizeOptionsSync(options) {
5153
- const tmpDir = options.tmpdir = _getTmpDirSync(options);
5154
- _assertOptionsBase(options, tmpDir);
5155
- const dir3 = _getRelativePathSync("dir", options.dir, tmpDir);
5156
- options.dir = _isUndefined(dir3) ? "" : dir3;
5157
- options.template = _getRelativePathSync("template", options.template, tmpDir);
5158
- return options;
5159
- }
5160
- function _isEBADF(error) {
5161
- return _isExpectedError(error, -EBADF, "EBADF");
5162
- }
5163
- function _isENOENT(error) {
5164
- return _isExpectedError(error, -ENOENT, "ENOENT");
5165
- }
5166
- function _isExpectedError(error, errno, code) {
5167
- return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno;
5168
- }
5169
- function setGracefulCleanup() {
5170
- _gracefulCleanup = true;
5171
- }
5172
- function _getTmpDir(options, cb) {
5173
- return fs.realpath(options && options.tmpdir || os.tmpdir(), cb);
5174
- }
5175
- function _getTmpDirSync(options) {
5176
- return fs.realpathSync(options && options.tmpdir || os.tmpdir());
5177
- }
5178
- process.addListener(EXIT, _garbageCollector);
5179
- Object.defineProperty(module2.exports, "tmpdir", {
5180
- enumerable: true,
5181
- configurable: false,
5182
- get: function() {
5183
- return _getTmpDirSync();
5184
- }
5185
- });
5186
- module2.exports.dir = dir2;
5187
- module2.exports.dirSync = dirSync;
5188
- module2.exports.file = file;
5189
- module2.exports.fileSync = fileSync;
5190
- module2.exports.tmpName = tmpName;
5191
- module2.exports.tmpNameSync = tmpNameSync;
5192
- module2.exports.setGracefulCleanup = setGracefulCleanup;
5193
- }
5194
- });
5195
-
5196
- // ../../../node_modules/libreoffice-convert/index.js
5197
- var require_libreoffice_convert = __commonJS({
5198
- "../../../node_modules/libreoffice-convert/index.js"(exports2, module2) {
5199
- "use strict";
5200
- var fs = require("fs");
5201
- var path = require("path");
5202
- var url = require("url");
5203
- var async = (init_async(), __toCommonJS(async_exports));
5204
- var tmp = require_tmp();
5205
- var { execFile } = require("child_process");
5206
- var convertWithOptions = (document, format, filter2, options, callback) => {
5207
- const tmpOptions = (options || {}).tmpOptions || {};
5208
- const asyncOptions = (options || {}).asyncOptions || {};
5209
- const execOptions = (options || {}).execOptions || {};
5210
- const fileName = (options || {}).fileName || "source";
5211
- const sofficeAdditionalArgs = (options || {}).sofficeAdditionalArgs || [];
5212
- const tempDir = tmp.dirSync({ prefix: "libreofficeConvert_", unsafeCleanup: true, ...tmpOptions });
5213
- const installDir = tmp.dirSync({ prefix: "soffice", unsafeCleanup: true, ...tmpOptions });
5214
- return async.auto({
5215
- soffice: (callback2) => {
5216
- let paths = (options || {}).sofficeBinaryPaths || [];
5217
- switch (process.platform) {
5218
- case "darwin":
5219
- paths = [...paths, "/Applications/LibreOffice.app/Contents/MacOS/soffice"];
5220
- break;
5221
- case "linux":
5222
- paths = [...paths, "/usr/bin/libreoffice", "/usr/bin/soffice", "/snap/bin/libreoffice", "/opt/libreoffice/program/soffice", "/opt/libreoffice7.6/program/soffice"];
5223
- break;
5224
- case "win32":
5225
- paths = [
5226
- ...paths,
5227
- path.join(process.env["PROGRAMFILES(X86)"] || "", "LIBREO~1/program/soffice.exe"),
5228
- path.join(process.env["PROGRAMFILES(X86)"] || "", "LibreOffice/program/soffice.exe"),
5229
- path.join(process.env.PROGRAMFILES_X86 || "", "LibreOffice/program/soffice.exe"),
5230
- path.join(process.env.PROGRAMFILES || "", "LibreOffice/program/soffice.exe"),
5231
- process.env.LIBRE_OFFICE_EXE || "",
5232
- "C:/Program Files/LibreOffice/program/soffice.exe"
5233
- ];
5234
- break;
5235
- default:
5236
- return callback2(new Error(`Operating system not yet supported: ${process.platform}`));
5237
- }
5238
- return async.filter(
5239
- paths,
5240
- (filePath, callback3) => fs.access(filePath, (err) => callback3(null, !err)),
5241
- (err, res) => {
5242
- if (res.length === 0) {
5243
- return callback2(new Error("Could not find soffice binary"));
5244
- }
5245
- return callback2(null, res[0]);
5246
- }
5247
- );
5248
- },
5249
- saveSource: (callback2) => fs.writeFile(path.join(tempDir.name, fileName), document, callback2),
5250
- convert: ["soffice", "saveSource", (results, callback2) => {
5251
- let filterParam = filter2?.length ? `:${filter2}` : "";
5252
- let fmt = !(filter2 ?? "").includes(" ") ? `${format}${filterParam}` : `"${format}${filterParam}"`;
5253
- let args = [];
5254
- args.push(`-env:UserInstallation=${url.pathToFileURL(installDir.name)}`);
5255
- args.push("--headless");
5256
- args.push("--convert-to");
5257
- args.push(fmt);
5258
- args.push("--outdir");
5259
- args.push(tempDir.name);
5260
- args.push(...sofficeAdditionalArgs);
5261
- args.push(path.join(tempDir.name, fileName));
5262
- return execFile(results.soffice, args, execOptions, (err, stdout, stderr) => {
5263
- if (stderr && stderr.toLowerCase().includes("error"))
5264
- callback2(new Error("Error calling soffice: " + stderr));
5265
- else callback2(err, stdout, stderr);
5266
- });
5267
- }],
5268
- loadDestination: [
5269
- "convert",
5270
- (results, callback2) => async.retry({
5271
- times: asyncOptions.times || 3,
5272
- interval: asyncOptions.interval || 200
5273
- }, (callback3) => fs.readFile(path.join(tempDir.name, `${fileName.slice(0, fileName.length - path.extname(fileName).length)}.${format.split(":")[0]}`), callback3), callback2)
5274
- ]
5275
- }).then((res) => {
5276
- return callback(null, res.loadDestination);
5277
- }).catch((err) => {
5278
- return callback(err);
5279
- }).finally(() => {
5280
- tempDir.removeCallback();
5281
- installDir.removeCallback();
5282
- });
5283
- };
5284
- var convert = (document, format, filter2, callback) => {
5285
- return convertWithOptions(document, format, filter2, {}, callback);
5286
- };
5287
- module2.exports = {
5288
- convert,
5289
- convertWithOptions
5290
- };
5291
- }
5292
- });
5293
-
5294
2980
  // src/index.ts
5295
2981
  var index_exports = {};
5296
2982
  __export(index_exports, {
@@ -5764,7 +3450,7 @@ async function extractHwpxStyles(zip, decompressed) {
5764
3450
  }
5765
3451
  return result;
5766
3452
  }
5767
- function parseCharProperties(doc, map2) {
3453
+ function parseCharProperties(doc, map) {
5768
3454
  const tagNames = ["hh:charPr", "charPr", "hp:charPr"];
5769
3455
  for (const tagName of tagNames) {
5770
3456
  const elements = doc.getElementsByTagName(tagName);
@@ -5791,11 +3477,11 @@ function parseCharProperties(doc, map2) {
5791
3477
  }
5792
3478
  }
5793
3479
  }
5794
- map2.set(id, prop);
3480
+ map.set(id, prop);
5795
3481
  }
5796
3482
  }
5797
3483
  }
5798
- function parseStyleElements(doc, map2) {
3484
+ function parseStyleElements(doc, map) {
5799
3485
  const tagNames = ["hh:style", "style", "hp:style"];
5800
3486
  for (const tagName of tagNames) {
5801
3487
  const elements = doc.getElementsByTagName(tagName);
@@ -5805,7 +3491,7 @@ function parseStyleElements(doc, map2) {
5805
3491
  const name = el.getAttribute("name") || el.getAttribute("engName") || "";
5806
3492
  const charPrId = el.getAttribute("charPrIDRef") || void 0;
5807
3493
  const paraPrId = el.getAttribute("paraPrIDRef") || void 0;
5808
- map2.set(id, { name, charPrId, paraPrId });
3494
+ map.set(id, { name, charPrId, paraPrId });
5809
3495
  }
5810
3496
  }
5811
3497
  }
@@ -6331,9 +4017,9 @@ function walkParagraphChildren(node, blocks, tableCtx, tableStack, styleMap, war
6331
4017
  if (depth > MAX_XML_DEPTH) return tableCtx;
6332
4018
  const children = node.childNodes;
6333
4019
  if (!children) return tableCtx;
6334
- const walkChildren = (parent2, d) => {
4020
+ const walkChildren = (parent, d) => {
6335
4021
  if (d > MAX_XML_DEPTH) return;
6336
- const kids = parent2.childNodes;
4022
+ const kids = parent.childNodes;
6337
4023
  if (!kids) return;
6338
4024
  for (let i = 0; i < kids.length; i++) {
6339
4025
  const el = kids[i];
@@ -8546,17 +6232,17 @@ function lineOverlapRatio(a1, a2, b1, b2) {
8546
6232
  return overlap / target;
8547
6233
  }
8548
6234
  function groupConnectedLines(lines) {
8549
- const parent2 = lines.map((_, i) => i);
6235
+ const parent = lines.map((_, i) => i);
8550
6236
  function find2(x) {
8551
- while (parent2[x] !== x) {
8552
- parent2[x] = parent2[parent2[x]];
8553
- x = parent2[x];
6237
+ while (parent[x] !== x) {
6238
+ parent[x] = parent[parent[x]];
6239
+ x = parent[x];
8554
6240
  }
8555
6241
  return x;
8556
6242
  }
8557
6243
  function union(a, b) {
8558
6244
  const ra = find2(a), rb = find2(b);
8559
- if (ra !== rb) parent2[ra] = rb;
6245
+ if (ra !== rb) parent[ra] = rb;
8560
6246
  }
8561
6247
  for (let i = 0; i < lines.length; i++) {
8562
6248
  for (let j = i + 1; j < lines.length; j++) {
@@ -8977,10 +6663,10 @@ async function loadPdfWithTimeout(buffer) {
8977
6663
  try {
8978
6664
  return await Promise.race([
8979
6665
  loadingTask.promise,
8980
- new Promise((_, reject2) => {
6666
+ new Promise((_, reject) => {
8981
6667
  timer = setTimeout(() => {
8982
6668
  loadingTask.destroy();
8983
- reject2(new KordocError(`PDF \uB85C\uB529 \uD0C0\uC784\uC544\uC6C3 (${timeoutSec}\uCD08 \uCD08\uACFC)`));
6669
+ reject(new KordocError(`PDF \uB85C\uB529 \uD0C0\uC784\uC544\uC6C3 (${timeoutSec}\uCD08 \uCD08\uACFC)`));
8984
6670
  }, timeoutMs);
8985
6671
  })
8986
6672
  ]);
@@ -9169,10 +6855,10 @@ async function parsePdfDocument(buffer, options) {
9169
6855
  }
9170
6856
  const { resolveOcrProvider: resolveOcrProvider2 } = await Promise.resolve().then(() => (init_resolve(), resolve_exports));
9171
6857
  const { ocrPages: ocrPages2 } = await Promise.resolve().then(() => (init_provider(), provider_exports));
9172
- const tryProvider = async (provider, filter2) => {
6858
+ const tryProvider = async (provider, filter) => {
9173
6859
  try {
9174
- logger.log({ level: "debug", stage: "ocr", event: "progress", message: "OCR provider \uC2E4\uD589", meta: { filteredPages: filter2?.size } });
9175
- return await ocrPages2(doc, provider, filter2, effectivePageCount, warnings, concurrency, options?.onProgress);
6860
+ logger.log({ level: "debug", stage: "ocr", event: "progress", message: "OCR provider \uC2E4\uD589", meta: { filteredPages: filter?.size } });
6861
+ return await ocrPages2(doc, provider, filter, effectivePageCount, warnings, concurrency, options?.onProgress);
9176
6862
  } catch {
9177
6863
  logger.log({ level: "warn", stage: "ocr", event: "progress", message: "OCR provider \uC2E4\uD589 \uC2E4\uD328(\uBE48 \uACB0\uACFC\uB85C \uCC98\uB9AC)" });
9178
6864
  return [];
@@ -10187,8 +7873,8 @@ function parseMergeRef(ref) {
10187
7873
  if (!start || !end) return null;
10188
7874
  return { startCol: start.col, startRow: start.row, endCol: end.col, endRow: end.row };
10189
7875
  }
10190
- function getElements(parent2, tagName) {
10191
- const nodes = parent2.getElementsByTagName(tagName);
7876
+ function getElements(parent, tagName) {
7877
+ const nodes = parent.getElementsByTagName(tagName);
10192
7878
  const result = [];
10193
7879
  for (let i = 0; i < nodes.length; i++) result.push(nodes[i]);
10194
7880
  return result;
@@ -10224,14 +7910,14 @@ function parseWorkbook(xml) {
10224
7910
  }
10225
7911
  function parseRels(xml) {
10226
7912
  const doc = parseXml(xml);
10227
- const map2 = /* @__PURE__ */ new Map();
7913
+ const map = /* @__PURE__ */ new Map();
10228
7914
  const rels = getElements(doc.documentElement, "Relationship");
10229
7915
  for (const rel of rels) {
10230
7916
  const id = rel.getAttribute("Id");
10231
7917
  const target = rel.getAttribute("Target");
10232
- if (id && target) map2.set(id, target);
7918
+ if (id && target) map.set(id, target);
10233
7919
  }
10234
- return map2;
7920
+ return map;
10235
7921
  }
10236
7922
  function parseWorksheet(xml, sharedStrings) {
10237
7923
  const doc = parseXml(xml);
@@ -10489,9 +8175,9 @@ var import_jszip4 = __toESM(require("jszip"), 1);
10489
8175
  var import_xmldom3 = require("@xmldom/xmldom");
10490
8176
  init_logger();
10491
8177
  var MAX_DECOMPRESS_SIZE4 = 500 * 1024 * 1024;
10492
- function getChildElements(parent2, localName) {
8178
+ function getChildElements(parent, localName) {
10493
8179
  const result = [];
10494
- const children = parent2.childNodes;
8180
+ const children = parent.childNodes;
10495
8181
  for (let i = 0; i < children.length; i++) {
10496
8182
  const node = children[i];
10497
8183
  if (node.nodeType === 1) {
@@ -10503,7 +8189,7 @@ function getChildElements(parent2, localName) {
10503
8189
  }
10504
8190
  return result;
10505
8191
  }
10506
- function findElements(parent2, localName) {
8192
+ function findElements(parent, localName) {
10507
8193
  const result = [];
10508
8194
  const walk = (node) => {
10509
8195
  const children = node.childNodes;
@@ -10518,7 +8204,7 @@ function findElements(parent2, localName) {
10518
8204
  }
10519
8205
  }
10520
8206
  };
10521
- walk(parent2);
8207
+ walk(parent);
10522
8208
  return result;
10523
8209
  }
10524
8210
  function getAttr(el, localName) {
@@ -10533,7 +8219,7 @@ function parseXml2(text) {
10533
8219
  return new import_xmldom3.DOMParser().parseFromString(text, "text/xml");
10534
8220
  }
10535
8221
  function buildElementIndex(root) {
10536
- const index2 = /* @__PURE__ */ new Map();
8222
+ const index = /* @__PURE__ */ new Map();
10537
8223
  const walk = (node) => {
10538
8224
  const children = node.childNodes;
10539
8225
  for (let i = 0; i < children.length; i++) {
@@ -10542,10 +8228,10 @@ function buildElementIndex(root) {
10542
8228
  const el = child;
10543
8229
  const name = el.localName ?? "";
10544
8230
  if (name) {
10545
- let list = index2.get(name);
8231
+ let list = index.get(name);
10546
8232
  if (!list) {
10547
8233
  list = [];
10548
- index2.set(name, list);
8234
+ index.set(name, list);
10549
8235
  }
10550
8236
  list.push(el);
10551
8237
  }
@@ -10554,7 +8240,7 @@ function buildElementIndex(root) {
10554
8240
  }
10555
8241
  };
10556
8242
  walk(root);
10557
- return index2;
8243
+ return index;
10558
8244
  }
10559
8245
  function parseStyles(xml) {
10560
8246
  const doc = parseXml2(xml);
@@ -10620,14 +8306,14 @@ function parseNumbering(xml) {
10620
8306
  }
10621
8307
  function parseRels2(xml) {
10622
8308
  const doc = parseXml2(xml);
10623
- const map2 = /* @__PURE__ */ new Map();
8309
+ const map = /* @__PURE__ */ new Map();
10624
8310
  const rels = findElements(doc, "Relationship");
10625
8311
  for (const rel of rels) {
10626
8312
  const id = getAttr(rel, "Id");
10627
8313
  const target = getAttr(rel, "Target");
10628
- if (id && target) map2.set(id, target);
8314
+ if (id && target) map.set(id, target);
10629
8315
  }
10630
- return map2;
8316
+ return map;
10631
8317
  }
10632
8318
  function parseFootnotes(xml) {
10633
8319
  const doc = parseXml2(xml);
@@ -12470,22 +10156,22 @@ function findCharPrByCharacteristic(charPrMap, characteristic) {
12470
10156
  italic: { minHeight: 800, maxHeight: 1100, needBold: false },
12471
10157
  normal: { minHeight: 900, maxHeight: 1100, needBold: false }
12472
10158
  };
12473
- const range2 = ranges[characteristic];
12474
- if (!range2) return null;
10159
+ const range = ranges[characteristic];
10160
+ if (!range) return null;
12475
10161
  let bestMatch = null;
12476
10162
  let bestScore = 0;
12477
10163
  for (const [id, prop] of charPrMap) {
12478
10164
  let score = 0;
12479
10165
  if (prop.height) {
12480
- if (prop.height >= range2.minHeight && prop.height <= range2.maxHeight) {
10166
+ if (prop.height >= range.minHeight && prop.height <= range.maxHeight) {
12481
10167
  score += 50;
12482
- } else if (Math.abs(prop.height - (range2.minHeight + range2.maxHeight) / 2) < 100) {
10168
+ } else if (Math.abs(prop.height - (range.minHeight + range.maxHeight) / 2) < 100) {
12483
10169
  score += 20;
12484
10170
  }
12485
10171
  }
12486
- if (range2.needBold !== void 0) {
12487
- if (range2.needBold && prop.bold) score += 30;
12488
- else if (!range2.needBold && !prop.bold) score += 20;
10172
+ if (range.needBold !== void 0) {
10173
+ if (range.needBold && prop.bold) score += 30;
10174
+ else if (!range.needBold && !prop.bold) score += 20;
12489
10175
  }
12490
10176
  if (characteristic === "italic" && prop.italic) score += 20;
12491
10177
  if (score > bestScore) {
@@ -13324,10 +11010,10 @@ function mimeToExtension(mimeType) {
13324
11010
  return "png";
13325
11011
  }
13326
11012
  function buildImageMap(images) {
13327
- const map2 = /* @__PURE__ */ new Map();
13328
- if (!images) return map2;
13329
- for (const img of images) map2.set(img.filename, img);
13330
- return map2;
11013
+ const map = /* @__PURE__ */ new Map();
11014
+ if (!images) return map;
11015
+ for (const img of images) map.set(img.filename, img);
11016
+ return map;
13331
11017
  }
13332
11018
  async function fillBodySheet(sheet, workbook, blocks, imageMap) {
13333
11019
  sheet.getColumn(1).width = 80;
@@ -13529,8 +11215,8 @@ var ApiKeyRotationPool = class _ApiKeyRotationPool {
13529
11215
  const s = this.find(keyId);
13530
11216
  s.failureCount++;
13531
11217
  s.consecutiveFailures++;
13532
- const retryable2 = this.isRetryableFailure(opts.status, opts.timeout);
13533
- if (!retryable2) return;
11218
+ const retryable = this.isRetryableFailure(opts.status, opts.timeout);
11219
+ if (!retryable) return;
13534
11220
  const exp = Math.max(0, s.consecutiveFailures - 1);
13535
11221
  const backoff = Math.min(this.baseCooldownMs * 2 ** exp, this.maxCooldownMs);
13536
11222
  const cooldown = Math.max(backoff, opts.retryAfterMs ?? 0);
@@ -13547,8 +11233,8 @@ var ApiKeyRotationPool = class _ApiKeyRotationPool {
13547
11233
  cooldownUntil: s.cooldownUntil
13548
11234
  }));
13549
11235
  }
13550
- isRetryableFailure(status, timeout2) {
13551
- if (timeout2) return true;
11236
+ isRetryableFailure(status, timeout) {
11237
+ if (timeout) return true;
13552
11238
  if (status === 429) return true;
13553
11239
  if (typeof status === "number" && status >= 500) return true;
13554
11240
  return false;
@@ -13565,169 +11251,69 @@ var import_promises2 = require("fs/promises");
13565
11251
  var import_path5 = require("path");
13566
11252
  var import_child_process4 = require("child_process");
13567
11253
  var import_node_perf_hooks = require("perf_hooks");
11254
+ var import_libreoffice_convert = __toESM(require("libreoffice-convert"), 1);
13568
11255
  init_logger();
13569
11256
 
13570
- // src/setup/detect.ts
13571
- var import_node_child_process = require("child_process");
13572
- var import_node_fs = require("fs");
13573
- var import_node_path = require("path");
13574
- var isWin = process.platform === "win32";
13575
- function which(cmd) {
13576
- const finder = isWin ? "where" : "which";
13577
- const r = (0, import_node_child_process.spawnSync)(finder, [cmd], { encoding: "utf8", shell: isWin });
13578
- if (r.status !== 0) return void 0;
13579
- return r.stdout.split(/\r?\n/).find(Boolean)?.trim();
13580
- }
13581
- function resolveCmd(cmd, envKey) {
13582
- const override = process.env[envKey];
13583
- if (override) return override;
13584
- const found = which(cmd);
13585
- if (found) return found;
13586
- if (isWin) return findWinCandidate(cmd);
13587
- return void 0;
13588
- }
13589
- function findWinCandidate(cmd) {
13590
- const exe = cmd.endsWith(".exe") ? cmd : `${cmd}.exe`;
13591
- const userProfile = process.env["USERPROFILE"] ?? "C:\\Users\\Default";
13592
- const localAppData = process.env["LOCALAPPDATA"] ?? (0, import_node_path.join)(userProfile, "AppData", "Local");
13593
- const programFiles = process.env["ProgramFiles"] ?? "C:\\Program Files";
13594
- const programFilesX86 = process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)";
13595
- const isPopplerExe = ["pdftoppm.exe", "pdfinfo.exe", "pdftotext.exe"].includes(exe);
13596
- const isSoffice = exe === "soffice.exe";
13597
- if (isPopplerExe) return findPopplerWin(exe, { userProfile, localAppData, programFiles, programFilesX86 });
13598
- if (isSoffice) return findSofficeWin({ programFiles, programFilesX86, localAppData });
13599
- return void 0;
13600
- }
13601
- function findPopplerWin(exe, p) {
13602
- const scoopPath = (0, import_node_path.join)(p.userProfile, "scoop", "apps", "poppler", "current", "bin", exe);
13603
- if ((0, import_node_fs.existsSync)(scoopPath)) return scoopPath;
13604
- const wingetBase = (0, import_node_path.join)(p.localAppData, "Microsoft", "WinGet", "Packages");
13605
- const wingetResult = globFirst(wingetBase, ["oschwartz10612.Poppler_*"], ["poppler-*", "Library", "bin", exe]);
13606
- if (wingetResult) return wingetResult;
13607
- const chocoBase = (0, import_node_path.join)("C:", "ProgramData", "chocolatey", "lib", "poppler", "tools");
13608
- const chocoResult = globFirst(chocoBase, ["poppler-*"], ["bin", exe]);
13609
- if (chocoResult) return chocoResult;
13610
- for (const base of [
13611
- (0, import_node_path.join)("C:", "poppler", "bin", exe),
13612
- (0, import_node_path.join)("C:", "tools", "poppler", "bin", exe),
13613
- (0, import_node_path.join)(p.programFiles, "poppler", "bin", exe),
13614
- (0, import_node_path.join)(p.programFilesX86, "poppler", "bin", exe),
13615
- (0, import_node_path.join)(p.localAppData, "Programs", "poppler", "bin", exe)
13616
- ]) {
13617
- if ((0, import_node_fs.existsSync)(base)) return base;
13618
- }
13619
- return void 0;
13620
- }
13621
- function findSofficeWin(p) {
13622
- for (const candidate of [
13623
- (0, import_node_path.join)(p.programFiles, "LibreOffice", "program", "soffice.exe"),
13624
- (0, import_node_path.join)(p.programFilesX86, "LibreOffice", "program", "soffice.exe"),
13625
- (0, import_node_path.join)(p.localAppData, "Programs", "LibreOffice", "program", "soffice.exe"),
13626
- // winget 설치는 Program Files와 동일
13627
- (0, import_node_path.join)(p.programFiles, "LibreOffice 24", "program", "soffice.exe"),
13628
- (0, import_node_path.join)(p.programFiles, "LibreOffice 25", "program", "soffice.exe")
13629
- ]) {
13630
- if ((0, import_node_fs.existsSync)(candidate)) return candidate;
13631
- }
13632
- return void 0;
13633
- }
13634
- function globFirst(base, wildcardSegments, rest) {
13635
- if (!(0, import_node_fs.existsSync)(base)) return void 0;
13636
- let current = base;
13637
- for (const seg of wildcardSegments) {
13638
- if (!seg.includes("*")) {
13639
- current = (0, import_node_path.join)(current, seg);
13640
- if (!(0, import_node_fs.existsSync)(current)) return void 0;
13641
- continue;
11257
+ // src/pipeline/bounded-queue.ts
11258
+ var QUEUE_DONE = /* @__PURE__ */ Symbol("QUEUE_DONE");
11259
+ var BoundedQueue = class {
11260
+ buffer = [];
11261
+ capacity;
11262
+ closed = false;
11263
+ producerWaiters = [];
11264
+ consumerWaiters = [];
11265
+ constructor(capacity) {
11266
+ if (capacity < 1) throw new RangeError("BoundedQueue capacity must be >= 1");
11267
+ this.capacity = capacity;
11268
+ }
11269
+ async enqueue(item) {
11270
+ if (this.closed) throw new Error("BoundedQueue: cannot enqueue after close()");
11271
+ if (this.consumerWaiters.length > 0) {
11272
+ const resolve4 = this.consumerWaiters.shift();
11273
+ resolve4(item);
11274
+ return;
13642
11275
  }
13643
- try {
13644
- const { readdirSync } = require("fs");
13645
- const entries = readdirSync(current);
13646
- const pattern = seg.replace(/\*/g, ".*");
13647
- const re = new RegExp(`^${pattern}$`, "i");
13648
- const match = entries.find((e) => re.test(e));
13649
- if (!match) return void 0;
13650
- current = (0, import_node_path.join)(current, match);
13651
- } catch {
13652
- return void 0;
11276
+ while (this.buffer.length >= this.capacity) {
11277
+ await new Promise((resolve4) => this.producerWaiters.push(resolve4));
11278
+ if (this.closed) throw new Error("BoundedQueue: closed while waiting to enqueue");
11279
+ }
11280
+ this.buffer.push(item);
11281
+ }
11282
+ async dequeue() {
11283
+ if (this.buffer.length > 0) {
11284
+ const item = this.buffer.shift();
11285
+ this._wakeProducer();
11286
+ return item;
11287
+ }
11288
+ if (this.closed) return QUEUE_DONE;
11289
+ return new Promise((resolve4) => {
11290
+ this.consumerWaiters.push(resolve4);
11291
+ });
11292
+ }
11293
+ close() {
11294
+ if (this.closed) return;
11295
+ this.closed = true;
11296
+ for (const resolve4 of this.consumerWaiters) {
11297
+ resolve4(QUEUE_DONE);
11298
+ }
11299
+ this.consumerWaiters = [];
11300
+ for (const wake of this.producerWaiters) {
11301
+ wake();
11302
+ }
11303
+ this.producerWaiters = [];
11304
+ }
11305
+ get size() {
11306
+ return this.buffer.length;
11307
+ }
11308
+ _wakeProducer() {
11309
+ if (this.producerWaiters.length > 0) {
11310
+ this.producerWaiters.shift()();
13653
11311
  }
13654
11312
  }
13655
- const final = (0, import_node_path.join)(current, ...rest);
13656
- return (0, import_node_fs.existsSync)(final) ? final : void 0;
13657
- }
13658
- function probe(cmd, envKey, versionArgs = ["--version"]) {
13659
- const resolvedPath = resolveCmd(cmd, envKey);
13660
- if (!resolvedPath) return { name: cmd, found: false };
13661
- const v = (0, import_node_child_process.spawnSync)(resolvedPath, versionArgs, { encoding: "utf8", shell: isWin });
13662
- const versionLine = (v.stdout || v.stderr).split(/\r?\n/)[0]?.trim();
13663
- return { name: cmd, found: true, path: resolvedPath, version: versionLine };
13664
- }
13665
- function probeOcrToolchain() {
13666
- return {
13667
- // poppler는 --version이 비표준이므로 -v 사용
13668
- pdftoppm: probe("pdftoppm", "KORDOC_PDFTOPPM_PATH", ["-v"]),
13669
- pdfinfo: probe("pdfinfo", "KORDOC_PDFINFO_PATH", ["-v"]),
13670
- pdftotext: probe("pdftotext", "KORDOC_PDFTOTEXT_PATH", ["-v"]),
13671
- soffice: probe("soffice", "KORDOC_SOFFICE_PATH", ["--version"])
13672
- };
13673
- }
13674
-
13675
- // src/setup/pm.ts
13676
- var import_node_child_process2 = require("child_process");
13677
- var isWin2 = process.platform === "win32";
13678
- function which2(cmd) {
13679
- const finder = isWin2 ? "where" : "which";
13680
- const r = (0, import_node_child_process2.spawnSync)(finder, [cmd], { encoding: "utf8", shell: isWin2 });
13681
- return r.status === 0;
13682
- }
13683
- function detectPackageManager() {
13684
- if (process.platform === "darwin") {
13685
- return which2("brew") ? "brew" : "unknown";
13686
- }
13687
- if (isWin2) {
13688
- if (which2("winget")) return "winget";
13689
- if (which2("scoop")) return "scoop";
13690
- if (which2("choco")) return "choco";
13691
- return "unknown";
13692
- }
13693
- if (which2("apt-get") || which2("apt")) return "apt";
13694
- if (which2("dnf")) return "dnf";
13695
- if (which2("yum")) return "yum";
13696
- if (which2("pacman")) return "pacman";
13697
- if (which2("zypper")) return "zypper";
13698
- if (which2("apk")) return "apk";
13699
- return "unknown";
13700
- }
13701
-
13702
- // src/setup/install-commands.ts
13703
- var POPPLER_RECIPES = {
13704
- brew: { pm: "brew", cmd: "brew install poppler", needsSudo: false },
13705
- winget: { pm: "winget", cmd: "winget install --id oschwartz10612.Poppler", needsSudo: false, notes: "\uC2E4\uC874 \uD655\uC778\uB428 (winget-pkgs 25.07.0-0)" },
13706
- scoop: { pm: "scoop", cmd: "scoop install poppler", needsSudo: false, notes: "main \uBC84\uD0B7 \uD3EC\uD568, PATH \uC790\uB3D9 \uB4F1\uB85D" },
13707
- choco: { pm: "choco", cmd: "choco install poppler -y", needsSudo: true, notes: "\uAD00\uB9AC\uC790 PowerShell \uD544\uC694" },
13708
- apt: { pm: "apt", cmd: "sudo apt-get install -y poppler-utils", needsSudo: true },
13709
- dnf: { pm: "dnf", cmd: "sudo dnf install -y poppler-utils", needsSudo: true },
13710
- yum: { pm: "yum", cmd: "sudo yum install -y poppler-utils", needsSudo: true },
13711
- pacman: { pm: "pacman", cmd: "sudo pacman -S --noconfirm poppler", needsSudo: true },
13712
- zypper: { pm: "zypper", cmd: "sudo zypper install -y poppler-tools", needsSudo: true },
13713
- apk: { pm: "apk", cmd: "apk add --no-cache poppler-utils", needsSudo: false, notes: "Alpine/Docker \uCE5C\uD654" },
13714
- unknown: null
13715
- };
13716
- var LIBREOFFICE_RECIPES = {
13717
- brew: { pm: "brew", cmd: "brew install --cask libreoffice", needsSudo: false },
13718
- winget: { pm: "winget", cmd: "winget install --id TheDocumentFoundation.LibreOffice", needsSudo: false, notes: "\uC2E4\uC874 \uD655\uC778\uB428" },
13719
- scoop: { pm: "scoop", cmd: "scoop bucket add extras && scoop install libreoffice", needsSudo: false },
13720
- choco: { pm: "choco", cmd: "choco install libreoffice-fresh -y", needsSudo: true, notes: "\uAD00\uB9AC\uC790 PowerShell \uD544\uC694" },
13721
- apt: { pm: "apt", cmd: "sudo apt-get install -y libreoffice", needsSudo: true },
13722
- dnf: { pm: "dnf", cmd: "sudo dnf install -y libreoffice", needsSudo: true },
13723
- yum: { pm: "yum", cmd: "sudo yum install -y libreoffice", needsSudo: true },
13724
- pacman: { pm: "pacman", cmd: "sudo pacman -S --noconfirm libreoffice-still", needsSudo: true },
13725
- zypper: { pm: "zypper", cmd: "sudo zypper install -y libreoffice", needsSudo: true },
13726
- apk: { pm: "apk", cmd: "apk add --no-cache libreoffice", needsSudo: false, notes: "Alpine \uBBF8\uC9C0\uC6D0 \uAC00\uB2A5 \u2014 node:20-slim(Debian) \uAD8C\uC7A5" },
13727
- unknown: null
13728
11313
  };
13729
11314
 
13730
11315
  // src/pipeline/unified-ocr.ts
11316
+ var libreConvert = import_libreoffice_convert.default.convert;
13731
11317
  var UnifiedOcrError = class extends Error {
13732
11318
  code;
13733
11319
  stage;
@@ -13758,11 +11344,11 @@ var DEFAULT_MODEL_MAX_TOKENS = {
13758
11344
  };
13759
11345
  var DEFAULT_STAGE_WEIGHTS = {
13760
11346
  convert: 15,
13761
- render: 20,
11347
+ render: 15,
13762
11348
  probe: 5,
13763
- ocr: 45,
11349
+ ocr: 55,
13764
11350
  proofread: 0,
13765
- merge: 5
11351
+ merge: 10
13766
11352
  };
13767
11353
  var OCR_PROMPT2 = [
13768
11354
  "\uC774 PDF \uD398\uC774\uC9C0 \uC774\uBBF8\uC9C0\uC5D0\uC11C \uD14D\uC2A4\uD2B8\uC640 \uD45C\uB97C \uCD94\uCD9C\uD558\uC5EC Markdown\uC73C\uB85C \uBCC0\uD658\uD558\uACE0, OCR \uC624\uC778\uC2DD \uC624\uB958\uB97C \uC989\uC2DC \uAD50\uC815\uD558\uC5EC \uCD5C\uC885 \uACB0\uACFC\uBB3C\uC744 \uCD9C\uB825\uD558\uC138\uC694.",
@@ -13834,14 +11420,13 @@ async function runUnifiedOcrPipeline(inputPath, options = {}) {
13834
11420
  };
13835
11421
  try {
13836
11422
  ensureSupportedInput(absInput);
13837
- const isPdfInput = (0, import_path5.extname)(absInput).toLowerCase() === ".pdf";
13838
- await assertOcrToolchain(isPdfInput);
13839
11423
  let workingPdfPath = absInput;
13840
11424
  const convertStart = import_node_perf_hooks.performance.now();
13841
11425
  currentStage = "convert";
13842
11426
  markStageStart("convert", "\uBB38\uC11C\uB97C PDF\uB85C \uBCC0\uD658 \uC911");
13843
11427
  logStage("info", "convert", "start", "\uBB38\uC11C\uB97C PDF\uB85C \uBCC0\uD658 \uC2DC\uC791", { input: absInput });
13844
- if (!isPdfInput) {
11428
+ if ((0, import_path5.extname)(absInput).toLowerCase() !== ".pdf") {
11429
+ await assertSofficeAvailable();
13845
11430
  workingPdfPath = (0, import_path5.join)(workspaceDir, `${stem}.pdf`);
13846
11431
  const inputBuffer = await (0, import_promises2.readFile)(absInput);
13847
11432
  const out = await convertWithLibreOffice(inputBuffer, ".pdf");
@@ -13852,39 +11437,19 @@ async function runUnifiedOcrPipeline(inputPath, options = {}) {
13852
11437
  logStage("info", "convert", "done", "PDF \uBCC0\uD658 \uC644\uB8CC", { elapsedMs: timingsMs.convert });
13853
11438
  const renderStart = import_node_perf_hooks.performance.now();
13854
11439
  currentStage = "render";
11440
+ const totalPages = await getPdfPageCount(workingPdfPath).catch(() => 0);
11441
+ if (totalPages === 0) throw new UnifiedOcrError("RENDER_FAILED", "render", "\uD398\uC774\uC9C0 \uC218\uB97C \uD655\uC778\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.");
13855
11442
  markStageStart("render", "PDF \uD398\uC774\uC9C0 \uC774\uBBF8\uC9C0 \uC0DD\uC131 \uC911");
13856
- logStage("info", "render", "start", "PDF \uD398\uC774\uC9C0 \uB80C\uB354\uB9C1 \uC2DC\uC791", { pdf: workingPdfPath, dpi });
13857
- const renderWithProgress = await renderPdfToPngWithProgress(
13858
- workingPdfPath,
13859
- (0, import_path5.join)(imagesDir, "page"),
13860
- dpi,
13861
- (current, total) => {
13862
- markStageProgress(
13863
- "render",
13864
- Math.round(current / total * 100),
13865
- current,
13866
- total,
13867
- `\uD398\uC774\uC9C0 ${current}/${total} \uB80C\uB354\uB9C1`
13868
- );
13869
- }
13870
- );
13871
- const images = await listPageImages(imagesDir);
13872
- if (images.length === 0) throw new UnifiedOcrError("RENDER_FAILED", "render", "\uD398\uC774\uC9C0 \uC774\uBBF8\uC9C0 \uC0DD\uC131 \uC2E4\uD328: \uACB0\uACFC \uC774\uBBF8\uC9C0\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.");
13873
- if (!renderWithProgress.emittedPerPageProgress) {
13874
- markStageProgress("render", 100, images.length, images.length, `\uD398\uC774\uC9C0 ${images.length}\uC7A5 \uC0DD\uC131`);
13875
- }
13876
- timingsMs.render = elapsedMs(renderStart);
13877
- markStageDone("render", "\uC774\uBBF8\uC9C0 \uC0DD\uC131 \uC644\uB8CC");
13878
- logStage("info", "render", "done", "\uD398\uC774\uC9C0 \uC774\uBBF8\uC9C0 \uC0DD\uC131 \uC644\uB8CC", {
13879
- pages: images.length,
13880
- elapsedMs: timingsMs.render,
13881
- pageCountSource: renderWithProgress.pageCountSource
13882
- });
11443
+ logStage("info", "render", "start", "PDF \uD398\uC774\uC9C0 \uB80C\uB354\uB9C1 \uC2DC\uC791", { pdf: workingPdfPath, dpi, totalPages });
11444
+ await runCommand("pdftoppm", ["-png", "-r", String(dpi), "-f", "1", "-l", "1", workingPdfPath, (0, import_path5.join)(imagesDir, "page")]);
11445
+ const firstFiles = (await (0, import_promises2.readdir)(imagesDir)).filter((f) => f.endsWith(".png")).sort((a, b) => naturalPageSort(a, b));
11446
+ if (firstFiles.length === 0) throw new UnifiedOcrError("RENDER_FAILED", "render", "\uCCAB \uD398\uC774\uC9C0 \uC774\uBBF8\uC9C0 \uC0DD\uC131 \uC2E4\uD328");
11447
+ const probeImage = (0, import_path5.join)(imagesDir, firstFiles[0]);
11448
+ markStageProgress("render", Math.round(1 / totalPages * 100), 1, totalPages, `\uD398\uC774\uC9C0 1/${totalPages} \uB80C\uB354\uB9C1`);
13883
11449
  const probeStart = import_node_perf_hooks.performance.now();
13884
11450
  currentStage = "probe";
13885
11451
  markStageStart("probe", "\uBAA8\uB378 \uC18D\uB3C4 \uD504\uB85C\uBE0C \uC218\uD589 \uC911");
13886
11452
  logStage("info", "probe", "start", "\uBAA8\uB378 \uC18D\uB3C4 \uD504\uB85C\uBE0C \uC2DC\uC791", { models, probeConcurrency });
13887
- const probeImage = await pickRepresentativeImage(images);
13888
11453
  let probeDone = 0;
13889
11454
  const probeRuns = startParallelProbeRuns({
13890
11455
  models,
@@ -13895,10 +11460,10 @@ async function runUnifiedOcrPipeline(inputPath, options = {}) {
13895
11460
  keyPool,
13896
11461
  timeoutMs,
13897
11462
  logger,
13898
- onProbeResult: ({ index: index2, model, result }) => {
11463
+ onProbeResult: ({ index, model, result }) => {
13899
11464
  probeDone += 1;
13900
11465
  markStageProgress("probe", Math.round(probeDone / models.length * 100), probeDone, models.length, `\uBAA8\uB378 \uD504\uB85C\uBE0C ${probeDone}/${models.length}`);
13901
- logStage("debug", "probe", "progress", "\uBAA8\uB378 \uD504\uB85C\uBE0C \uC9C4\uD589", { index: index2 + 1, total: models.length, model, result });
11466
+ logStage("debug", "probe", "progress", "\uBAA8\uB378 \uD504\uB85C\uBE0C \uC9C4\uD589", { index: index + 1, total: models.length, model, result });
13902
11467
  }
13903
11468
  });
13904
11469
  const selected = await probeRuns.firstSuccess;
@@ -13911,33 +11476,74 @@ async function runUnifiedOcrPipeline(inputPath, options = {}) {
13911
11476
  await updateModelCache(modelCachePath, results);
13912
11477
  return results;
13913
11478
  });
11479
+ const concurrencyPerKey = Math.max(1, options.concurrencyPerKey ?? 2);
11480
+ const keyCount = keyPool.snapshot().length;
11481
+ const workerCount = Math.max(1, keyCount * concurrencyPerKey);
11482
+ const queueCapacity = workerCount * 2;
11483
+ const queue = new BoundedQueue(queueCapacity);
13914
11484
  const ocrStart = import_node_perf_hooks.performance.now();
13915
11485
  currentStage = "ocr";
13916
- markStageStart("ocr", `OCR \uC9C4\uD589 \uC911 (${selectedModel})`);
13917
- logStage("info", "ocr", "start", "\uD398\uC774\uC9C0 OCR \uC2DC\uC791", { selectedModel, pageCount: images.length });
13918
- const rawPagePaths = [];
13919
- for (let i = 0; i < images.length; i++) {
13920
- const imagePath = images[i];
13921
- const markdown = await ocrImageWithFallback({
13922
- imagePath,
13923
- prompt: OCR_PROMPT2,
13924
- models: fallbackModelOrder,
13925
- modelMaxTokens,
13926
- baseUrl,
13927
- keyPool,
13928
- timeoutMs,
13929
- maxRetriesPerPage,
11486
+ markStageStart("ocr", `OCR \uC9C4\uD589 \uC911 (\uC6CC\uCEE4 ${workerCount}\uAC1C)`);
11487
+ logStage("info", "ocr", "start", "\uD398\uC774\uC9C0 OCR \uC2DC\uC791", { workerCount, keyCount, pageCount: totalPages });
11488
+ let renderDone = 1;
11489
+ const renderProducer = (async () => {
11490
+ try {
11491
+ await queue.enqueue({ pageNumber: 1, imagePath: probeImage });
11492
+ if (totalPages > 1) {
11493
+ for await (const item of renderPdfToPngStream(workingPdfPath, (0, import_path5.join)(imagesDir, "page"), dpi, totalPages, 2)) {
11494
+ await queue.enqueue(item);
11495
+ renderDone++;
11496
+ markStageProgress("render", Math.round(renderDone / totalPages * 100), renderDone, totalPages, `\uD398\uC774\uC9C0 ${renderDone}/${totalPages} \uB80C\uB354\uB9C1`);
11497
+ logStage("debug", "render", "progress", "\uD398\uC774\uC9C0 \uB80C\uB354 \uC644\uB8CC", { page: item.pageNumber });
11498
+ }
11499
+ }
11500
+ } finally {
11501
+ queue.close();
11502
+ timingsMs.render = elapsedMs(renderStart);
11503
+ markStageDone("render", "\uC774\uBBF8\uC9C0 \uC0DD\uC131 \uC644\uB8CC");
11504
+ logStage("info", "render", "done", "\uD398\uC774\uC9C0 \uC774\uBBF8\uC9C0 \uC0DD\uC131 \uC644\uB8CC", { pages: renderDone, elapsedMs: timingsMs.render });
11505
+ }
11506
+ })();
11507
+ const [, pageResultsMap] = await Promise.all([
11508
+ renderProducer,
11509
+ ocrWorkerPool({
11510
+ queue,
11511
+ workerCount,
11512
+ totalPages,
11513
+ ocrInput: {
11514
+ prompt: OCR_PROMPT2,
11515
+ models: fallbackModelOrder,
11516
+ modelMaxTokens,
11517
+ baseUrl,
11518
+ keyPool,
11519
+ timeoutMs,
11520
+ maxRetriesPerPage,
11521
+ logger
11522
+ },
11523
+ onPageDone: (pageNumber, completedCount, model) => {
11524
+ markStageProgress(
11525
+ "ocr",
11526
+ Math.round(completedCount / totalPages * 100),
11527
+ completedCount,
11528
+ totalPages,
11529
+ `OCR ${completedCount}/${totalPages}`,
11530
+ model || void 0
11531
+ );
11532
+ logStage("debug", "ocr", "progress", "\uD398\uC774\uC9C0 OCR \uC644\uB8CC", { page: pageNumber, total: totalPages, model });
11533
+ },
13930
11534
  logger
13931
- });
13932
- const pagePath = (0, import_path5.join)(rawDir, `page_${String(i + 1).padStart(4, "0")}.md`);
13933
- await (0, import_promises2.writeFile)(pagePath, markdown, "utf-8");
13934
- rawPagePaths.push(pagePath);
13935
- markStageProgress("ocr", Math.round((i + 1) / images.length * 100), i + 1, images.length, `OCR ${i + 1}/${images.length}`, selectedModel);
13936
- logStage("debug", "ocr", "progress", "\uD398\uC774\uC9C0 OCR \uC644\uB8CC", { page: i + 1, total: images.length });
13937
- }
11535
+ })
11536
+ ]);
13938
11537
  timingsMs.ocr = elapsedMs(ocrStart);
13939
11538
  markStageDone("ocr", "OCR \uC644\uB8CC");
13940
11539
  logStage("info", "ocr", "done", "\uD398\uC774\uC9C0 OCR \uC644\uB8CC", { elapsedMs: timingsMs.ocr });
11540
+ const sortedEntries = Array.from(pageResultsMap.entries()).sort((a, b) => a[0] - b[0]);
11541
+ const rawPagePaths = [];
11542
+ for (const [pageNum, markdown] of sortedEntries) {
11543
+ const pagePath = (0, import_path5.join)(rawDir, `page_${String(pageNum).padStart(4, "0")}.md`);
11544
+ await (0, import_promises2.writeFile)(pagePath, markdown, "utf-8");
11545
+ rawPagePaths.push(pagePath);
11546
+ }
13941
11547
  const mergeStart = import_node_perf_hooks.performance.now();
13942
11548
  currentStage = "merge";
13943
11549
  markStageStart("merge", "\uCD5C\uC885 Markdown \uBCD1\uD569 \uC911");
@@ -13954,7 +11560,7 @@ async function runUnifiedOcrPipeline(inputPath, options = {}) {
13954
11560
  selectedModel,
13955
11561
  probeImage,
13956
11562
  probeResults: await probeResultsPromise,
13957
- pageCount: images.length,
11563
+ pageCount: totalPages,
13958
11564
  keyHealth: keyPool.snapshot(),
13959
11565
  timingsMs,
13960
11566
  modelCachePath
@@ -14021,37 +11627,17 @@ function emitProgress(cb, stage, stagePercent, weights, extra) {
14021
11627
  model: extra.model
14022
11628
  });
14023
11629
  }
14024
- async function loadLibreConvert() {
14025
- try {
14026
- const m = await Promise.resolve().then(() => __toESM(require_libreoffice_convert(), 1));
14027
- return (m.default ?? m).convert;
14028
- } catch {
14029
- throw new UnifiedOcrError(
14030
- "LIBRE_NOT_INSTALLED",
14031
- "convert",
14032
- "libreoffice-convert npm \uD328\uD0A4\uC9C0\uAC00 \uC124\uCE58\uB418\uC5B4 \uC788\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n npm install libreoffice-convert\n\uB610\uB294 npx kordoc setup \uC744 \uC2E4\uD589\uD558\uC138\uC694."
14033
- );
14034
- }
14035
- }
14036
11630
  async function convertWithLibreOffice(buffer, ext) {
14037
- const libreConvert = await loadLibreConvert();
14038
- return await new Promise((resolvePromise, reject2) => {
11631
+ return await new Promise((resolvePromise, reject) => {
14039
11632
  libreConvert(buffer, ext, void 0, (err, done) => {
14040
11633
  if (err || !done) {
14041
- reject2(new UnifiedOcrError("CONVERT_FAILED", "convert", err?.message ?? "LibreOffice \uBCC0\uD658 \uC2E4\uD328"));
11634
+ reject(new UnifiedOcrError("CONVERT_FAILED", "convert", err?.message ?? "LibreOffice \uBCC0\uD658 \uC2E4\uD328"));
14042
11635
  return;
14043
11636
  }
14044
11637
  resolvePromise(done);
14045
11638
  });
14046
11639
  });
14047
11640
  }
14048
- async function renderPdfToPng(pdfPath, prefixPath, dpi) {
14049
- try {
14050
- await runCommand("pdftoppm", ["-png", "-r", String(dpi), pdfPath, prefixPath]);
14051
- } catch (err) {
14052
- throw new UnifiedOcrError("RENDER_FAILED", "render", err instanceof Error ? err.message : String(err));
14053
- }
14054
- }
14055
11641
  async function getPdfPageCount(pdfPath) {
14056
11642
  const stdout = await runCommandWithStdout("pdfinfo", [pdfPath]);
14057
11643
  const m = stdout.match(/^\s*Pages:\s*(\d+)\s*$/mi);
@@ -14064,53 +11650,50 @@ async function getPdfPageCount(pdfPath) {
14064
11650
  }
14065
11651
  return n;
14066
11652
  }
14067
- async function renderPdfToPngWithProgress(pdfPath, prefixPath, dpi, onPageDone) {
14068
- let totalPages = 0;
14069
- try {
14070
- totalPages = await getPdfPageCount(pdfPath);
14071
- } catch {
14072
- totalPages = 0;
14073
- }
14074
- if (totalPages > 0) {
11653
+ async function* renderPdfToPngStream(pdfPath, prefixPath, dpi, totalPages, startPage = 1) {
11654
+ const imagesDir = (0, import_path5.dirname)(prefixPath);
11655
+ for (let page = startPage; page <= totalPages; page++) {
14075
11656
  try {
14076
- for (let page = 1; page <= totalPages; page++) {
14077
- await runCommand("pdftoppm", [
14078
- "-png",
14079
- "-r",
14080
- String(dpi),
14081
- "-f",
14082
- String(page),
14083
- "-l",
14084
- String(page),
14085
- pdfPath,
14086
- prefixPath
14087
- ]);
14088
- onPageDone(page, totalPages);
14089
- }
14090
- return { emittedPerPageProgress: true, pageCountSource: "pdfinfo" };
11657
+ await runCommand("pdftoppm", [
11658
+ "-png",
11659
+ "-r",
11660
+ String(dpi),
11661
+ "-f",
11662
+ String(page),
11663
+ "-l",
11664
+ String(page),
11665
+ pdfPath,
11666
+ prefixPath
11667
+ ]);
11668
+ const files = await (0, import_promises2.readdir)(imagesDir);
11669
+ const pageFiles = files.filter((f) => f.endsWith(".png")).sort((a, b) => naturalPageSort(a, b));
11670
+ const imagePath = (0, import_path5.join)(imagesDir, pageFiles[pageFiles.length - 1]);
11671
+ yield { pageNumber: page, imagePath };
14091
11672
  } catch (err) {
14092
- throw new UnifiedOcrError("RENDER_FAILED", "render", err instanceof Error ? err.message : String(err));
11673
+ yield {
11674
+ pageNumber: page,
11675
+ imagePath: null,
11676
+ error: err instanceof Error ? err : new Error(String(err))
11677
+ };
14093
11678
  }
14094
11679
  }
14095
- await renderPdfToPng(pdfPath, prefixPath, dpi);
14096
- return { emittedPerPageProgress: false, pageCountSource: "fallback" };
14097
11680
  }
14098
11681
  async function runCommand(cmd, args) {
14099
- await new Promise((resolvePromise, reject2) => {
11682
+ await new Promise((resolvePromise, reject) => {
14100
11683
  const child = (0, import_child_process4.spawn)(cmd, args, { stdio: "pipe" });
14101
11684
  let stderr = "";
14102
11685
  child.stderr.on("data", (d) => {
14103
11686
  stderr += String(d);
14104
11687
  });
14105
- child.on("error", reject2);
11688
+ child.on("error", reject);
14106
11689
  child.on("close", (code) => {
14107
11690
  if (code === 0) resolvePromise();
14108
- else reject2(new Error(`${cmd} \uC2E4\uD328 (code=${code}): ${stderr.trim()}`));
11691
+ else reject(new Error(`${cmd} \uC2E4\uD328 (code=${code}): ${stderr.trim()}`));
14109
11692
  });
14110
11693
  });
14111
11694
  }
14112
11695
  async function runCommandWithStdout(cmd, args) {
14113
- return await new Promise((resolvePromise, reject2) => {
11696
+ return await new Promise((resolvePromise, reject) => {
14114
11697
  const child = (0, import_child_process4.spawn)(cmd, args, { stdio: "pipe" });
14115
11698
  let stdout = "";
14116
11699
  let stderr = "";
@@ -14120,52 +11703,25 @@ async function runCommandWithStdout(cmd, args) {
14120
11703
  child.stderr.on("data", (d) => {
14121
11704
  stderr += String(d);
14122
11705
  });
14123
- child.on("error", reject2);
11706
+ child.on("error", reject);
14124
11707
  child.on("close", (code) => {
14125
11708
  if (code === 0) resolvePromise(stdout);
14126
- else reject2(new Error(`${cmd} \uC2E4\uD328 (code=${code}): ${stderr.trim()}`));
11709
+ else reject(new Error(`${cmd} \uC2E4\uD328 (code=${code}): ${stderr.trim()}`));
14127
11710
  });
14128
11711
  });
14129
11712
  }
14130
- async function assertOcrToolchain(isPdfInput = false) {
14131
- const t = probeOcrToolchain();
14132
- const pm = detectPackageManager();
14133
- const missing = [];
14134
- if (!t.pdftoppm.found || !t.pdfinfo.found) missing.push("poppler");
14135
- if (!isPdfInput && !t.soffice.found) missing.push("libreoffice");
14136
- if (missing.length === 0) return;
14137
- const lines = ["OCR \uD30C\uC774\uD504\uB77C\uC778\uC5D0 \uD544\uC694\uD55C \uC2DC\uC2A4\uD15C \uB3C4\uAD6C\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4."];
14138
- if (missing.includes("poppler")) {
14139
- const r = POPPLER_RECIPES[pm];
14140
- lines.push(` - poppler (pdftoppm/pdfinfo): ${r ? r.cmd : "OS\uBCC4 \uC124\uCE58 \uC548\uB0B4\uB294 README \uCC38\uACE0"}`);
14141
- }
14142
- if (missing.includes("libreoffice")) {
14143
- const r = LIBREOFFICE_RECIPES[pm];
14144
- lines.push(` - LibreOffice (soffice): ${r ? r.cmd : "OS\uBCC4 \uC124\uCE58 \uC548\uB0B4\uB294 README \uCC38\uACE0"}`);
14145
- }
14146
- lines.push("\uC790\uC138\uD55C \uC810\uAC80: npx kordoc doctor");
14147
- throw new UnifiedOcrError("TOOLCHAIN_MISSING", "convert", lines.join("\n"));
14148
- }
14149
- async function listPageImages(imagesDir) {
14150
- const files = await (0, import_promises2.readdir)(imagesDir);
14151
- return files.filter((f) => f.endsWith(".png")).sort((a, b) => naturalPageSort(a, b)).map((f) => (0, import_path5.join)(imagesDir, f));
11713
+ async function assertSofficeAvailable() {
11714
+ try {
11715
+ await runCommand("soffice", ["--version"]);
11716
+ } catch {
11717
+ throw new UnifiedOcrError("SOFFICE_NOT_FOUND", "convert", "soffice\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. LibreOffice\uB97C \uC124\uCE58\uD574 \uC8FC\uC138\uC694.");
11718
+ }
14152
11719
  }
14153
11720
  function naturalPageSort(a, b) {
14154
11721
  const na = Number((a.match(/\d+/g) || ["0"]).at(-1) || 0);
14155
11722
  const nb = Number((b.match(/\d+/g) || ["0"]).at(-1) || 0);
14156
11723
  return na - nb;
14157
11724
  }
14158
- async function pickRepresentativeImage(images) {
14159
- const sample = images.slice(0, Math.min(images.length, 8));
14160
- const weighted = [];
14161
- for (const p of sample) {
14162
- const st = await (0, import_promises2.stat)(p);
14163
- if (st.size > 8 * 1024) weighted.push({ path: p, size: st.size });
14164
- }
14165
- const use = weighted.length > 0 ? weighted : await Promise.all(sample.map(async (p) => ({ path: p, size: (await (0, import_promises2.stat)(p)).size })));
14166
- use.sort((a, b) => a.size - b.size);
14167
- return use[Math.floor(use.length / 2)].path;
14168
- }
14169
11725
  async function mapWithConcurrency(items, concurrency, mapper) {
14170
11726
  const results = new Array(items.length);
14171
11727
  let nextIndex = 0;
@@ -14186,12 +11742,12 @@ function startParallelProbeRuns(input) {
14186
11742
  let doneCount = 0;
14187
11743
  let resolveFirst;
14188
11744
  let rejectFirst;
14189
- const firstSuccess = new Promise((resolve4, reject2) => {
11745
+ const firstSuccess = new Promise((resolve4, reject) => {
14190
11746
  resolveFirst = resolve4;
14191
- rejectFirst = reject2;
11747
+ rejectFirst = reject;
14192
11748
  });
14193
11749
  let lastErr = "\uC18D\uB3C4 \uD504\uB85C\uBE0C \uC2E4\uD328: \uC0AC\uC6A9 \uAC00\uB2A5\uD55C OCR \uBAA8\uB378\uC774 \uC5C6\uC2B5\uB2C8\uB2E4.";
14194
- const allResults = mapWithConcurrency(input.models, input.probeConcurrency, async (model, index2) => {
11750
+ const allResults = mapWithConcurrency(input.models, input.probeConcurrency, async (model, index) => {
14195
11751
  const t0 = import_node_perf_hooks.performance.now();
14196
11752
  try {
14197
11753
  await ocrImageViaNim({
@@ -14207,7 +11763,7 @@ function startParallelProbeRuns(input) {
14207
11763
  stage: "probe"
14208
11764
  });
14209
11765
  const result = { model, durationMs: elapsedMs(t0), success: true };
14210
- input.onProbeResult?.({ index: index2, model, result });
11766
+ input.onProbeResult?.({ index, model, result });
14211
11767
  if (!firstResolved) {
14212
11768
  firstResolved = true;
14213
11769
  resolveFirst?.({ selectedModel: model, firstDurationMs: result.durationMs });
@@ -14221,7 +11777,7 @@ function startParallelProbeRuns(input) {
14221
11777
  error: err instanceof Error ? err.message : String(err)
14222
11778
  };
14223
11779
  lastErr = result.error ?? lastErr;
14224
- input.onProbeResult?.({ index: index2, model, result });
11780
+ input.onProbeResult?.({ index, model, result });
14225
11781
  return result;
14226
11782
  } finally {
14227
11783
  doneCount += 1;
@@ -14267,11 +11823,43 @@ async function updateModelCache(path, probes) {
14267
11823
  current.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
14268
11824
  await (0, import_promises2.writeFile)(path, JSON.stringify(current, null, 2), "utf-8");
14269
11825
  }
11826
+ async function ocrWorkerPool(input) {
11827
+ const { queue, workerCount, ocrInput, onPageDone } = input;
11828
+ const results = /* @__PURE__ */ new Map();
11829
+ let completedCount = 0;
11830
+ async function worker() {
11831
+ while (true) {
11832
+ const item = await queue.dequeue();
11833
+ if (item === QUEUE_DONE) break;
11834
+ const { pageNumber, imagePath, error } = item;
11835
+ if (imagePath === null) {
11836
+ input.logger?.log({
11837
+ level: "warn",
11838
+ stage: "ocr",
11839
+ event: "message",
11840
+ message: `\uD398\uC774\uC9C0 ${pageNumber} \uB80C\uB354 \uC2E4\uD328 \u2014 \uBE48 \uD398\uC774\uC9C0\uB85C \uCC98\uB9AC`,
11841
+ meta: { error: String(error) }
11842
+ });
11843
+ results.set(pageNumber, "");
11844
+ completedCount++;
11845
+ onPageDone(pageNumber, completedCount, "");
11846
+ continue;
11847
+ }
11848
+ const { markdown, model } = await ocrImageWithFallback({ ...ocrInput, imagePath });
11849
+ results.set(pageNumber, markdown);
11850
+ completedCount++;
11851
+ onPageDone(pageNumber, completedCount, model);
11852
+ }
11853
+ }
11854
+ const workers = Array.from({ length: workerCount }, () => worker());
11855
+ await Promise.all(workers);
11856
+ return results;
11857
+ }
14270
11858
  async function ocrImageWithFallback(input) {
14271
11859
  let lastErr = "\uC54C \uC218 \uC5C6\uB294 \uC624\uB958";
14272
11860
  for (const model of input.models) {
14273
11861
  try {
14274
- return await ocrImageViaNim({
11862
+ const markdown = await ocrImageViaNim({
14275
11863
  imagePath: input.imagePath,
14276
11864
  prompt: input.prompt,
14277
11865
  model,
@@ -14283,6 +11871,7 @@ async function ocrImageWithFallback(input) {
14283
11871
  logger: input.logger,
14284
11872
  stage: "ocr"
14285
11873
  });
11874
+ return { markdown, model };
14286
11875
  } catch (err) {
14287
11876
  lastErr = err instanceof Error ? err.message : String(err);
14288
11877
  }
@@ -14629,14 +12218,5 @@ async function parseDocx(buffer, options, zip) {
14629
12218
 
14630
12219
  cfb/cfb.js:
14631
12220
  (*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com *)
14632
-
14633
- tmp/lib/tmp.js:
14634
- (*!
14635
- * Tmp
14636
- *
14637
- * Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
14638
- *
14639
- * MIT Licensed
14640
- *)
14641
12221
  */
14642
12222
  //# sourceMappingURL=index.cjs.map