@skrillex1224/playwright-toolkit 2.1.219 → 2.1.221

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.js CHANGED
@@ -334,18 +334,18 @@ var fallbackLog = {
334
334
  error: (...args) => console.error(...args),
335
335
  debug: (...args) => console.debug ? console.debug(...args) : console.log(...args)
336
336
  };
337
- var resolveLogMethod = (logger13, name) => {
338
- if (logger13 && typeof logger13[name] === "function") {
339
- return logger13[name].bind(logger13);
337
+ var resolveLogMethod = (logger14, name) => {
338
+ if (logger14 && typeof logger14[name] === "function") {
339
+ return logger14[name].bind(logger14);
340
340
  }
341
- if (name === "warning" && logger13 && typeof logger13.warn === "function") {
342
- return logger13.warn.bind(logger13);
341
+ if (name === "warning" && logger14 && typeof logger14.warn === "function") {
342
+ return logger14.warn.bind(logger14);
343
343
  }
344
344
  return fallbackLog[name];
345
345
  };
346
346
  var defaultLogger = null;
347
- var setDefaultLogger = (logger13) => {
348
- defaultLogger = logger13;
347
+ var setDefaultLogger = (logger14) => {
348
+ defaultLogger = logger14;
349
349
  };
350
350
  var resolveLogger = (explicitLogger) => {
351
351
  if (explicitLogger && typeof explicitLogger.info === "function") {
@@ -372,8 +372,8 @@ var colorize = (text, color) => {
372
372
  var createBaseLogger = (prefix = "", explicitLogger) => {
373
373
  const name = prefix ? String(prefix) : "";
374
374
  const dispatch = (methodName, icon, message, color) => {
375
- const logger13 = resolveLogger(explicitLogger);
376
- const logFn = resolveLogMethod(logger13, methodName);
375
+ const logger14 = resolveLogger(explicitLogger);
376
+ const logFn = resolveLogMethod(logger14, methodName);
377
377
  const timestamp = colorize(`[${formatTimestamp()}]`, ANSI.gray);
378
378
  const line = formatLine(name, icon, message);
379
379
  const coloredLine = colorize(line, color);
@@ -412,6 +412,7 @@ function createInternalLogger(moduleName, explicitLogger) {
412
412
  },
413
413
  warning(message) {
414
414
  baseLogger.warning(message);
415
+ a;
415
416
  },
416
417
  info(message) {
417
418
  baseLogger.info(message);
@@ -657,9 +658,9 @@ var resolveResourceTypeMeta = (domain) => {
657
658
  if (!byType || byType.size === 0) {
658
659
  return { resourceType: "", resourceTypeCounts: void 0 };
659
660
  }
660
- const entries = Array.from(byType.entries()).filter(([type, count]) => type && Number(count) > 0).sort((a, b) => {
661
- if (Number(b[1]) !== Number(a[1])) return Number(b[1]) - Number(a[1]);
662
- return String(a[0]).localeCompare(String(b[0]));
661
+ const entries = Array.from(byType.entries()).filter(([type, count]) => type && Number(count) > 0).sort((a2, b) => {
662
+ if (Number(b[1]) !== Number(a2[1])) return Number(b[1]) - Number(a2[1]);
663
+ return String(a2[0]).localeCompare(String(b[0]));
663
664
  });
664
665
  if (entries.length === 0) {
665
666
  return { resourceType: "", resourceTypeCounts: void 0 };
@@ -749,10 +750,10 @@ var normalizeDomainRows = (hosts) => {
749
750
  resourceTypeCounts: resourceTypeMeta.resourceTypeCounts || void 0
750
751
  });
751
752
  }
752
- rows.sort((a, b) => {
753
- if (b.totalBytes !== a.totalBytes) return b.totalBytes - a.totalBytes;
754
- if (b.requests !== a.requests) return b.requests - a.requests;
755
- return String(a.domain).localeCompare(String(b.domain));
753
+ rows.sort((a2, b) => {
754
+ if (b.totalBytes !== a2.totalBytes) return b.totalBytes - a2.totalBytes;
755
+ if (b.requests !== a2.requests) return b.requests - a2.requests;
756
+ return String(a2.domain).localeCompare(String(b.domain));
756
757
  });
757
758
  return {
758
759
  topDomains: rows.slice(0, MAX_TOP_DOMAINS),
@@ -2947,13 +2948,91 @@ var LiveView = {
2947
2948
  useLiveView
2948
2949
  };
2949
2950
 
2950
- // src/captcha-monitor.js
2951
+ // src/chaptcha.js
2951
2952
  import { v4 as uuidv4 } from "uuid";
2953
+
2954
+ // src/internals/captcha/shared.js
2955
+ var waitForVisible = async (locator, timeout) => {
2956
+ try {
2957
+ await locator.waitFor({
2958
+ state: "visible",
2959
+ timeout
2960
+ });
2961
+ return true;
2962
+ } catch {
2963
+ return false;
2964
+ }
2965
+ };
2966
+ var isAnyCaptchaTextVisible = async (frame, texts, timeout) => {
2967
+ for (const text of texts || []) {
2968
+ if (!text) {
2969
+ continue;
2970
+ }
2971
+ const candidates = [
2972
+ frame.getByText(text, { exact: false }).first(),
2973
+ frame.locator(`text=${text}`).first()
2974
+ ];
2975
+ for (const candidate of candidates) {
2976
+ const isVisible = await candidate.isVisible({ timeout }).catch(() => false);
2977
+ if (isVisible) {
2978
+ return true;
2979
+ }
2980
+ }
2981
+ }
2982
+ return false;
2983
+ };
2984
+ var clickCaptchaAction = async (frame, texts, options) => {
2985
+ for (const text of texts || []) {
2986
+ const candidates = [
2987
+ frame.getByText(text, { exact: false }).first(),
2988
+ frame.locator(`text=${text}`).first()
2989
+ ];
2990
+ for (const candidate of candidates) {
2991
+ const isVisible = await waitForVisible(candidate, options.actionVisibleTimeoutMs);
2992
+ if (!isVisible) {
2993
+ continue;
2994
+ }
2995
+ await candidate.click();
2996
+ return true;
2997
+ }
2998
+ }
2999
+ return false;
3000
+ };
3001
+ var dragCaptchaWithMouse = async (page, sourceLocator, targetLocator) => {
3002
+ const sourceBox = await sourceLocator.boundingBox();
3003
+ const targetBox = await targetLocator.boundingBox();
3004
+ if (!sourceBox || !targetBox) {
3005
+ throw new Error("Unable to resolve captcha drag coordinates.");
3006
+ }
3007
+ const startX = sourceBox.x + sourceBox.width / 2;
3008
+ const startY = sourceBox.y + sourceBox.height / 2;
3009
+ const endX = targetBox.x + targetBox.width / 2;
3010
+ const endY = targetBox.y + targetBox.height / 2;
3011
+ const steps = 10;
3012
+ const liftOffsetX = Math.min(18, Math.max(8, sourceBox.width * 0.12));
3013
+ const liftOffsetY = Math.min(12, Math.max(4, sourceBox.height * 0.08));
3014
+ await page.mouse.move(startX, startY, { steps: 8 });
3015
+ await page.waitForTimeout(250);
3016
+ await page.mouse.down();
3017
+ await page.waitForTimeout(350);
3018
+ await page.mouse.move(startX + liftOffsetX, startY + liftOffsetY, { steps: 6 });
3019
+ await page.waitForTimeout(250);
3020
+ for (let step = 1; step <= steps; step++) {
3021
+ const progress = step / steps;
3022
+ const easedProgress = 1 - (1 - progress) * (1 - progress);
3023
+ const currentX = startX + liftOffsetX + (endX - startX - liftOffsetX) * easedProgress;
3024
+ const currentY = startY + liftOffsetY + (endY - startY - liftOffsetY) * easedProgress;
3025
+ await page.mouse.move(currentX, currentY, { steps: 2 });
3026
+ await page.waitForTimeout(90);
3027
+ }
3028
+ await page.waitForTimeout(100);
3029
+ await page.mouse.up();
3030
+ await page.waitForTimeout(100);
3031
+ };
3032
+
3033
+ // src/internals/captcha/bytedance.js
2952
3034
  var logger9 = createInternalLogger("Captcha");
2953
- var DEFAULT_BYTEDANCE_CAPTCHA_TOKEN = "eKJvBfwfN0YRav0-VD_44E2VBSfm7l0YtddUQ7cFySI";
2954
3035
  var DEFAULT_BYTEDANCE_CAPTCHA_OPTIONS = Object.freeze({
2955
- token: DEFAULT_BYTEDANCE_CAPTCHA_TOKEN,
2956
- apiUrl: "https://api.jfbym.com/api/YmServer/customApi",
2957
3036
  apiType: "31234",
2958
3037
  maxRetries: 3,
2959
3038
  containerSelector: "#captcha_container",
@@ -2973,137 +3052,23 @@ var DEFAULT_BYTEDANCE_CAPTCHA_OPTIONS = Object.freeze({
2973
3052
  actionVisibleTimeoutMs: 1500,
2974
3053
  sourceImageVisibleTimeoutMs: 3e3,
2975
3054
  challengeReadyTimeoutMs: 15e3,
3055
+ challengeReadyRefreshTimeoutMs: 2e4,
2976
3056
  challengeReadyPollMs: 300,
2977
3057
  loadingIndicatorVisibleTimeoutMs: 200,
2978
3058
  loadingTexts: ["\u52A0\u8F7D\u4E2D", "\u52A0\u8F7D\u4E2D..."],
3059
+ errorTexts: [
3060
+ "\u68C0\u6D4B\u5230\u60A8\u7684\u7F51\u7EDC\u73AF\u5883\u8F83\u5DEE",
3061
+ "\u7F51\u7EDC\u73AF\u5883\u8F83\u5DEE",
3062
+ "\u8BF7\u66F4\u6362\u7F51\u7EDC\u6216\u8005\u7A0D\u540E\u518D\u8BD5",
3063
+ "\u8BF7\u66F4\u6362\u7F51\u7EDC\u6216\u7A0D\u540E\u518D\u8BD5",
3064
+ "\u7A0D\u540E\u518D\u8BD5"
3065
+ ],
2979
3066
  recognitionDelayMs: 2e3,
2980
3067
  refreshWaitMs: 3e3,
2981
3068
  submitWaitMs: 3e3,
2982
3069
  retryDelayBaseMs: 2e3,
2983
3070
  retryDelayStepMs: 1e3
2984
3071
  });
2985
- function useCaptchaMonitor(page, options) {
2986
- const { domSelector, urlPattern, onDetected } = options;
2987
- if (!domSelector && !urlPattern) {
2988
- throw new Error("[CaptchaMonitor] \u5FC5\u987B\u63D0\u4F9B domSelector \u6216 urlPattern\u3002");
2989
- }
2990
- if (!onDetected || typeof onDetected !== "function") {
2991
- throw new Error("[CaptchaMonitor] onDetected \u5FC5\u987B\u662F\u51FD\u6570\u3002");
2992
- }
2993
- let isStopped = false;
2994
- let isHandling = false;
2995
- let frameHandler = null;
2996
- let exposedFunctionName = null;
2997
- const triggerDetected = async () => {
2998
- if (isStopped || isHandling) return;
2999
- isHandling = true;
3000
- try {
3001
- await onDetected();
3002
- } finally {
3003
- isHandling = false;
3004
- }
3005
- };
3006
- const cleanupFns = [];
3007
- if (domSelector) {
3008
- exposedFunctionName = `__c_d_${uuidv4().replace(/-/g, "_")}`;
3009
- const cleanerName = `__c_cleaner_${uuidv4().replace(/-/g, "_")}`;
3010
- page.exposeFunction(exposedFunctionName, triggerDetected).catch(() => {
3011
- });
3012
- page.addInitScript(({ selector, callbackName, cleanerName: cleanupName }) => {
3013
- (() => {
3014
- let observer = null;
3015
- const checkAndReport = () => {
3016
- const element = document.querySelector(selector);
3017
- if (!element) {
3018
- return false;
3019
- }
3020
- if (window[callbackName]) {
3021
- window[callbackName]();
3022
- }
3023
- return true;
3024
- };
3025
- checkAndReport();
3026
- observer = new MutationObserver((mutations) => {
3027
- const shouldCheck = mutations.some((mutation) => mutation.addedNodes.length > 0);
3028
- if (shouldCheck && observer) {
3029
- checkAndReport();
3030
- }
3031
- });
3032
- const mountObserver = () => {
3033
- const target = document.documentElement;
3034
- if (target && observer) {
3035
- observer.observe(target, { childList: true, subtree: true });
3036
- }
3037
- };
3038
- if (document.readyState === "loading") {
3039
- window.addEventListener("DOMContentLoaded", mountObserver);
3040
- } else {
3041
- mountObserver();
3042
- }
3043
- window[cleanupName] = () => {
3044
- if (observer) {
3045
- observer.disconnect();
3046
- observer = null;
3047
- }
3048
- };
3049
- })();
3050
- }, { selector: domSelector, callbackName: exposedFunctionName, cleanerName });
3051
- logger9.success("useCaptchaMonitor", `DOM \u76D1\u63A7\u5DF2\u542F\u7528\uFF1A${domSelector}`);
3052
- cleanupFns.push(async () => {
3053
- try {
3054
- await page.evaluate((name) => {
3055
- if (window[name]) {
3056
- window[name]();
3057
- delete window[name];
3058
- }
3059
- }, cleanerName);
3060
- } catch {
3061
- }
3062
- });
3063
- }
3064
- if (urlPattern) {
3065
- frameHandler = async (frame) => {
3066
- if (frame !== page.mainFrame()) {
3067
- return;
3068
- }
3069
- const currentUrl = page.url();
3070
- if (currentUrl.includes(urlPattern)) {
3071
- await triggerDetected();
3072
- }
3073
- };
3074
- page.on("framenavigated", frameHandler);
3075
- logger9.success("useCaptchaMonitor", `URL \u76D1\u63A7\u5DF2\u542F\u7528\uFF1A${urlPattern}`);
3076
- cleanupFns.push(async () => {
3077
- page.off("framenavigated", frameHandler);
3078
- });
3079
- }
3080
- return {
3081
- stop: async () => {
3082
- logger9.info("\u6B63\u5728\u505C\u6B62\u9A8C\u8BC1\u7801\u76D1\u63A7...");
3083
- for (const fn of cleanupFns) {
3084
- await fn();
3085
- }
3086
- isStopped = true;
3087
- }
3088
- };
3089
- }
3090
- var callCaptchaRecognitionApi = async (imageBase64, { apiUrl, apiType, token }) => {
3091
- const response = await fetch(apiUrl, {
3092
- method: "POST",
3093
- headers: {
3094
- "Content-Type": "application/json"
3095
- },
3096
- body: JSON.stringify({
3097
- type: apiType,
3098
- image: imageBase64,
3099
- token
3100
- })
3101
- });
3102
- if (!response.ok) {
3103
- throw new Error(`Captcha API request failed with status ${response.status}`);
3104
- }
3105
- return await response.json();
3106
- };
3107
3072
  var extractCaptchaSerialNumbers = (apiResponse) => {
3108
3073
  const serialNumbers = apiResponse?.data?.data?.serial_number;
3109
3074
  if (!Array.isArray(serialNumbers)) {
@@ -3111,56 +3076,6 @@ var extractCaptchaSerialNumbers = (apiResponse) => {
3111
3076
  }
3112
3077
  return serialNumbers.map((value) => Number(value)).filter((value) => Number.isInteger(value) && value >= 0);
3113
3078
  };
3114
- var waitForVisible = async (locator, timeout) => {
3115
- try {
3116
- await locator.waitFor({
3117
- state: "visible",
3118
- timeout
3119
- });
3120
- return true;
3121
- } catch {
3122
- return false;
3123
- }
3124
- };
3125
- var isAnyCaptchaTextVisible = async (frame, texts, timeout) => {
3126
- for (const text of texts || []) {
3127
- if (!text) {
3128
- continue;
3129
- }
3130
- const candidates = [
3131
- frame.getByText(text, { exact: false }).first(),
3132
- frame.locator(`text=${text}`).first()
3133
- ];
3134
- for (const candidate of candidates) {
3135
- const isVisible = await candidate.isVisible({ timeout }).catch(() => false);
3136
- if (isVisible) {
3137
- return true;
3138
- }
3139
- }
3140
- }
3141
- return false;
3142
- };
3143
- var waitForCaptchaChallengeReady = async (page, frame, options) => {
3144
- const deadline = Date.now() + options.challengeReadyTimeoutMs;
3145
- let hasSeenLoading = false;
3146
- while (Date.now() < deadline) {
3147
- const isLoadingVisible = await isAnyCaptchaTextVisible(
3148
- frame,
3149
- options.loadingTexts,
3150
- options.loadingIndicatorVisibleTimeoutMs
3151
- );
3152
- hasSeenLoading = hasSeenLoading || isLoadingVisible;
3153
- const sourceImages = frame.locator(options.sourceImageSelector);
3154
- const imageCount = await sourceImages.count().catch(() => 0);
3155
- const hasVisibleSourceImage = imageCount > 0 ? await sourceImages.first().isVisible({ timeout: options.loadingIndicatorVisibleTimeoutMs }).catch(() => false) : false;
3156
- if (!isLoadingVisible && hasVisibleSourceImage) {
3157
- logger9.info(hasSeenLoading ? "\u9A8C\u8BC1\u7801\u56FE\u7247\u5DF2\u52A0\u8F7D\u5B8C\u6210\u3002" : "\u9A8C\u8BC1\u7801\u56FE\u7247\u5DF2\u5C31\u7EEA\u3002");
3158
- return;
3159
- }
3160
- await page.waitForTimeout(options.challengeReadyPollMs);
3161
- }
3162
- throw new Error("Captcha challenge is still loading and did not become ready in time.");
3163
- };
3164
3079
  var resolveContentFrame = async (page, iframeLocator, options) => {
3165
3080
  for (let attempt = 1; attempt <= options.contentFrameResolveRetries; attempt++) {
3166
3081
  const iframeHandle = await iframeLocator.elementHandle();
@@ -3207,22 +3122,14 @@ var getVerifycenterCaptchaContext = async (page, options) => {
3207
3122
  }
3208
3123
  return { iframeLocator, frame };
3209
3124
  };
3210
- var clickCaptchaAction = async (frame, texts, options) => {
3211
- for (const text of texts) {
3212
- const candidates = [
3213
- frame.getByText(text, { exact: false }).first(),
3214
- frame.locator(`text=${text}`).first()
3215
- ];
3216
- for (const candidate of candidates) {
3217
- const isVisible = await waitForVisible(candidate, options.actionVisibleTimeoutMs);
3218
- if (!isVisible) {
3219
- continue;
3220
- }
3221
- await candidate.click();
3222
- return true;
3223
- }
3125
+ var refreshCaptcha = async (page, frame, options) => {
3126
+ const clicked = await clickCaptchaAction(frame, options.refreshTexts, options).catch(() => false);
3127
+ if (!clicked) {
3128
+ logger9.warn("Refresh button not found.");
3129
+ return false;
3224
3130
  }
3225
- return false;
3131
+ await page.waitForTimeout(options.refreshWaitMs);
3132
+ return true;
3226
3133
  };
3227
3134
  var findCaptchaDropTarget = async (frame, options) => {
3228
3135
  for (const text of options.dropTargetTexts) {
@@ -3239,47 +3146,52 @@ var findCaptchaDropTarget = async (frame, options) => {
3239
3146
  }
3240
3147
  return null;
3241
3148
  };
3242
- var dragCaptchaWithMouse = async (page, sourceLocator, targetLocator) => {
3243
- const sourceBox = await sourceLocator.boundingBox();
3244
- const targetBox = await targetLocator.boundingBox();
3245
- if (!sourceBox || !targetBox) {
3246
- throw new Error("Unable to resolve captcha drag coordinates.");
3247
- }
3248
- const startX = sourceBox.x + sourceBox.width / 2;
3249
- const startY = sourceBox.y + sourceBox.height / 2;
3250
- const endX = targetBox.x + targetBox.width / 2;
3251
- const endY = targetBox.y + targetBox.height / 2;
3252
- const steps = 10;
3253
- const liftOffsetX = Math.min(18, Math.max(8, sourceBox.width * 0.12));
3254
- const liftOffsetY = Math.min(12, Math.max(4, sourceBox.height * 0.08));
3255
- await page.mouse.move(startX, startY, { steps: 8 });
3256
- await page.waitForTimeout(250);
3257
- await page.mouse.down();
3258
- await page.waitForTimeout(350);
3259
- await page.mouse.move(startX + liftOffsetX, startY + liftOffsetY, { steps: 6 });
3260
- await page.waitForTimeout(250);
3261
- for (let step = 1; step <= steps; step++) {
3262
- const progress = step / steps;
3263
- const easedProgress = 1 - (1 - progress) * (1 - progress);
3264
- const currentX = startX + liftOffsetX + (endX - startX - liftOffsetX) * easedProgress;
3265
- const currentY = startY + liftOffsetY + (endY - startY - liftOffsetY) * easedProgress;
3266
- await page.mouse.move(currentX, currentY, { steps: 2 });
3267
- await page.waitForTimeout(90);
3149
+ var waitForCaptchaChallengeReady = async (page, frame, options) => {
3150
+ const deadline = Date.now() + options.challengeReadyTimeoutMs;
3151
+ let refreshDeadline = Date.now() + options.challengeReadyRefreshTimeoutMs;
3152
+ let hasSeenLoading = false;
3153
+ while (Date.now() < deadline) {
3154
+ const isLoadingVisible = await isAnyCaptchaTextVisible(
3155
+ frame,
3156
+ options.loadingTexts,
3157
+ options.loadingIndicatorVisibleTimeoutMs
3158
+ );
3159
+ const hasErrorTextVisible = await isAnyCaptchaTextVisible(
3160
+ frame,
3161
+ options.errorTexts,
3162
+ options.loadingIndicatorVisibleTimeoutMs
3163
+ );
3164
+ hasSeenLoading = hasSeenLoading || isLoadingVisible;
3165
+ const sourceImages = frame.locator(options.sourceImageSelector);
3166
+ const imageCount = await sourceImages.count().catch(() => 0);
3167
+ const hasVisibleSourceImage = imageCount > 0 ? await sourceImages.first().isVisible({ timeout: options.loadingIndicatorVisibleTimeoutMs }).catch(() => false) : false;
3168
+ if (!isLoadingVisible && hasVisibleSourceImage) {
3169
+ logger9.info(hasSeenLoading ? "\u9A8C\u8BC1\u7801\u56FE\u7247\u5DF2\u52A0\u8F7D\u5B8C\u6210\u3002" : "\u9A8C\u8BC1\u7801\u56FE\u7247\u5DF2\u5C31\u7EEA\u3002");
3170
+ return;
3171
+ }
3172
+ if (hasErrorTextVisible) {
3173
+ logger9.warn("\u9A8C\u8BC1\u7801\u9762\u677F\u51FA\u73B0\u7F51\u7EDC\u5F02\u5E38\u6587\u6848\uFF0C\u5C1D\u8BD5\u7ACB\u5373\u5237\u65B0\u9898\u76EE\u3002");
3174
+ await refreshCaptcha(page, frame, options);
3175
+ refreshDeadline = Date.now() + options.challengeReadyRefreshTimeoutMs;
3176
+ hasSeenLoading = false;
3177
+ continue;
3178
+ }
3179
+ if (!hasVisibleSourceImage && Date.now() >= refreshDeadline) {
3180
+ logger9.warn(`\u9A8C\u8BC1\u7801\u56FE\u7247\u8D85\u8FC7 ${options.challengeReadyRefreshTimeoutMs}ms \u4ECD\u672A\u51FA\u73B0\uFF0C\u5C1D\u8BD5\u5237\u65B0\u9898\u76EE\u3002`);
3181
+ await refreshCaptcha(page, frame, options);
3182
+ refreshDeadline = Date.now() + options.challengeReadyRefreshTimeoutMs;
3183
+ hasSeenLoading = false;
3184
+ continue;
3185
+ }
3186
+ await page.waitForTimeout(options.challengeReadyPollMs);
3268
3187
  }
3269
- await page.waitForTimeout(100);
3270
- await page.mouse.up();
3271
- await page.waitForTimeout(100);
3188
+ throw new Error("Captcha challenge is still loading and did not become ready in time.");
3272
3189
  };
3273
- var refreshCaptcha = async (page, frame, options) => {
3274
- const clicked = await clickCaptchaAction(frame, options.refreshTexts, options).catch(() => false);
3275
- if (!clicked) {
3276
- logger9.warn("Refresh button not found.");
3277
- return false;
3190
+ async function solveCaptcha(page, options = {}, dependencies = {}) {
3191
+ const { callCaptchaRecognitionApi: callCaptchaRecognitionApi2 } = dependencies;
3192
+ if (typeof callCaptchaRecognitionApi2 !== "function") {
3193
+ throw new Error("[Captcha] \u7F3A\u5C11\u901A\u7528\u8BC6\u522B\u8BF7\u6C42\u51FD\u6570 callCaptchaRecognitionApi\u3002");
3278
3194
  }
3279
- await page.waitForTimeout(options.refreshWaitMs);
3280
- return true;
3281
- };
3282
- async function solveBytedanceCaptcha(page, options = {}) {
3283
3195
  const config = {
3284
3196
  ...DEFAULT_BYTEDANCE_CAPTCHA_OPTIONS,
3285
3197
  ...options
@@ -3288,6 +3200,7 @@ async function solveBytedanceCaptcha(page, options = {}) {
3288
3200
  logger9.warn("\u7F3A\u5C11\u9A8C\u8BC1\u7801 token\uFF0C\u8DF3\u8FC7\u81EA\u52A8\u8BC6\u522B\u3002");
3289
3201
  return false;
3290
3202
  }
3203
+ logger9.info("\u5F53\u524D\u4F7F\u7528\u672Ctool\u2014\u2014\u6D4B\u8BD5\u7248\u672C");
3291
3204
  for (let attempt = 1; attempt <= config.maxRetries; attempt++) {
3292
3205
  logger9.info(`\u5F00\u59CB\u7B2C ${attempt}/${config.maxRetries} \u6B21 verifycenter \u9A8C\u8BC1\u7801\u8BC6\u522B\u3002`);
3293
3206
  try {
@@ -3300,10 +3213,12 @@ async function solveBytedanceCaptcha(page, options = {}) {
3300
3213
  await waitForCaptchaChallengeReady(page, frame, config);
3301
3214
  await page.waitForTimeout(config.recognitionDelayMs);
3302
3215
  const screenshotBuffer = await iframeLocator.screenshot();
3303
- const apiResponse = await callCaptchaRecognitionApi(
3304
- screenshotBuffer.toString("base64"),
3305
- config
3306
- );
3216
+ const apiResponse = await callCaptchaRecognitionApi2({
3217
+ apiUrl: config.apiUrl,
3218
+ type: config.apiType,
3219
+ image: screenshotBuffer.toString("base64"),
3220
+ token: config.token
3221
+ });
3307
3222
  const serialNumbers = extractCaptchaSerialNumbers(apiResponse);
3308
3223
  if (apiResponse?.code !== config.recognitionSuccessCode || serialNumbers.length === 0) {
3309
3224
  logger9.warn(
@@ -3359,15 +3274,178 @@ async function solveBytedanceCaptcha(page, options = {}) {
3359
3274
  logger9.error(`\u91CD\u8BD5 ${config.maxRetries} \u6B21\u540E\uFF0C\u9A8C\u8BC1\u7801\u4ECD\u672A\u8BC6\u522B\u6210\u529F\u3002`);
3360
3275
  return false;
3361
3276
  }
3277
+ var sloveCaptcha = solveCaptcha;
3278
+
3279
+ // src/chaptcha.js
3280
+ var logger10 = createInternalLogger("Captcha");
3281
+ var DEFAULT_CAPTCHA_RECOGNITION_OPTIONS = Object.freeze({
3282
+ token: "eKJvBfwfN0YRav0-VD_44E2VBSfm7l0YtddUQ7cFySI",
3283
+ apiUrl: "https://api.jfbym.com/api/YmServer/customApi"
3284
+ });
3285
+ var CAPTCHA_STRATEGIES = Object.freeze({
3286
+ bytedance: {
3287
+ sloveCaptcha
3288
+ }
3289
+ });
3290
+ var mergeDefinedOptions = (...sources) => {
3291
+ const merged = {};
3292
+ for (const source of sources) {
3293
+ for (const [key, value] of Object.entries(source || {})) {
3294
+ if (value !== void 0) {
3295
+ merged[key] = value;
3296
+ }
3297
+ }
3298
+ }
3299
+ return merged;
3300
+ };
3301
+ function useCaptchaMonitor(page, options) {
3302
+ const { domSelector, urlPattern, onDetected } = options;
3303
+ if (!domSelector && !urlPattern) {
3304
+ throw new Error("[CaptchaMonitor] \u5FC5\u987B\u63D0\u4F9B domSelector \u6216 urlPattern\u3002");
3305
+ }
3306
+ if (!onDetected || typeof onDetected !== "function") {
3307
+ throw new Error("[CaptchaMonitor] onDetected \u5FC5\u987B\u662F\u51FD\u6570\u3002");
3308
+ }
3309
+ let isStopped = false;
3310
+ let isHandling = false;
3311
+ let frameHandler = null;
3312
+ let exposedFunctionName = null;
3313
+ const triggerDetected = async () => {
3314
+ if (isStopped || isHandling) return;
3315
+ isHandling = true;
3316
+ try {
3317
+ await onDetected();
3318
+ } finally {
3319
+ isHandling = false;
3320
+ }
3321
+ };
3322
+ const cleanupFns = [];
3323
+ if (domSelector) {
3324
+ exposedFunctionName = `__c_d_${uuidv4().replace(/-/g, "_")}`;
3325
+ const cleanerName = `__c_cleaner_${uuidv4().replace(/-/g, "_")}`;
3326
+ page.exposeFunction(exposedFunctionName, triggerDetected).catch(() => {
3327
+ });
3328
+ page.addInitScript(({ selector, callbackName, cleanerName: cleanupName }) => {
3329
+ (() => {
3330
+ let observer = null;
3331
+ const checkAndReport = () => {
3332
+ const element = document.querySelector(selector);
3333
+ if (!element) {
3334
+ return false;
3335
+ }
3336
+ if (window[callbackName]) {
3337
+ window[callbackName]();
3338
+ }
3339
+ return true;
3340
+ };
3341
+ checkAndReport();
3342
+ observer = new MutationObserver((mutations) => {
3343
+ const shouldCheck = mutations.some((mutation) => mutation.addedNodes.length > 0);
3344
+ if (shouldCheck && observer) {
3345
+ checkAndReport();
3346
+ }
3347
+ });
3348
+ const mountObserver = () => {
3349
+ const target = document.documentElement;
3350
+ if (target && observer) {
3351
+ observer.observe(target, { childList: true, subtree: true });
3352
+ }
3353
+ };
3354
+ if (document.readyState === "loading") {
3355
+ window.addEventListener("DOMContentLoaded", mountObserver);
3356
+ } else {
3357
+ mountObserver();
3358
+ }
3359
+ window[cleanupName] = () => {
3360
+ if (observer) {
3361
+ observer.disconnect();
3362
+ observer = null;
3363
+ }
3364
+ };
3365
+ })();
3366
+ }, { selector: domSelector, callbackName: exposedFunctionName, cleanerName });
3367
+ logger10.success("useCaptchaMonitor", `DOM \u76D1\u63A7\u5DF2\u542F\u7528\uFF1A${domSelector}`);
3368
+ cleanupFns.push(async () => {
3369
+ try {
3370
+ await page.evaluate((name) => {
3371
+ if (window[name]) {
3372
+ window[name]();
3373
+ delete window[name];
3374
+ }
3375
+ }, cleanerName);
3376
+ } catch {
3377
+ }
3378
+ });
3379
+ }
3380
+ if (urlPattern) {
3381
+ frameHandler = async (frame) => {
3382
+ if (frame !== page.mainFrame()) {
3383
+ return;
3384
+ }
3385
+ const currentUrl = page.url();
3386
+ if (currentUrl.includes(urlPattern)) {
3387
+ await triggerDetected();
3388
+ }
3389
+ };
3390
+ page.on("framenavigated", frameHandler);
3391
+ logger10.success("useCaptchaMonitor", `URL \u76D1\u63A7\u5DF2\u542F\u7528\uFF1A${urlPattern}`);
3392
+ cleanupFns.push(async () => {
3393
+ page.off("framenavigated", frameHandler);
3394
+ });
3395
+ }
3396
+ return {
3397
+ stop: async () => {
3398
+ logger10.info("\u6B63\u5728\u505C\u6B62\u9A8C\u8BC1\u7801\u76D1\u63A7...");
3399
+ for (const fn of cleanupFns) {
3400
+ await fn();
3401
+ }
3402
+ isStopped = true;
3403
+ }
3404
+ };
3405
+ }
3406
+ var callCaptchaRecognitionApi = async (requestParams = {}) => {
3407
+ const { apiUrl, ...payload } = mergeDefinedOptions(
3408
+ DEFAULT_CAPTCHA_RECOGNITION_OPTIONS,
3409
+ requestParams
3410
+ );
3411
+ if (!apiUrl) {
3412
+ throw new Error("[Captcha] \u7F3A\u5C11\u9A8C\u8BC1\u7801\u8BC6\u522B\u63A5\u53E3\u5730\u5740 apiUrl\u3002");
3413
+ }
3414
+ const response = await fetch(apiUrl, {
3415
+ method: "POST",
3416
+ headers: {
3417
+ "Content-Type": "application/json"
3418
+ },
3419
+ body: JSON.stringify(payload)
3420
+ });
3421
+ if (!response.ok) {
3422
+ throw new Error(`Captcha API request failed with status ${response.status}`);
3423
+ }
3424
+ return await response.json();
3425
+ };
3426
+ async function solveCaptchaWithStrategy(strategyName, page, options = {}) {
3427
+ const strategy = CAPTCHA_STRATEGIES[strategyName];
3428
+ if (!strategy?.sloveCaptcha) {
3429
+ throw new Error(`[Captcha] \u672A\u627E\u5230\u9A8C\u8BC1\u7801\u7B56\u7565\uFF1A${strategyName}`);
3430
+ }
3431
+ const resolvedOptions = mergeDefinedOptions(
3432
+ DEFAULT_CAPTCHA_RECOGNITION_OPTIONS,
3433
+ options
3434
+ );
3435
+ return strategy.sloveCaptcha(page, resolvedOptions, {
3436
+ callCaptchaRecognitionApi,
3437
+ logger: logger10
3438
+ });
3439
+ }
3362
3440
  var Captcha = {
3363
3441
  useCaptchaMonitor,
3364
- solveBytedanceCaptcha
3442
+ solveCaptchaWithStrategy
3365
3443
  };
3366
3444
 
3367
3445
  // src/mutation.js
3368
3446
  import { createHash } from "node:crypto";
3369
3447
  import { v4 as uuidv42 } from "uuid";
3370
- var logger10 = createInternalLogger("Mutation");
3448
+ var logger11 = createInternalLogger("Mutation");
3371
3449
  var MUTATION_MONITOR_MODE = Object.freeze({
3372
3450
  Added: "added",
3373
3451
  Changed: "changed",
@@ -3400,14 +3478,14 @@ var Mutation = {
3400
3478
  const stableTime = options.stableTime ?? 5 * 1e3;
3401
3479
  const timeout = options.timeout ?? 120 * 1e3;
3402
3480
  const onMutation = options.onMutation;
3403
- logger10.start("waitForStable", `\u76D1\u63A7 ${selectorList.length} \u4E2A\u9009\u62E9\u5668, \u7A33\u5B9A\u65F6\u95F4=${stableTime}ms`);
3481
+ logger11.start("waitForStable", `\u76D1\u63A7 ${selectorList.length} \u4E2A\u9009\u62E9\u5668, \u7A33\u5B9A\u65F6\u95F4=${stableTime}ms`);
3404
3482
  if (initialTimeout > 0) {
3405
3483
  const selectorQuery = selectorList.join(",");
3406
3484
  try {
3407
3485
  await page.waitForSelector(selectorQuery, { timeout: initialTimeout });
3408
- logger10.info(`waitForStable \u5DF2\u68C0\u6D4B\u5230\u5143\u7D20: ${selectorQuery}`);
3486
+ logger11.info(`waitForStable \u5DF2\u68C0\u6D4B\u5230\u5143\u7D20: ${selectorQuery}`);
3409
3487
  } catch (e) {
3410
- logger10.warning(`waitForStable \u521D\u59CB\u7B49\u5F85\u8D85\u65F6 (${initialTimeout}ms): ${selectorQuery}`);
3488
+ logger11.warning(`waitForStable \u521D\u59CB\u7B49\u5F85\u8D85\u65F6 (${initialTimeout}ms): ${selectorQuery}`);
3411
3489
  throw e;
3412
3490
  }
3413
3491
  }
@@ -3423,7 +3501,7 @@ var Mutation = {
3423
3501
  return "__CONTINUE__";
3424
3502
  }
3425
3503
  });
3426
- logger10.info("waitForStable \u5DF2\u542F\u7528 onMutation \u56DE\u8C03");
3504
+ logger11.info("waitForStable \u5DF2\u542F\u7528 onMutation \u56DE\u8C03");
3427
3505
  } catch (e) {
3428
3506
  }
3429
3507
  }
@@ -3538,9 +3616,9 @@ var Mutation = {
3538
3616
  { selectorList, stableTime, timeout, callbackName, hasCallback: !!onMutation }
3539
3617
  );
3540
3618
  if (result.mutationCount === 0 && result.stableTime === 0) {
3541
- logger10.warning("waitForStable \u672A\u627E\u5230\u53EF\u76D1\u63A7\u7684\u5143\u7D20");
3619
+ logger11.warning("waitForStable \u672A\u627E\u5230\u53EF\u76D1\u63A7\u7684\u5143\u7D20");
3542
3620
  }
3543
- logger10.success("waitForStable", `DOM \u7A33\u5B9A, \u603B\u5171 ${result.mutationCount} \u6B21\u53D8\u5316${result.wasPaused ? ", \u66FE\u6682\u505C\u8BA1\u65F6" : ""}`);
3621
+ logger11.success("waitForStable", `DOM \u7A33\u5B9A, \u603B\u5171 ${result.mutationCount} \u6B21\u53D8\u5316${result.wasPaused ? ", \u66FE\u6682\u505C\u8BA1\u65F6" : ""}`);
3544
3622
  return result;
3545
3623
  },
3546
3624
  /**
@@ -3712,22 +3790,22 @@ var Mutation = {
3712
3790
  return "__CONTINUE__";
3713
3791
  }
3714
3792
  };
3715
- logger10.start(
3793
+ logger11.start(
3716
3794
  "waitForStableAcrossRoots",
3717
3795
  `\u76D1\u63A7 ${selectorList.length} \u4E2A\u9009\u62E9\u5668(\u8DE8 root), \u7A33\u5B9A\u65F6\u95F4=${waitForStableTime}ms`
3718
3796
  );
3719
3797
  if (initialTimeout > 0) {
3720
3798
  try {
3721
3799
  await page.waitForSelector(selectorQuery, { timeout: initialTimeout });
3722
- logger10.info(`waitForStableAcrossRoots \u5DF2\u68C0\u6D4B\u5230\u5143\u7D20: ${selectorQuery}`);
3800
+ logger11.info(`waitForStableAcrossRoots \u5DF2\u68C0\u6D4B\u5230\u5143\u7D20: ${selectorQuery}`);
3723
3801
  } catch (e) {
3724
- logger10.warning(`waitForStableAcrossRoots \u521D\u59CB\u7B49\u5F85\u8D85\u65F6 (${initialTimeout}ms): ${selectorQuery}`);
3802
+ logger11.warning(`waitForStableAcrossRoots \u521D\u59CB\u7B49\u5F85\u8D85\u65F6 (${initialTimeout}ms): ${selectorQuery}`);
3725
3803
  throw e;
3726
3804
  }
3727
3805
  }
3728
3806
  let state = await buildState();
3729
3807
  if (!state?.hasMatched) {
3730
- logger10.warning("waitForStableAcrossRoots \u672A\u627E\u5230\u53EF\u76D1\u63A7\u7684\u5143\u7D20");
3808
+ logger11.warning("waitForStableAcrossRoots \u672A\u627E\u5230\u53EF\u76D1\u63A7\u7684\u5143\u7D20");
3731
3809
  return { mutationCount: 0, stableTime: 0, wasPaused: false };
3732
3810
  }
3733
3811
  let mutationCount = 0;
@@ -3764,7 +3842,7 @@ var Mutation = {
3764
3842
  if (lastState.snapshotKey !== lastSnapshotKey) {
3765
3843
  lastSnapshotKey = lastState.snapshotKey;
3766
3844
  mutationCount += 1;
3767
- logger10.info(
3845
+ logger11.info(
3768
3846
  `waitForStableAcrossRoots \u53D8\u5316#${mutationCount}, len=${lastState.snapshotLength}, path=${lastState.primaryPath || "unknown"}, preview="${truncate(lastState.text, 120)}"`
3769
3847
  );
3770
3848
  const signal = await invokeMutationCallback({
@@ -3777,7 +3855,7 @@ var Mutation = {
3777
3855
  continue;
3778
3856
  }
3779
3857
  if (!isPaused && stableSince > 0 && Date.now() - stableSince >= waitForStableTime) {
3780
- logger10.success("waitForStableAcrossRoots", `DOM \u7A33\u5B9A, \u603B\u5171 ${mutationCount} \u6B21\u53D8\u5316${wasPaused ? ", \u66FE\u6682\u505C\u8BA1\u65F6" : ""}`);
3858
+ logger11.success("waitForStableAcrossRoots", `DOM \u7A33\u5B9A, \u603B\u5171 ${mutationCount} \u6B21\u53D8\u5316${wasPaused ? ", \u66FE\u6682\u505C\u8BA1\u65F6" : ""}`);
3781
3859
  return {
3782
3860
  mutationCount,
3783
3861
  stableTime: waitForStableTime,
@@ -3804,7 +3882,7 @@ var Mutation = {
3804
3882
  const onMutation = options.onMutation;
3805
3883
  const rawMode = String(options.mode || MUTATION_MONITOR_MODE.Added).toLowerCase();
3806
3884
  const mode = [MUTATION_MONITOR_MODE.Added, MUTATION_MONITOR_MODE.Changed, MUTATION_MONITOR_MODE.All].includes(rawMode) ? rawMode : MUTATION_MONITOR_MODE.Added;
3807
- logger10.start("useMonitor", `\u76D1\u63A7 ${selectorList.length} \u4E2A\u9009\u62E9\u5668, mode=${mode}`);
3885
+ logger11.start("useMonitor", `\u76D1\u63A7 ${selectorList.length} \u4E2A\u9009\u62E9\u5668, mode=${mode}`);
3808
3886
  const monitorKey = generateKey("pk_mon");
3809
3887
  const callbackName = generateKey("pk_mon_cb");
3810
3888
  const cleanerName = generateKey("pk_mon_clean");
@@ -3947,7 +4025,7 @@ var Mutation = {
3947
4025
  return total;
3948
4026
  };
3949
4027
  }, { selectorList, monitorKey, callbackName, cleanerName, hasCallback: !!onMutation, mode });
3950
- logger10.success("useMonitor", "\u76D1\u63A7\u5668\u5DF2\u542F\u52A8");
4028
+ logger11.success("useMonitor", "\u76D1\u63A7\u5668\u5DF2\u542F\u52A8");
3951
4029
  return {
3952
4030
  stop: async () => {
3953
4031
  let totalMutations = 0;
@@ -3960,7 +4038,7 @@ var Mutation = {
3960
4038
  }, cleanerName);
3961
4039
  } catch (e) {
3962
4040
  }
3963
- logger10.success("useMonitor.stop", `\u76D1\u63A7\u5DF2\u505C\u6B62, \u5171 ${totalMutations} \u6B21\u53D8\u5316`);
4041
+ logger11.success("useMonitor.stop", `\u76D1\u63A7\u5DF2\u505C\u6B62, \u5171 ${totalMutations} \u6B21\u53D8\u5316`);
3964
4042
  return { totalMutations };
3965
4043
  }
3966
4044
  };
@@ -4829,7 +4907,7 @@ var createTemplateLogger = (baseLogger = createBaseLogger()) => {
4829
4907
  };
4830
4908
  var getDefaultBaseLogger = () => createBaseLogger("");
4831
4909
  var Logger = {
4832
- setLogger: (logger13) => setDefaultLogger(logger13),
4910
+ setLogger: (logger14) => setDefaultLogger(logger14),
4833
4911
  info: (message) => getDefaultBaseLogger().info(message),
4834
4912
  success: (message) => getDefaultBaseLogger().success(message),
4835
4913
  warning: (message) => getDefaultBaseLogger().warning(message),
@@ -4837,8 +4915,8 @@ var Logger = {
4837
4915
  error: (message) => getDefaultBaseLogger().error(message),
4838
4916
  debug: (message) => getDefaultBaseLogger().debug(message),
4839
4917
  start: (message) => getDefaultBaseLogger().start(message),
4840
- useTemplate: (logger13) => {
4841
- if (logger13) return createTemplateLogger(createBaseLogger("", logger13));
4918
+ useTemplate: (logger14) => {
4919
+ if (logger14) return createTemplateLogger(createBaseLogger("", logger14));
4842
4920
  return createTemplateLogger();
4843
4921
  }
4844
4922
  };
@@ -4903,7 +4981,7 @@ var LOCATION_NETWORK_SUFFIX_PATTERNS = [
4903
4981
  ];
4904
4982
  var cachedStripLogoSrcPromise = null;
4905
4983
  var cachedEnrichmentByContext = /* @__PURE__ */ new WeakMap();
4906
- var logger11 = createInternalLogger("Watermarkify");
4984
+ var logger12 = createInternalLogger("Watermarkify");
4907
4985
  var normalizeText = (value) => String(value || "").trim();
4908
4986
  var toInline = (value, maxLen = 200) => {
4909
4987
  const text = normalizeText(value);
@@ -5145,9 +5223,9 @@ var resolveWithCustomResolver = async (page, baseMeta, options = {}) => {
5145
5223
  location: toInline(resolved.location, 80)
5146
5224
  };
5147
5225
  if (enrichment.ip || enrichment.location) {
5148
- logger11.info(`\u81EA\u5B9A\u4E49 resolver \u547D\u4E2D: ip=${enrichment.ip || "-"}, loc=${enrichment.location || "-"}`);
5226
+ logger12.info(`\u81EA\u5B9A\u4E49 resolver \u547D\u4E2D: ip=${enrichment.ip || "-"}, loc=${enrichment.location || "-"}`);
5149
5227
  } else {
5150
- logger11.warning("\u81EA\u5B9A\u4E49 resolver \u5DF2\u6267\u884C\uFF0C\u4F46\u672A\u8FD4\u56DE IP/Loc");
5228
+ logger12.warning("\u81EA\u5B9A\u4E49 resolver \u5DF2\u6267\u884C\uFF0C\u4F46\u672A\u8FD4\u56DE IP/Loc");
5151
5229
  }
5152
5230
  return enrichment;
5153
5231
  } finally {
@@ -5331,12 +5409,12 @@ var buildWatermarkifyRenderHtml = ({ imageSrc, overlaySvg, width, height }) => {
5331
5409
  };
5332
5410
  var composeScreenshotBufferWithBrowser = async (page, buffer, overlaySvg, imageInfo = {}) => {
5333
5411
  if (!page || typeof page.context !== "function") {
5334
- logger11.warning("watermarkify \u6D4F\u89C8\u5668\u5408\u6210\u8DF3\u8FC7: \u7F3A\u5C11\u53EF\u7528 page");
5412
+ logger12.warning("watermarkify \u6D4F\u89C8\u5668\u5408\u6210\u8DF3\u8FC7: \u7F3A\u5C11\u53EF\u7528 page");
5335
5413
  return buffer;
5336
5414
  }
5337
5415
  const renderScope = await openProbePage(page);
5338
5416
  if (!renderScope?.page) {
5339
- logger11.warning("watermarkify \u6D4F\u89C8\u5668\u5408\u6210\u8DF3\u8FC7: \u65E0\u6CD5\u521B\u5EFA render page");
5417
+ logger12.warning("watermarkify \u6D4F\u89C8\u5668\u5408\u6210\u8DF3\u8FC7: \u65E0\u6CD5\u521B\u5EFA render page");
5340
5418
  return buffer;
5341
5419
  }
5342
5420
  try {
@@ -5379,13 +5457,13 @@ var composeScreenshotBufferWithBrowser = async (page, buffer, overlaySvg, imageI
5379
5457
  fullPage: true,
5380
5458
  animations: "disabled"
5381
5459
  }).catch((error) => {
5382
- logger11.warning(`watermarkify \u6D4F\u89C8\u5668\u5408\u6210\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`);
5460
+ logger12.warning(`watermarkify \u6D4F\u89C8\u5668\u5408\u6210\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`);
5383
5461
  return null;
5384
5462
  });
5385
5463
  if (Buffer.isBuffer(composed) && composed.length > 0) {
5386
5464
  return composed;
5387
5465
  }
5388
- logger11.warning("watermarkify \u6D4F\u89C8\u5668\u5408\u6210\u5931\u8D25: \u672A\u5F97\u5230\u6709\u6548\u622A\u56FE\u7ED3\u679C");
5466
+ logger12.warning("watermarkify \u6D4F\u89C8\u5668\u5408\u6210\u5931\u8D25: \u672A\u5F97\u5230\u6709\u6548\u622A\u56FE\u7ED3\u679C");
5389
5467
  return buffer;
5390
5468
  } finally {
5391
5469
  await renderScope.close().catch(() => {
@@ -5398,7 +5476,7 @@ var resolveWithIpLookup = async (page, options = {}) => {
5398
5476
  }
5399
5477
  const probeScope = await openProbePage(page);
5400
5478
  if (!probeScope?.page) {
5401
- logger11.warning("ipLookup \u8DF3\u8FC7: \u65E0\u6CD5\u521B\u5EFA probe page");
5479
+ logger12.warning("ipLookup \u8DF3\u8FC7: \u65E0\u6CD5\u521B\u5EFA probe page");
5402
5480
  return null;
5403
5481
  }
5404
5482
  const timeoutMs = Math.max(
@@ -5407,12 +5485,12 @@ var resolveWithIpLookup = async (page, options = {}) => {
5407
5485
  );
5408
5486
  try {
5409
5487
  const probePage = probeScope.page;
5410
- logger11.info(`ipLookup \u5C1D\u8BD5: url=${DEFAULT_IP_LOOKUP_URL}, timeoutMs=${timeoutMs}`);
5488
+ logger12.info(`ipLookup \u5C1D\u8BD5: url=${DEFAULT_IP_LOOKUP_URL}, timeoutMs=${timeoutMs}`);
5411
5489
  const response = await probePage.goto(DEFAULT_IP_LOOKUP_URL, {
5412
5490
  waitUntil: "commit",
5413
5491
  timeout: timeoutMs
5414
5492
  }).catch((error) => {
5415
- logger11.warning(`ipLookup \u8BF7\u6C42\u5931\u8D25: url=${DEFAULT_IP_LOOKUP_URL}, error=${error instanceof Error ? error.message : String(error)}`);
5493
+ logger12.warning(`ipLookup \u8BF7\u6C42\u5931\u8D25: url=${DEFAULT_IP_LOOKUP_URL}, error=${error instanceof Error ? error.message : String(error)}`);
5416
5494
  return null;
5417
5495
  });
5418
5496
  const status = response && typeof response.status === "function" ? response.status() : 0;
@@ -5434,13 +5512,13 @@ var resolveWithIpLookup = async (page, options = {}) => {
5434
5512
  }
5435
5513
  const parsed = parseIpIpJsonResponse(rawText);
5436
5514
  if (parsed?.ip || parsed?.location) {
5437
- logger11.info(`ipLookup \u6210\u529F: url=${DEFAULT_IP_LOOKUP_URL}, status=${status || "-"}, contentType=${contentType || "-"}, ip=${parsed.ip || "-"}, loc=${parsed.location || "-"}`);
5515
+ logger12.info(`ipLookup \u6210\u529F: url=${DEFAULT_IP_LOOKUP_URL}, status=${status || "-"}, contentType=${contentType || "-"}, ip=${parsed.ip || "-"}, loc=${parsed.location || "-"}`);
5438
5516
  return parsed;
5439
5517
  }
5440
- logger11.warning(`ipLookup \u672A\u89E3\u6790\u51FA IP/Loc: url=${DEFAULT_IP_LOOKUP_URL}, status=${status || "-"}, contentType=${contentType || "-"}, preview=${shortenTail(rawText, 120) || "[empty]"}`);
5518
+ logger12.warning(`ipLookup \u672A\u89E3\u6790\u51FA IP/Loc: url=${DEFAULT_IP_LOOKUP_URL}, status=${status || "-"}, contentType=${contentType || "-"}, preview=${shortenTail(rawText, 120) || "[empty]"}`);
5441
5519
  return null;
5442
5520
  } catch (error) {
5443
- logger11.warning(`ipLookup \u6267\u884C\u5F02\u5E38\uFF0C\u672A\u83B7\u5F97 IP/Loc: ${error instanceof Error ? error.message : String(error)}`);
5521
+ logger12.warning(`ipLookup \u6267\u884C\u5F02\u5E38\uFF0C\u672A\u83B7\u5F97 IP/Loc: ${error instanceof Error ? error.message : String(error)}`);
5444
5522
  return null;
5445
5523
  } finally {
5446
5524
  await probeScope.close().catch(() => {
@@ -5454,10 +5532,10 @@ var resolveEnrichment = async (page, baseMeta, options) => {
5454
5532
  ip: toInline(options.ip, 80),
5455
5533
  location: toInline(options.location, 80)
5456
5534
  };
5457
- logger11.info(`enrichment \u5F00\u59CB: host=${baseMeta.hostname || "-"}, hasPresetIp=${Boolean(merged.ip)}, hasPresetLoc=${Boolean(merged.location)}, ipLookup=${options.ipLookup !== false}`);
5535
+ logger12.info(`enrichment \u5F00\u59CB: host=${baseMeta.hostname || "-"}, hasPresetIp=${Boolean(merged.ip)}, hasPresetLoc=${Boolean(merged.location)}, ipLookup=${options.ipLookup !== false}`);
5458
5536
  if (!merged.ip || !merged.location) {
5459
5537
  if (cached?.ip || cached?.location) {
5460
- logger11.info(`enrichment \u547D\u4E2D\u4E0A\u4E0B\u6587\u7F13\u5B58: ip=${cached.ip || "-"}, loc=${cached.location || "-"}`);
5538
+ logger12.info(`enrichment \u547D\u4E2D\u4E0A\u4E0B\u6587\u7F13\u5B58: ip=${cached.ip || "-"}, loc=${cached.location || "-"}`);
5461
5539
  }
5462
5540
  fillEnrichment(merged, cached);
5463
5541
  }
@@ -5481,15 +5559,15 @@ var resolveEnrichment = async (page, baseMeta, options) => {
5481
5559
  "x-geo-country"
5482
5560
  ]), 80);
5483
5561
  if (!merged.location || isWeakLocationValue(merged.location) && headerLocation) {
5484
- logger11.info(`enrichment \u4F7F\u7528\u54CD\u5E94\u5934\u8865\u5145 Loc: ${headerLocation || "-"}`);
5562
+ logger12.info(`enrichment \u4F7F\u7528\u54CD\u5E94\u5934\u8865\u5145 Loc: ${headerLocation || "-"}`);
5485
5563
  merged.location = headerLocation || merged.location;
5486
5564
  }
5487
5565
  }
5488
5566
  writeCachedEnrichment(page, merged);
5489
5567
  if (merged.ip || merged.location) {
5490
- logger11.info(`enrichment \u5B8C\u6210: ip=${merged.ip || "-"}, loc=${merged.location || "-"}`);
5568
+ logger12.info(`enrichment \u5B8C\u6210: ip=${merged.ip || "-"}, loc=${merged.location || "-"}`);
5491
5569
  } else {
5492
- logger11.warning("enrichment \u5B8C\u6210: \u672A\u83B7\u5F97 IP/Loc");
5570
+ logger12.warning("enrichment \u5B8C\u6210: \u672A\u83B7\u5F97 IP/Loc");
5493
5571
  }
5494
5572
  return merged;
5495
5573
  };
@@ -6157,7 +6235,7 @@ var watermarkifyScreenshotBuffer = async (buffer, meta, page = null) => {
6157
6235
  }
6158
6236
  const imageInfo = readImageInfo(buffer);
6159
6237
  if (!imageInfo.width || !imageInfo.height || !imageInfo.mimeType) {
6160
- logger11.warning("watermarkify \u8DF3\u8FC7: \u65E0\u6CD5\u89E3\u6790\u622A\u56FE\u5C3A\u5BF8\u6216\u683C\u5F0F");
6238
+ logger12.warning("watermarkify \u8DF3\u8FC7: \u65E0\u6CD5\u89E3\u6790\u622A\u56FE\u5C3A\u5BF8\u6216\u683C\u5F0F");
6161
6239
  return buffer;
6162
6240
  }
6163
6241
  const overlaySvg = buildWatermarkifySvg(meta, imageInfo.width, imageInfo.height);
@@ -6168,7 +6246,7 @@ var watermarkifyScreenshotBuffer = async (buffer, meta, page = null) => {
6168
6246
  };
6169
6247
 
6170
6248
  // src/share.js
6171
- var logger12 = createInternalLogger("Share");
6249
+ var logger13 = createInternalLogger("Share");
6172
6250
  var DEFAULT_TIMEOUT_MS2 = 50 * 1e3;
6173
6251
  var DEFAULT_PAYLOAD_SNAPSHOT_MAX_LEN = 500;
6174
6252
  var DEFAULT_POLL_INTERVAL_MS = 120;
@@ -6305,7 +6383,7 @@ var createDomShareMonitor = async (page, options = {}) => {
6305
6383
  const onMatch = typeof options.onMatch === "function" ? options.onMatch : null;
6306
6384
  const onTelemetry = typeof options.onTelemetry === "function" ? options.onTelemetry : null;
6307
6385
  let matched = false;
6308
- logger12.info(`DOM \u76D1\u542C\u51C6\u5907\u6302\u8F7D: selectors=${toJsonInline(selectors, 120)}, mode=${mode}`);
6386
+ logger13.info(`DOM \u76D1\u542C\u51C6\u5907\u6302\u8F7D: selectors=${toJsonInline(selectors, 120)}, mode=${mode}`);
6309
6387
  const monitor = await Mutation.useMonitor(page, selectors, {
6310
6388
  mode,
6311
6389
  onMutation: (context = {}) => {
@@ -6323,12 +6401,12 @@ ${text}`;
6323
6401
  });
6324
6402
  }
6325
6403
  if (mutationCount <= 5 || mutationCount % 50 === 0) {
6326
- logger12.info(`DOM \u53D8\u5316\u5DF2\u6355\u83B7: mutationCount=${mutationCount}, mutationNodes=${mutationNodes.length}`);
6404
+ logger13.info(`DOM \u53D8\u5316\u5DF2\u6355\u83B7: mutationCount=${mutationCount}, mutationNodes=${mutationNodes.length}`);
6327
6405
  }
6328
6406
  const [candidate] = Utils.parseLinks(rawDom, { prefix }) || [];
6329
6407
  if (!candidate) return;
6330
6408
  matched = true;
6331
- logger12.success("captureLink.domHit", `DOM \u547D\u4E2D\u5206\u4EAB\u94FE\u63A5: mutationCount=${mutationCount}, link=${candidate}`);
6409
+ logger13.success("captureLink.domHit", `DOM \u547D\u4E2D\u5206\u4EAB\u94FE\u63A5: mutationCount=${mutationCount}, link=${candidate}`);
6332
6410
  if (onMatch) {
6333
6411
  onMatch({
6334
6412
  link: candidate,
@@ -6344,7 +6422,7 @@ ${text}`;
6344
6422
  return {
6345
6423
  stop: async () => {
6346
6424
  const result = await monitor.stop();
6347
- logger12.info(`DOM \u76D1\u542C\u5DF2\u505C\u6B62: totalMutations=${result?.totalMutations || 0}`);
6425
+ logger13.info(`DOM \u76D1\u542C\u5DF2\u505C\u6B62: totalMutations=${result?.totalMutations || 0}`);
6348
6426
  return result;
6349
6427
  }
6350
6428
  };
@@ -6384,8 +6462,8 @@ var Share = {
6384
6462
  if (share.mode === "response" && apiMatchers.length === 0) {
6385
6463
  throw new Error("Share.captureLink requires share.xurl[0] api matcher when mode=response");
6386
6464
  }
6387
- logger12.start("captureLink", `mode=${share.mode}, timeoutMs=${timeoutMs}, prefix=${share.prefix}`);
6388
- logger12.info(`captureLink \u914D\u7F6E: xurl=${toJsonInline(share.xurl)}, domMode=${domMode}, domSelectors=${toJsonInline(domSelectors, 120)}`);
6465
+ logger13.start("captureLink", `mode=${share.mode}, timeoutMs=${timeoutMs}, prefix=${share.prefix}`);
6466
+ logger13.info(`captureLink \u914D\u7F6E: xurl=${toJsonInline(share.xurl)}, domMode=${domMode}, domSelectors=${toJsonInline(domSelectors, 120)}`);
6389
6467
  const stats = {
6390
6468
  actionTimedOut: false,
6391
6469
  domMutationCount: 0,
@@ -6410,7 +6488,7 @@ var Share = {
6410
6488
  link: validated,
6411
6489
  payloadText: String(payloadText || "")
6412
6490
  };
6413
- logger12.info(`\u5019\u9009\u94FE\u63A5\u5DF2\u786E\u8BA4: source=${source}, link=${validated}`);
6491
+ logger13.info(`\u5019\u9009\u94FE\u63A5\u5DF2\u786E\u8BA4: source=${source}, link=${validated}`);
6414
6492
  return true;
6415
6493
  };
6416
6494
  const resolveResponseCandidate = (responseText) => {
@@ -6445,7 +6523,7 @@ var Share = {
6445
6523
  try {
6446
6524
  await monitor.stop();
6447
6525
  } catch (error) {
6448
- logger12.warning(`\u505C\u6B62 DOM \u76D1\u542C\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`);
6526
+ logger13.warning(`\u505C\u6B62 DOM \u76D1\u542C\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`);
6449
6527
  }
6450
6528
  };
6451
6529
  const onResponse = async (response) => {
@@ -6458,29 +6536,29 @@ var Share = {
6458
6536
  stats.responseSampleUrls.push(url);
6459
6537
  }
6460
6538
  if (stats.responseObserved <= 5) {
6461
- logger12.info(`\u63A5\u53E3\u54CD\u5E94\u91C7\u6837(${stats.responseObserved}): ${url}`);
6539
+ logger13.info(`\u63A5\u53E3\u54CD\u5E94\u91C7\u6837(${stats.responseObserved}): ${url}`);
6462
6540
  }
6463
6541
  if (!apiMatchers.some((matcher) => url.includes(matcher))) return;
6464
6542
  stats.responseMatched += 1;
6465
6543
  stats.lastMatchedUrl = url;
6466
- logger12.info(`\u63A5\u53E3\u547D\u4E2D\u5339\u914D(${stats.responseMatched}): ${url}`);
6544
+ logger13.info(`\u63A5\u53E3\u547D\u4E2D\u5339\u914D(${stats.responseMatched}): ${url}`);
6467
6545
  const text = await response.text();
6468
6546
  const hit = resolveResponseCandidate(text);
6469
6547
  if (!hit?.link) {
6470
6548
  if (stats.responseMatched <= 3) {
6471
- logger12.info(`\u63A5\u53E3\u89E3\u6790\u5B8C\u6210\u4F46\u672A\u63D0\u53D6\u5230\u5206\u4EAB\u94FE\u63A5: payloadSize=${text.length}`);
6549
+ logger13.info(`\u63A5\u53E3\u89E3\u6790\u5B8C\u6210\u4F46\u672A\u63D0\u53D6\u5230\u5206\u4EAB\u94FE\u63A5: payloadSize=${text.length}`);
6472
6550
  }
6473
6551
  return;
6474
6552
  }
6475
6553
  stats.responseResolved += 1;
6476
- logger12.success("captureLink.responseHit", `\u63A5\u53E3\u547D\u4E2D\u5206\u4EAB\u94FE\u63A5: url=${url}, link=${hit.link}`);
6554
+ logger13.success("captureLink.responseHit", `\u63A5\u53E3\u547D\u4E2D\u5206\u4EAB\u94FE\u63A5: url=${url}, link=${hit.link}`);
6477
6555
  setCandidate("response", hit.link, hit.payloadText);
6478
6556
  } catch (error) {
6479
- logger12.warning(`\u63A5\u53E3\u54CD\u5E94\u5904\u7406\u5F02\u5E38: ${error instanceof Error ? error.message : String(error)}`);
6557
+ logger13.warning(`\u63A5\u53E3\u54CD\u5E94\u5904\u7406\u5F02\u5E38: ${error instanceof Error ? error.message : String(error)}`);
6480
6558
  }
6481
6559
  };
6482
6560
  if (share.mode === "dom") {
6483
- logger12.info("\u5F53\u524D\u4E3A DOM \u6A21\u5F0F\uFF0C\u4EC5\u542F\u7528 DOM \u76D1\u542C");
6561
+ logger13.info("\u5F53\u524D\u4E3A DOM \u6A21\u5F0F\uFF0C\u4EC5\u542F\u7528 DOM \u76D1\u542C");
6484
6562
  domMonitor = await createDomShareMonitor(page, {
6485
6563
  prefix: share.prefix,
6486
6564
  selectors: domSelectors,
@@ -6495,14 +6573,14 @@ var Share = {
6495
6573
  });
6496
6574
  }
6497
6575
  if (share.mode === "response") {
6498
- logger12.info(`\u5F53\u524D\u4E3A\u63A5\u53E3\u6A21\u5F0F\uFF0C\u6302\u8F7D response \u76D1\u542C: apiMatchers=${toJsonInline(apiMatchers, 160)}`);
6576
+ logger13.info(`\u5F53\u524D\u4E3A\u63A5\u53E3\u6A21\u5F0F\uFF0C\u6302\u8F7D response \u76D1\u542C: apiMatchers=${toJsonInline(apiMatchers, 160)}`);
6499
6577
  page.on("response", onResponse);
6500
6578
  }
6501
6579
  const deadline = Date.now() + timeoutMs;
6502
6580
  const getRemainingMs = () => Math.max(0, deadline - Date.now());
6503
6581
  try {
6504
6582
  const actionTimeout = getRemainingMs();
6505
- logger12.start("captureLink.performActions", `\u6267\u884C\u52A8\u4F5C\u9884\u7B97=${actionTimeout}ms`);
6583
+ logger13.start("captureLink.performActions", `\u6267\u884C\u52A8\u4F5C\u9884\u7B97=${actionTimeout}ms`);
6506
6584
  if (actionTimeout > 0) {
6507
6585
  let timer = null;
6508
6586
  let actionError = null;
@@ -6516,21 +6594,21 @@ var Share = {
6516
6594
  const actionResult = await Promise.race([actionPromise, timeoutPromise]);
6517
6595
  if (timer) clearTimeout(timer);
6518
6596
  if (actionResult === "__ACTION_ERROR__") {
6519
- logger12.fail("captureLink.performActions", actionError);
6597
+ logger13.fail("captureLink.performActions", actionError);
6520
6598
  throw actionError;
6521
6599
  }
6522
6600
  if (actionResult === "__ACTION_TIMEOUT__") {
6523
6601
  stats.actionTimedOut = true;
6524
- logger12.warning(`performActions \u5DF2\u8D85\u65F6 (${actionTimeout}ms)\uFF0C\u52A8\u4F5C\u53EF\u80FD\u4ECD\u5728\u5F02\u6B65\u6267\u884C`);
6602
+ logger13.warning(`performActions \u5DF2\u8D85\u65F6 (${actionTimeout}ms)\uFF0C\u52A8\u4F5C\u53EF\u80FD\u4ECD\u5728\u5F02\u6B65\u6267\u884C`);
6525
6603
  } else {
6526
- logger12.success("captureLink.performActions", "\u6267\u884C\u52A8\u4F5C\u5B8C\u6210");
6604
+ logger13.success("captureLink.performActions", "\u6267\u884C\u52A8\u4F5C\u5B8C\u6210");
6527
6605
  }
6528
6606
  }
6529
6607
  let nextProgressLogTs = Date.now() + 3e3;
6530
6608
  while (true) {
6531
6609
  const selected = share.mode === "dom" ? candidates.dom : candidates.response;
6532
6610
  if (selected?.link) {
6533
- logger12.success("captureLink", `\u6355\u83B7\u6210\u529F: source=${share.mode}, link=${selected.link}`);
6611
+ logger13.success("captureLink", `\u6355\u83B7\u6210\u529F: source=${share.mode}, link=${selected.link}`);
6534
6612
  return {
6535
6613
  link: selected.link,
6536
6614
  payloadText: selected.payloadText,
@@ -6542,7 +6620,7 @@ var Share = {
6542
6620
  if (remaining <= 0) break;
6543
6621
  const now = Date.now();
6544
6622
  if (now >= nextProgressLogTs) {
6545
- logger12.info(
6623
+ logger13.info(
6546
6624
  `captureLink \u7B49\u5F85\u4E2D: remaining=${remaining}ms, domMutationCount=${stats.domMutationCount}, responseMatched=${stats.responseMatched}`
6547
6625
  );
6548
6626
  nextProgressLogTs = now + 5e3;
@@ -6550,11 +6628,11 @@ var Share = {
6550
6628
  await delay2(Math.max(0, Math.min(DEFAULT_POLL_INTERVAL_MS, remaining)));
6551
6629
  }
6552
6630
  if (share.mode === "response" && stats.responseMatched === 0) {
6553
- logger12.warning(
6631
+ logger13.warning(
6554
6632
  `\u63A5\u53E3\u76D1\u542C\u672A\u547D\u4E2D: apiMatchers=${toJsonInline(apiMatchers, 220)}, \u54CD\u5E94\u6837\u672CURLs=${toJsonInline(stats.responseSampleUrls, 420)}`
6555
6633
  );
6556
6634
  }
6557
- logger12.warning(
6635
+ logger13.warning(
6558
6636
  `captureLink \u8D85\u65F6\u672A\u62FF\u5230\u94FE\u63A5: mode=${share.mode}, actionTimedOut=${stats.actionTimedOut}, domMutationCount=${stats.domMutationCount}, responseObserved=${stats.responseObserved}, responseMatched=${stats.responseMatched}, lastMatchedUrl=${stats.lastMatchedUrl || "none"}`
6559
6637
  );
6560
6638
  return {
@@ -6566,7 +6644,7 @@ var Share = {
6566
6644
  } finally {
6567
6645
  if (share.mode === "response") {
6568
6646
  page.off("response", onResponse);
6569
- logger12.info("response \u76D1\u542C\u5DF2\u5378\u8F7D");
6647
+ logger13.info("response \u76D1\u542C\u5DF2\u5378\u8F7D");
6570
6648
  }
6571
6649
  await stopDomMonitor();
6572
6650
  }