customer-chat-sdk 1.0.46 → 1.0.48

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.
@@ -14878,27 +14878,43 @@ class ScreenshotManager {
14878
14878
  console.log(`📸 原始大小: ${Math.round(base64Data.length * 0.75 / 1024)} KB`);
14879
14879
  console.log(`📸 Base64 长度: ${base64Data.length} 字符`);
14880
14880
  }
14881
- // 检测移动设备和低端设备
14882
- const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
14883
- const isLowEndDevice = navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4;
14884
- // 如果启用压缩(仅在非移动设备上启用)
14885
- const shouldCompress = this.options.compress && !isMobile && !isLowEndDevice;
14886
- if (shouldCompress && this.worker) {
14887
- if (!this.options.silentMode) {
14888
- console.log('📸 发送到 WebWorker 进行压缩...');
14881
+ // 如果启用压缩(所有设备都支持)
14882
+ const shouldCompress = this.options.compress;
14883
+ if (shouldCompress) {
14884
+ // 确保 Worker 已创建
14885
+ if (!this.worker) {
14886
+ this.worker = this.createWorker();
14887
+ if (!this.options.silentMode) {
14888
+ if (this.worker) {
14889
+ console.log('📸 Worker 已创建,准备压缩');
14890
+ }
14891
+ else {
14892
+ console.warn('📸 ⚠️ Worker 创建失败,无法使用压缩功能');
14893
+ }
14894
+ }
14895
+ }
14896
+ if (this.worker) {
14897
+ if (!this.options.silentMode) {
14898
+ console.log('📸 发送到 WebWorker 进行压缩...');
14899
+ }
14900
+ this.worker.postMessage({
14901
+ type: 'COMPRESS_IMAGE',
14902
+ data: {
14903
+ dataUrl,
14904
+ maxWidth: this.options.maxWidth,
14905
+ maxHeight: this.options.maxHeight,
14906
+ quality: this.options.quality,
14907
+ outputFormat: this.options.outputFormat,
14908
+ timestamp,
14909
+ count: this.screenshotCount
14910
+ }
14911
+ });
14889
14912
  }
14890
- this.worker.postMessage({
14891
- type: 'COMPRESS_IMAGE',
14892
- data: {
14893
- dataUrl,
14894
- maxWidth: this.options.maxWidth,
14895
- maxHeight: this.options.maxHeight,
14896
- quality: this.options.quality,
14897
- outputFormat: this.options.outputFormat,
14898
- timestamp,
14899
- count: this.screenshotCount
14913
+ else {
14914
+ if (!this.options.silentMode) {
14915
+ console.warn('📸 ⚠️ Worker 不可用,跳过压缩(使用原始截图)');
14900
14916
  }
14901
- });
14917
+ }
14902
14918
  }
14903
14919
  this.error = null;
14904
14920
  return true;
@@ -16693,25 +16709,219 @@ class ScreenshotManager {
16693
16709
  return { width, height };
16694
16710
  }
16695
16711
  /**
16696
- * 创建 WebWorker
16712
+ * 创建 WebWorker(实现类似 TinyPNG 的智能压缩)
16697
16713
  */
16698
16714
  createWorker() {
16699
- if (typeof Worker === 'undefined' || typeof OffscreenCanvas === 'undefined') {
16715
+ if (typeof Worker === 'undefined') {
16700
16716
  return null;
16701
16717
  }
16702
16718
  try {
16703
- // 简化的 Worker 代码(实际使用时需要完整实现)
16719
+ // 完整的 Worker 压缩代码(类似 TinyPNG 的智能压缩)
16704
16720
  const workerCode = `
16705
- self.onmessage = function(e) {
16721
+ // 图片压缩 Worker(类似 TinyPNG 的智能压缩)
16722
+ self.onmessage = async function(e) {
16706
16723
  const { type, data } = e.data;
16724
+
16707
16725
  if (type === 'COMPRESS_IMAGE') {
16708
- // 压缩逻辑(简化版)
16709
- self.postMessage({
16710
- type: 'SCREENSHOT_RESULT',
16711
- data: { compressed: { dataUrl: data.dataUrl } }
16712
- });
16726
+ try {
16727
+ const { dataUrl, maxWidth, maxHeight, quality, outputFormat } = data;
16728
+
16729
+ // 1. 加载图片
16730
+ const img = await loadImage(dataUrl);
16731
+
16732
+ // 获取图片尺寸(ImageBitmap 或 Image 都支持)
16733
+ const imgWidth = img.width || img.naturalWidth || 0;
16734
+ const imgHeight = img.height || img.naturalHeight || 0;
16735
+
16736
+ if (imgWidth === 0 || imgHeight === 0) {
16737
+ throw new Error('无法获取图片尺寸');
16738
+ }
16739
+
16740
+ // 2. 计算压缩后的尺寸(保持宽高比)
16741
+ const { width, height } = calculateSize(
16742
+ imgWidth,
16743
+ imgHeight,
16744
+ maxWidth || 1600,
16745
+ maxHeight || 900
16746
+ );
16747
+
16748
+ // 3. 创建 OffscreenCanvas(Worker 中必须使用 OffscreenCanvas)
16749
+ if (typeof OffscreenCanvas === 'undefined') {
16750
+ throw new Error('浏览器不支持 OffscreenCanvas,无法在 Worker 中压缩');
16751
+ }
16752
+
16753
+ const canvas = new OffscreenCanvas(width, height);
16754
+ const ctx = canvas.getContext('2d');
16755
+
16756
+ if (!ctx) {
16757
+ throw new Error('无法获取 Canvas 上下文');
16758
+ }
16759
+
16760
+ // 4. 优化绘制设置(提升压缩质量)
16761
+ ctx.imageSmoothingEnabled = true;
16762
+ ctx.imageSmoothingQuality = 'high';
16763
+
16764
+ // 5. 使用白色背景(避免透明区域压缩问题)
16765
+ ctx.fillStyle = '#ffffff';
16766
+ ctx.fillRect(0, 0, width, height);
16767
+
16768
+ // 6. 绘制图片(高质量缩放)
16769
+ ctx.drawImage(img, 0, 0, width, height);
16770
+
16771
+ // 7. 转换为目标格式(智能质量调整)
16772
+ // OffscreenCanvas 使用 convertToBlob 而不是 toDataURL
16773
+ let compressedDataUrl;
16774
+ const finalQuality = Math.max(0.1, Math.min(0.95, quality || 0.15));
16775
+
16776
+ // 辅助函数:将 Blob 转换为 data URL
16777
+ async function blobToDataURL(blob) {
16778
+ return new Promise((resolve, reject) => {
16779
+ const reader = new FileReader();
16780
+ reader.onload = () => resolve(reader.result);
16781
+ reader.onerror = reject;
16782
+ reader.readAsDataURL(blob);
16783
+ });
16784
+ }
16785
+
16786
+ // 确定 MIME 类型
16787
+ let mimeType = 'image/png';
16788
+ if (outputFormat === 'webp') {
16789
+ mimeType = 'image/webp';
16790
+ } else if (outputFormat === 'jpeg') {
16791
+ mimeType = 'image/jpeg';
16792
+ }
16793
+
16794
+ // 第一次压缩
16795
+ let blob = await canvas.convertToBlob({
16796
+ type: mimeType,
16797
+ quality: finalQuality
16798
+ });
16799
+
16800
+ compressedDataUrl = await blobToDataURL(blob);
16801
+
16802
+ // 8. 如果压缩后文件仍然较大,尝试进一步降低质量
16803
+ const originalSize = dataUrl.length;
16804
+ let compressedSize = compressedDataUrl.length;
16805
+
16806
+ // 如果压缩后大小减少不足 20%,尝试更激进的压缩
16807
+ if (compressedSize > originalSize * 0.8 && finalQuality > 0.1 && (outputFormat === 'webp' || outputFormat === 'jpeg')) {
16808
+ const aggressiveQuality = Math.max(0.1, finalQuality * 0.7);
16809
+
16810
+ try {
16811
+ const moreCompressedBlob = await canvas.convertToBlob({
16812
+ type: mimeType,
16813
+ quality: aggressiveQuality
16814
+ });
16815
+
16816
+ const moreCompressedDataUrl = await blobToDataURL(moreCompressedBlob);
16817
+
16818
+ // 如果更激进的压缩效果更好,使用它
16819
+ if (moreCompressedDataUrl.length < compressedDataUrl.length) {
16820
+ compressedDataUrl = moreCompressedDataUrl;
16821
+ compressedSize = compressedDataUrl.length;
16822
+ }
16823
+ } catch (e) {
16824
+ // 忽略错误,使用之前的压缩结果
16825
+ }
16826
+ }
16827
+
16828
+ // 9. 返回压缩结果
16829
+ self.postMessage({
16830
+ type: 'SCREENSHOT_RESULT',
16831
+ data: {
16832
+ compressed: {
16833
+ dataUrl: compressedDataUrl,
16834
+ originalSize: originalSize,
16835
+ compressedSize: compressedDataUrl.length,
16836
+ compressionRatio: ((1 - compressedDataUrl.length / originalSize) * 100).toFixed(1)
16837
+ }
16838
+ }
16839
+ });
16840
+ } catch (error) {
16841
+ // 压缩失败,返回原始数据
16842
+ self.postMessage({
16843
+ type: 'SCREENSHOT_RESULT',
16844
+ data: {
16845
+ compressed: {
16846
+ dataUrl: data.dataUrl,
16847
+ error: error.message
16848
+ }
16849
+ }
16850
+ });
16851
+ }
16713
16852
  }
16714
16853
  };
16854
+
16855
+ // 加载图片的辅助函数(Worker 中使用 createImageBitmap)
16856
+ async function loadImage(dataUrl) {
16857
+ try {
16858
+ // 将 data URL 转换为 Blob
16859
+ let blob;
16860
+ if (typeof fetch !== 'undefined') {
16861
+ try {
16862
+ const response = await fetch(dataUrl);
16863
+ blob = await response.blob();
16864
+ } catch (e) {
16865
+ // fetch 失败,手动转换 data URL 到 Blob
16866
+ blob = dataURLToBlob(dataUrl);
16867
+ }
16868
+ } else {
16869
+ // 没有 fetch,手动转换
16870
+ blob = dataURLToBlob(dataUrl);
16871
+ }
16872
+
16873
+ // 使用 createImageBitmap 创建图片(Worker 中推荐方式)
16874
+ if (typeof createImageBitmap !== 'undefined') {
16875
+ return await createImageBitmap(blob);
16876
+ } else {
16877
+ // 回退方案:使用 Image(某些 Worker 环境可能支持)
16878
+ return new Promise((resolve, reject) => {
16879
+ const img = new Image();
16880
+ img.onload = () => resolve(img);
16881
+ img.onerror = reject;
16882
+ img.src = dataUrl;
16883
+ });
16884
+ }
16885
+ } catch (error) {
16886
+ // 如果 createImageBitmap 失败,尝试直接使用 Image
16887
+ return new Promise((resolve, reject) => {
16888
+ const img = new Image();
16889
+ img.onload = () => resolve(img);
16890
+ img.onerror = () => reject(error);
16891
+ img.src = dataUrl;
16892
+ });
16893
+ }
16894
+ }
16895
+
16896
+ // 将 data URL 转换为 Blob 的辅助函数
16897
+ function dataURLToBlob(dataUrl) {
16898
+ const arr = dataUrl.split(',');
16899
+ const mimeMatch = arr[0].match(/:(.*?);/);
16900
+ const mime = mimeMatch ? mimeMatch[1] : 'image/png';
16901
+ const bstr = atob(arr[1]);
16902
+ let n = bstr.length;
16903
+ const u8arr = new Uint8Array(n);
16904
+ while (n--) {
16905
+ u8arr[n] = bstr.charCodeAt(n);
16906
+ }
16907
+ return new Blob([u8arr], { type: mime });
16908
+ }
16909
+
16910
+ // 计算压缩后尺寸的辅助函数(保持宽高比)
16911
+ function calculateSize(originalWidth, originalHeight, maxWidth, maxHeight) {
16912
+ let width = originalWidth;
16913
+ let height = originalHeight;
16914
+
16915
+ if (width > maxWidth || height > maxHeight) {
16916
+ const widthRatio = maxWidth / width;
16917
+ const heightRatio = maxHeight / height;
16918
+ const ratio = Math.min(widthRatio, heightRatio);
16919
+ width = Math.round(width * ratio);
16920
+ height = Math.round(height * ratio);
16921
+ }
16922
+
16923
+ return { width, height };
16924
+ }
16715
16925
  `;
16716
16926
  const blob = new Blob([workerCode], { type: 'application/javascript' });
16717
16927
  const workerUrl = URL.createObjectURL(blob);
@@ -16719,17 +16929,34 @@ class ScreenshotManager {
16719
16929
  newWorker.onmessage = (e) => {
16720
16930
  const { type, data } = e.data;
16721
16931
  if (type === 'SCREENSHOT_RESULT' && data?.compressed) {
16932
+ const compressed = data.compressed;
16933
+ // 更新截图历史记录
16722
16934
  if (this.screenshotHistory.length > 0) {
16723
- this.screenshotHistory[this.screenshotHistory.length - 1] = data.compressed.dataUrl;
16935
+ this.screenshotHistory[this.screenshotHistory.length - 1] = compressed.dataUrl;
16936
+ // 打印压缩统计信息
16937
+ if (!this.options.silentMode && compressed.originalSize && compressed.compressedSize) {
16938
+ const originalKB = (compressed.originalSize * 0.75 / 1024).toFixed(2);
16939
+ const compressedKB = (compressed.compressedSize * 0.75 / 1024).toFixed(2);
16940
+ const ratio = compressed.compressionRatio || '0';
16941
+ console.log('📸 [Worker 压缩] ✅ 压缩完成');
16942
+ console.log(` 原始大小: ${originalKB} KB`);
16943
+ console.log(` 压缩后: ${compressedKB} KB`);
16944
+ console.log(` 压缩率: ${ratio}%`);
16945
+ if (compressed.error) {
16946
+ console.warn(` ⚠️ 压缩警告: ${compressed.error}`);
16947
+ }
16948
+ }
16724
16949
  }
16725
16950
  }
16726
16951
  };
16727
16952
  newWorker.onerror = (e) => {
16728
16953
  console.error('📸 WebWorker 错误:', e);
16954
+ if (!this.options.silentMode) {
16955
+ console.warn('📸 Worker 压缩失败,使用原始截图');
16956
+ }
16729
16957
  };
16730
16958
  // 注意:不要立即 revokeObjectURL,因为 Worker 需要这个 URL 保持有效
16731
16959
  // 在 destroy() 方法中清理 Worker 时再 revoke
16732
- // URL.revokeObjectURL(workerUrl) // 已移除,在 destroy 时清理
16733
16960
  return newWorker;
16734
16961
  }
16735
16962
  catch (err) {
@@ -16807,7 +17034,7 @@ class ScreenshotManager {
16807
17034
  const encoder = new TextEncoder();
16808
17035
  let offset = 0;
16809
17036
  // sign: 8字节 (BigInt64)
16810
- view.setBigInt64(offset, BigInt(config.sign), true); // little-endian
17037
+ view.setBigInt64(offset, BigInt(config.sign));
16811
17038
  offset += 8;
16812
17039
  // type: 1字节 (Uint8)
16813
17040
  view.setUint8(offset, config.type);