k2-im 0.2.11 → 0.2.12

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.
@@ -1943,7 +1943,7 @@ interface ImHttpPort {
1943
1943
  }
1944
1944
 
1945
1945
  /** 可持久化的媒体资产类型;未注册类型必须跳过缓存,不能回退到其它类型。 */
1946
- type MediaAssetKind = 'image' | 'video';
1946
+ type MediaAssetKind = 'image' | 'video' | 'file';
1947
1947
  /** 持久媒体资产的稳定键。resourceVersion 由远端资源标识派生,避免同消息替换资源后误命中旧缓存。 */
1948
1948
  interface MediaAssetCacheKey {
1949
1949
  kind: MediaAssetKind;
@@ -5474,7 +5474,7 @@ interface ImMediaTasksApi {
5474
5474
  clearCache: () => Promise<void>;
5475
5475
  /**
5476
5476
  * 按输入顺序查询完整本机媒体是否可用;不下载、不读取 Blob、不续缓存期限或创建任务。
5477
- * 仅支持图片/视频(含媒体合集);未配置持久缓存时只检查内存。
5477
+ * 支持图片、视频和文件(含各自合集);未配置持久缓存时只检查内存。
5478
5478
  * @throws 不支持轻量查询或存储读取失败时明确拒绝,不伪装成未命中。
5479
5479
  * @example const [available] = await client.media.probeCached([messageRef])
5480
5480
  */
@@ -1940,7 +1940,7 @@ interface ImHttpPort {
1940
1940
  }
1941
1941
 
1942
1942
  /** 可持久化的媒体资产类型;未注册类型必须跳过缓存,不能回退到其它类型。 */
1943
- type MediaAssetKind = 'image' | 'video';
1943
+ type MediaAssetKind = 'image' | 'video' | 'file';
1944
1944
  /** 持久媒体资产的稳定键。resourceVersion 由远端资源标识派生,避免同消息替换资源后误命中旧缓存。 */
1945
1945
  interface MediaAssetCacheKey {
1946
1946
  kind: MediaAssetKind;
@@ -5585,7 +5585,7 @@ interface ImMediaTasksApi {
5585
5585
  clearCache: () => Promise<void>;
5586
5586
  /**
5587
5587
  * 按输入顺序查询完整本机媒体是否可用;不下载、不读取 Blob、不续缓存期限或创建任务。
5588
- * 仅支持图片/视频(含媒体合集);未配置持久缓存时只检查内存。
5588
+ * 支持图片、视频和文件(含各自合集);未配置持久缓存时只检查内存。
5589
5589
  * @throws 不支持轻量查询或存储读取失败时明确拒绝,不伪装成未命中。
5590
5590
  * @example const [available] = await client.media.probeCached([messageRef])
5591
5591
  */
package/dist/index.d.ts CHANGED
@@ -1981,7 +1981,7 @@ interface ImHttpPort {
1981
1981
  }
1982
1982
 
1983
1983
  /** 可持久化的媒体资产类型;未注册类型必须跳过缓存,不能回退到其它类型。 */
1984
- type MediaAssetKind = 'image' | 'video';
1984
+ type MediaAssetKind = 'image' | 'video' | 'file';
1985
1985
  /** 持久媒体资产的稳定键。resourceVersion 由远端资源标识派生,避免同消息替换资源后误命中旧缓存。 */
1986
1986
  interface MediaAssetCacheKey {
1987
1987
  kind: MediaAssetKind;
@@ -6157,7 +6157,7 @@ interface ImMediaTasksApi {
6157
6157
  clearCache: () => Promise<void>;
6158
6158
  /**
6159
6159
  * 按输入顺序查询完整本机媒体是否可用;不下载、不读取 Blob、不续缓存期限或创建任务。
6160
- * 仅支持图片/视频(含媒体合集);未配置持久缓存时只检查内存。
6160
+ * 支持图片、视频和文件(含各自合集);未配置持久缓存时只检查内存。
6161
6161
  * @throws 不支持轻量查询或存储读取失败时明确拒绝,不伪装成未命中。
6162
6162
  * @example const [available] = await client.media.probeCached([messageRef])
6163
6163
  */
@@ -1 +1 @@
1
- import{createImSdkError as e}from"./message.js";import{createMediaAssetCacheStrategyRegistry as t,mediaAssetResourceVersion as o}from"../../../im-core/src/ports/media-asset-cache-port.js";import{throwIfAborted as r}from"../../../im-core/src/abort.js";import{resolveMediaThumbnailMimeType as a}from"../../../im-core/src/media-thumbnail.js";import{isCryptoExecutionError as i}from"../../../im-core/src/ports/crypto-task-executor.js";const n=6048e5,s=1048576;function d(e){let t=0,o=!1;const r=[];function a(){if(!o)for(;t<e&&r.length>0;){r.sort((e,t)=>t.getPriority()-e.getPriority());const e=r.shift();if(e.signal.removeEventListener("abort",e.onAbort),e.signal.aborted){e.reject(new DOMException("媒体下载已取消","AbortError"));continue}t+=1;let o=!1;e.resolve(()=>{o||(o=!0,t=Math.max(0,t-1),a())})}}return{acquire:(e,t)=>o?Promise.reject(new Error("媒体下载并发控制器已释放")):new Promise((o,i)=>{const n={resolve:o,reject:i,signal:e,getPriority:t,onAbort:()=>{const e=r.indexOf(n);e>=0&&r.splice(e,1),i(new DOMException("媒体下载已取消","AbortError"))}};e.addEventListener("abort",n.onAbort,{once:!0}),r.push(n),a()}),dispose(){o=!0;for(const e of r.splice(0))e.signal.removeEventListener("abort",e.onAbort),e.reject(new Error("媒体下载并发控制器已释放"))}}}function c(){return t([{kind:"image",softMaxBytes:512*s,maxEntries:512,maxEntryBytes:30*s,maxIdleMs:n},{kind:"video",softMaxBytes:1792*s,maxEntries:64,maxEntryBytes:200*s,maxIdleMs:n}])}function l(e){return Number.isFinite(e)?Math.max(0,Math.min(100,Math.round(e))):0}function m(e){return Object.freeze({conversationType:e.conversationType,conversationId:e.conversationId})}function p(e,t,o,r){const a=`${e}:${encodeURIComponent(t.conversationType)}:${encodeURIComponent(t.conversationId)}:${encodeURIComponent(o)}`;return void 0===r?a:`${a}:${r}`}function u(e){const t=e.ref.conversationType,o=e.ref.conversationId;if("direct"!==t&&"group"!==t&&"channel"!==t||""===o.trim())throw y({code:"supergroup"===t?"IM_SDK_SUPERGROUP_UNSUPPORTED":"IM_SDK_MEDIA_TASK_REF_INVALID",category:"supergroup"===t?"unsupported":"contract",operation:"media.tasks.project",retryable:!1});const r=m({conversationType:t,conversationId:o});return g({id:p(e.direction,r,e.messageId),messageId:e.messageId,ref:r,direction:e.direction,state:e.state,percent:l(e.percent),...void 0===e.items?{}:{items:e.items},...void 0===e.attempt?{}:{attempt:e.attempt},...void 0===e.maxAttempts?{}:{maxAttempts:e.maxAttempts},...void 0===e.bytesTransferred?{}:{bytesTransferred:e.bytesTransferred},...void 0===e.bytesTotal?{}:{bytesTotal:e.bytesTotal},...void 0===e.recovery?{}:{recovery:e.recovery},...void 0===e.recoveryReason?{}:{recoveryReason:e.recoveryReason},...void 0===e.phase?{}:{phase:e.phase},...void 0===e.failure?{}:{error:I(e.failure,r)}})}function y(t){const o=e(t);return Object.assign(new Error(o.code),o,{name:"ImMediaTaskOperationError"})}function f(e){return!(void 0!==e.recalled||void 0!==e.deletedForEveryone||"failed"!==e.status&&"uploading"!==e.status||"media.cancelled"===e.failure?.displayCode&&!0!==e.failure.retryable||"media.uploadTimeout"===e.failure?.displayCode&&!1===e.failure.retryable)}function I(t,o){if(void 0===t)return;const r=t.displayCode,a=void 0===r?void 0:{"media.empty":{code:"IM_SDK_MEDIA_EMPTY",category:"validation",retryable:!1},"media.noCrypto":{code:"IM_SDK_MEDIA_CRYPTO_UNAVAILABLE",category:"contract",retryable:!1},"media.previewFailed":{code:"IM_SDK_MEDIA_PREVIEW_FAILED",category:"state",retryable:!1},"media.encryptFailed":{code:"IM_SDK_MEDIA_ENCRYPT_FAILED",category:"state",retryable:!1},"media.uploadFailed":{code:"IM_SDK_MEDIA_UPLOAD_FAILED",category:"network",retryable:!0},"media.uploadTimeout":{code:"IM_SDK_MEDIA_UPLOAD_TIMEOUT",category:"network",retryable:!0},"media.resumeUnavailable":{code:"IM_SDK_MEDIA_UPLOAD_RESTART_REQUIRED",category:"state",retryable:!0},"media.cleanupUnconfirmed":{code:"IM_SDK_MEDIA_UPLOAD_CLEANUP_UNCONFIRMED",category:"state",retryable:!0},"media.cancelled":{code:"IM_SDK_MEDIA_UPLOAD_CANCELED",category:"state",retryable:!0},"media.invalidDuration":{code:"IM_SDK_VOICE_DURATION_INVALID",category:"validation",retryable:!1},"media.uploadInterrupted":{code:"IM_SDK_MEDIA_UPLOAD_INTERRUPTED",category:"network",retryable:!0}}[r];return Object.freeze(e({...a??{code:"IM_SDK_MEDIA_UPLOAD_FAILED",category:"state",retryable:t.retryable??!1},...!1===t.retryable?{retryable:!1}:{},operation:"media.upload",conversation:o}))}function g(e){return Object.freeze({...e,ref:m(e.ref),...void 0===e.items?{}:{items:Object.freeze(e.items.map(e=>Object.freeze({...e})))},...void 0===e.error?{}:{error:Object.freeze({...e.error})}})}function v(e){const t=e?.conversation,o=t?.conversationType,r=t?.conversationId;if("supergroup"===o)throw y({code:"IM_SDK_SUPERGROUP_UNSUPPORTED",category:"unsupported",operation:"media.download",retryable:!1});if("direct"!==o&&"group"!==o&&"channel"!==o||"string"!=typeof r||""===r.trim()||"string"!=typeof e?.messageId||""===e.messageId.trim())throw y({code:"IM_SDK_MEDIA_MESSAGE_REF_INVALID",category:"validation",operation:"media.download",retryable:!1});return m({conversationType:o,conversationId:r})}function _(e){let t=!0;const s=e.now??Date.now;let c=0,I=0;const _=/* @__PURE__ */new Map,E=/* @__PURE__ */new Set,h=/* @__PURE__ */new Map,D=/* @__PURE__ */new Map,A=/* @__PURE__ */new Map,b=/* @__PURE__ */new Map,M=/* @__PURE__ */new Map,w=/* @__PURE__ */new Set;let T=!1;const L=/* @__PURE__ */new Map,S=/* @__PURE__ */new Set,C=e.maxDownloadCheckpointBytes??536870912;function K(e){return y({code:"IM_SDK_MEDIA_DOWNLOAD_RESTART_REQUIRED",category:"state",operation:"media.download",retryable:!0,conversation:e})}function O(e,t){L.delete(e),S.add(e);const o=_.get(e);if(void 0!==o){const e={...o,recoveryReason:t,..."failed"===o.state||"canceled"===o.state?{error:K(o.ref)}:{}};"running"===o.state?$(e):q(e)}}const R=d(3);let U;const P=e.maxCachedBlobs??8,N=e.maxCachedBlobBytes??67108864;let k=0;function V(){if(!t||!e.isActive())throw y({code:"IM_SDK_MEDIA_RUNTIME_INACTIVE",category:"state",operation:"media.tasks",retryable:!1})}function x(){return Object.freeze([..._.values()])}function F(){const t=x();for(const o of[...E])try{o(t)}catch(t){e.emitter.emit({type:"error",error:{scope:"unknown",message:"媒体任务订阅者回调异常",cause:t}})}}function z(){!T&&t&&e.isActive()&&(T=!0,queueMicrotask(()=>{if(T=!1,t&&e.isActive())for(const t of[...w])try{t()}catch(t){e.emitter.emit({type:"error",error:{scope:"unknown",message:"媒体缓存订阅者回调异常",cause:t}})}}))}function j(e){const t=A.get(e);void 0!==t&&(k-=t.size,A.delete(e),b.delete(e),M.delete(e),z())}function B(){if(!t||!e.isActive())return;const o=s();for(const[e,t]of L)!D.has(e)&&void 0!==t.idleSince&&o-t.idleSince>=864e5&&O(e,"download-checkpoint-expired");for(const[e,t]of b)!D.has(e)&&o-t>=n&&j(e);z()}function W(e,t){const o=A.get(e);if(void 0!==o){if(!(M.get(e)!==t||s()-b.get(e)>=n))return A.delete(e),A.set(e,o),b.set(e,s()),o;j(e)}}function Y(){c+=1,A.clear(),b.clear(),M.clear(),z(),k=0;for(const e of[...L.keys()])O(e,"download-checkpoint-cleared")}function H(e){_.delete(e),h.delete(e),L.delete(e),S.delete(e),j(e)}function $(e){_.set(e.id,g(e)),function(){for(;_.size>128;){const e=[..._.values()].find(e=>"completed"===e.state||"failed"===e.state||"canceled"===e.state);if(void 0===e)return;H(e.id)}}()}function q(o){if(!t||!e.isActive())return;$(o);const r=_.get(o.id);if(F(),!t||!e.isActive()||void 0===r||_.get(o.id)!==r)return;const a={id:r.id,messageId:r.messageId,ref:r.ref,direction:"download",state:r.state,percent:r.percent};e.emitter.emit({type:"media-task:updated",conversation:r.ref,task:a})}function J(e,t,o){if(j(e),!(t.size>N))for(A.set(e,t),M.set(e,o),z(),b.set(e,s()),k+=t.size;A.size>P||k>N;){const e=A.keys().next().value;if(void 0===e)break;j(e)}}function G(t,r=!0){const a=v(t),i=e.domainState.getConversationMessage(a,t.messageId);if(void 0===i)throw y({code:"IM_SDK_MEDIA_MESSAGE_NOT_FOUND",category:"state",operation:"media.download",retryable:!1,conversation:a});let n,s,d,c;if("image"===i.contentType)n=i.body.image,s=e.loaders?.loadImage,c="image";else if("video"===i.contentType)n=i.body.video,s=e.loaders?.loadVideo,c="video";else if("voice"===i.contentType)n=i.body.voice,s=e.loaders?.loadVoice;else if("file"===i.contentType)n=i.body.file,s=e.loaders?.loadFile,d=i.body.file?.mimeType;else if("filesAlbum"===i.contentType){const o=t.itemIndex;if(n=void 0===o?void 0:i.body.filesAlbum?.items[o],void 0===n)throw y({code:"IM_SDK_MEDIA_ALBUM_ITEM_INVALID",category:"validation",operation:"media.download",retryable:!1,conversation:a});s=e.loaders?.loadFile}else if("mediaAlbum"===i.contentType){const o=i.body.mediaAlbum?.items,r=t.itemIndex,d=void 0===r||void 0===o?void 0:o[r];if(void 0===d)throw y({code:"IM_SDK_MEDIA_ALBUM_ITEM_INVALID",category:"validation",operation:"media.download",retryable:!1,conversation:a});n=d,s="video"===d.kind?e.loaders?.loadVideo:e.loaders?.loadImage,c=d.kind}if("mediaAlbum"!==i.contentType&&"filesAlbum"!==i.contentType&&void 0!==t.itemIndex)throw y({code:"IM_SDK_MEDIA_ALBUM_ITEM_INVALID",category:"validation",operation:"media.download",retryable:!1,conversation:a});if(void 0===n)throw y({code:"IM_SDK_MEDIA_MESSAGE_UNSUPPORTED",category:"unsupported",operation:"media.download",retryable:!1,conversation:a});if(r&&void 0===s)throw y({code:"IM_SDK_MEDIA_DOWNLOAD_UNAVAILABLE",category:"contract",operation:"media.download",retryable:!1,conversation:a});if(""===n.url.trim()||n.url.startsWith("blob:"))throw y({code:"IM_SDK_MEDIA_REMOTE_URL_UNAVAILABLE",category:"state",operation:"media.download",retryable:!1,conversation:a});return{ref:a,messageId:i.id,...void 0===t.itemIndex?{}:{itemIndex:t.itemIndex},...void 0===d?{}:{mimeType:d},...void 0===c?{}:{cacheKind:c,resourceVersion:o(n.url,{conversation:a,itemIndex:t.itemIndex})},...void 0===s?{}:{load:s},input:{url:n.url,...void 0===n.size?{}:{expectedBytes:n.size},...void 0===n.teaKey?{}:{teaKey:n.teaKey},...void 0===n.fileEncryptType?{}:{fileEncryptType:n.fileEncryptType}}}}function Q(e){return y({code:"IM_SDK_MEDIA_DOWNLOAD_CANCELED",category:"state",operation:"media.download",retryable:!0,conversation:e})}function X(){return y({code:"IM_SDK_MEDIA_RUNTIME_INACTIVE",category:"state",operation:"media.download",retryable:!1})}async function Z(t,o,r=c){if(V(),r!==c)return null;const a=p("download",t.ref,t.messageId,t.itemIndex),i=W(a,t.resourceVersion);if(void 0!==i)return i;if(void 0===e.assetCache||void 0===t.cacheKind||void 0===t.resourceVersion)return null;let n;try{n=await e.assetCache.get({kind:t.cacheKind,messageId:t.messageId,resourceVersion:t.resourceVersion}),e.onAssetCacheEvent?.({operation:"get",outcome:null===n?"miss":"hit",kind:t.cacheKind,messageId:t.messageId,...null===n?{}:{byteLength:n.blob.size}})}catch(r){if(e.onAssetCacheEvent?.({operation:"get",outcome:"failed",kind:t.cacheKind,messageId:t.messageId,cause:r}),o)throw y({code:"IM_SDK_MEDIA_CACHE_READ_FAILED",category:"state",operation:"media.getCached",retryable:!0,conversation:t.ref});return null}if(null===n)return null;if(V(),r!==c)return null;const s=n.blob,d=n.mimeType??t.mimeType??"",l=s.type===d?s:s.slice(0,s.size,d);return J(a,l,t.resourceVersion),l}function ee(e,t){B();const o=L.get(e);if(void 0!==o&&o.url!==t.input.url&&O(e,"download-object-changed"),S.has(e)){const o=K(t.ref),r=_.get(e);throw void 0===r||"failed"!==r.state&&"canceled"!==r.state||q({...r,error:o}),o}return o?.state}function te(o,r=!1){const a=c,n=p("download",o.ref,o.messageId,o.itemIndex),d=D.get(n);if(void 0!==d&&!d.controller.signal.aborted)return d.promise;if(!r){const e=W(n,o.resourceVersion);if(void 0!==e)return q({id:n,ref:m(o.ref),messageId:o.messageId,...void 0===o.itemIndex?{}:{itemIndex:o.itemIndex},direction:"download",state:"completed",percent:100}),Promise.resolve(e)}j(n);const u=(()=>{const e=ee(n,o);return void 0===e?{percent:0}:{percent:Math.min(99,Math.round(e.bytesDownloaded/e.bytesTotal*100)),bytesTransferred:e.bytesDownloaded,bytesTotal:e.bytesTotal}})(),f=m(o.ref);h.set(n,Object.freeze({conversation:f,messageId:o.messageId,...void 0===o.itemIndex?{}:{itemIndex:o.itemIndex}}));const I={id:n,messageId:o.messageId,ref:f,direction:"download",...void 0===o.itemIndex?{}:{itemIndex:o.itemIndex}},g=new AbortController,v=Promise.resolve().then(async()=>{let d;try{if(!t||!e.isActive())throw X();if(g.signal.aborted)throw Q(f);if(d=await R.acquire(g.signal,()=>U===n?1:0),!t||!e.isActive())throw X();if(g.signal.aborted)throw Q(f);if(q({...I,...u,state:"running"}),!t||!e.isActive())throw X();if(g.signal.aborted)throw Q(f);if(!r&&void 0!==e.assetCache&&void 0!==o.cacheKind&&void 0!==o.resourceVersion){const e=await Z(o,!1,a);if(null!==e){if(g.signal.aborted)throw Q(f);return L.delete(n),S.delete(n),q({..._.get(n),...I,state:"completed",percent:100,error:void 0,recoveryReason:void 0}),e}}const i=o.load;if(void 0===i)throw y({code:"IM_SDK_MEDIA_DOWNLOAD_UNAVAILABLE",category:"contract",operation:"media.download",retryable:!1,conversation:f});const s=ee(n,o);if(void 0!==u.bytesTransferred&&(void 0===s||a!==c))throw O(n,"download-checkpoint-cleared"),K(f);const m=await i({...o.input,getPriority:()=>U===n?1:0,...void 0===s?{}:{resume:s},onResumable:r=>{t&&e.isActive()&&a===c&&D.get(n)?.controller===g&&function(e,t,o){L.delete(e),L.set(e,{url:t,state:o}),S.delete(e);let r=[...L.values()].reduce((e,t)=>e+t.state.bytesDownloaded,0);for(;L.size>8||r>C;){const e=L.entries().next().value;if(void 0===e)break;r-=e[1].state.bytesDownloaded,O(e[0],"download-checkpoint-limit")}}(n,o.input.url,r)},onResumeInvalidated:()=>{t&&e.isActive()&&a===c&&D.get(n)?.controller===g&&O(n,"download-checkpoint-invalid")},signal:g.signal,onTransferProgress:o=>{const r=_.get(n);t&&e.isActive()&&!g.signal.aborted&&D.get(n)?.controller===g&&"running"===r?.state&&q({...r,state:"running",percent:Math.min(99,l(o.percent)),bytesTransferred:o.bytesTransferred,bytesTotal:o.bytesTotal,phase:o.bytesTotal>0&&o.bytesTransferred>=o.bytesTotal?"finalizing":"transferring"})},onProgress:o=>{const r=_.get(n);if(!t||!e.isActive()||g.signal.aborted||D.get(n)?.controller!==g||"running"!==r?.state)return;const a=Math.min(99,l(o));a<=r.percent||q({...r,state:"running",percent:a})}});if(!t||!e.isActive())throw X();if(g.signal.aborted)throw Q(f);const p=m instanceof Blob?void 0:m;let v=void 0===p?m:new Blob([p],void 0===o.mimeType?void 0:{type:o.mimeType});if(void 0!==o.mimeType&&v.type!==o.mimeType&&(v=v.slice(0,v.size,o.mimeType)),a===c&&J(n,v,o.resourceVersion),a===c&&void 0!==e.assetCache&&void 0!==o.cacheKind&&void 0!==o.resourceVersion){const t=v.size;e.assetCache.put({kind:o.cacheKind,messageId:o.messageId,resourceVersion:o.resourceVersion,blob:v,...void 0===o.mimeType?{}:{mimeType:o.mimeType}}).then(r=>{z(),e.onAssetCacheEvent?.({operation:"put",outcome:r,kind:o.cacheKind,messageId:o.messageId,byteLength:t})}).catch(r=>{e.onAssetCacheEvent?.({operation:"put",outcome:"failed",kind:o.cacheKind,messageId:o.messageId,byteLength:t,cause:r})})}if(L.delete(n),S.delete(n),q({..._.get(n),...I,state:"completed",percent:100,error:void 0,recoveryReason:void 0}),!t||!e.isActive())throw X();return v}catch(o){if(!t||!e.isActive())throw X();if(g.signal.aborted||"object"==typeof o&&null!==o&&"code"in o&&"IM_SDK_MEDIA_DOWNLOAD_CANCELED"===o.code){const e=Q(f);throw D.get(n)?.controller===g&&"canceled"!==_.get(n)?.state&&q({..._.get(n),...I,state:"canceled",percent:_.get(n)?.percent??0,error:S.has(n)?K(f):e}),e}const r=S.has(n)?K(f):i(o)?y({code:"IM_SDK_CRYPTO_EXECUTION_FAILED",category:"state",operation:"crypto.execute",retryable:"queue-full"===o.reason,conversation:f,details:{reason:o.reason}}):o instanceof Error&&"ImMediaTaskOperationError"===o.name?o:y({code:"IM_SDK_MEDIA_DOWNLOAD_FAILED",category:"network",operation:"media.download",retryable:!0,conversation:f});throw D.get(n)?.controller===g&&q({..._.get(n),...I,state:"failed",percent:_.get(n)?.percent??0,error:r}),r}finally{if(d?.(),D.get(n)?.controller===g){D.delete(n);const e=L.get(n);void 0!==e&&(e.idleSince=s())}}});return D.set(n,{controller:g,promise:v}),q({...I,...u,state:"queued"}),v}function oe(e,t){V();const o=_.get(e);if(void 0===o)throw y({code:"IM_SDK_MEDIA_TASK_NOT_FOUND",category:"state",operation:t,retryable:!1});return o}function re(e,t){return y({code:"IM_SDK_MEDIA_TASK_INVALID_STATE",category:"state",operation:t,retryable:!1,conversation:e.ref,details:Object.freeze({state:e.state,direction:e.direction})})}const ae=e.emitter.subscribe(e=>{var o,r;t&&"media-task:updated"===e.type&&"upload"===e.task.direction&&(o=e.conversation,r=e.task.ref,o.conversationType===r.conversationType&&o.conversationId===r.conversationId&&($(u(e.task)),F()))});return{api:{async clearCache(){V(),e.connection.invalidateMediaAssetCacheWrites?.(),Y();try{await(e.assetCache?.clear())}catch(t){throw V(),e.emitter.emit({type:"error",error:{scope:"storage",message:"媒体缓存清理失败",cause:t}}),y({code:"IM_SDK_MEDIA_CACHE_CLEAR_FAILED",category:"state",operation:"media.clearCache",retryable:!0})}V(),z()},getSnapshot:()=>(V(),x()),subscribe:e=>(V(),E.add(e),()=>E.delete(e)),async cancel(t,o){const r=oe(t,"media.cancel");if("queued"!==r.state&&"running"!==r.state&&("upload"!==r.direction||"paused"!==r.state))throw re(r,"media.cancel");if("upload"===r.direction){if(!(void 0===o?e.connection.cancelMediaUpload(r.messageId):e.connection.cancelMediaUpload(r.messageId,o)))throw y({code:"IM_SDK_MEDIA_TASK_CONTROL_REJECTED",category:"state",operation:"media.cancel",retryable:!1,conversation:r.ref});return}const a=D.get(t);if(void 0===a)throw re(r,"media.cancel");a.controller.abort();const i=S.has(t)?K(r.ref):Q(r.ref);q({...r,state:"canceled",error:i})},async pause(t){const o=oe(t,"media.pause");if("upload"!==o.direction||"queued"!==o.state&&"running"!==o.state)throw re(o,"media.pause");if(!await(e.connection.pauseMediaUpload?.(o.messageId)))throw y({code:"IM_SDK_MEDIA_TASK_CONTROL_REJECTED",category:"state",operation:"media.pause",retryable:!1,conversation:o.ref});V()},async resume(t){const o=oe(t,"media.resume");if("upload"!==o.direction||"paused"!==o.state)throw re(o,"media.resume");if(!e.connection.resumeMediaUpload?.(o.messageId))throw y({code:"IM_SDK_MEDIA_TASK_CONTROL_REJECTED",category:"state",operation:"media.resume",retryable:!1,conversation:o.ref})},async retry(t,o){const r=oe(t,"media.retry");if("failed"!==r.state&&"canceled"!==r.state)throw re(r,"media.retry");if("upload"===r.direction){if(void 0!==o?.restartDownload)throw re(r,"media.retry");if(("IM_SDK_MEDIA_UPLOAD_RESTART_REQUIRED"===r.error?.code||"IM_SDK_MEDIA_UPLOAD_CLEANUP_UNCONFIRMED"===r.error?.code)&&!0!==o?.restartUpload)throw y({code:"IM_SDK_MEDIA_UPLOAD_RESTART_REQUIRED",category:"state",operation:"media.retry",retryable:!0,conversation:r.ref});if(!(void 0===o?e.connection.retryMediaUpload(r.messageId):e.connection.retryMediaUpload(r.messageId,o)))throw y({code:"IM_SDK_MEDIA_TASK_CONTROL_REJECTED",category:"state",operation:"media.retry",retryable:!1,conversation:r.ref});return}if(void 0!==o?.restartUpload)throw re(r,"media.retry");if(D.has(t)&&!D.get(t).controller.signal.aborted)throw y({code:"IM_SDK_MEDIA_TASK_IN_FLIGHT",category:"state",operation:"media.retry",retryable:!0,conversation:r.ref});const a=h.get(t);if(void 0===a)throw y({code:"IM_SDK_MEDIA_TASK_NOT_FOUND",category:"state",operation:"media.retry",retryable:!1});!0===o?.restartDownload&&(L.delete(t),S.delete(t)),await te(G(a),!0)},async getUploadRecovery(t){V();const o=v(t);if(void 0!==t.itemIndex)return{available:!1,reason:"unsupported"};const r=t.messageId;if(void 0===e.recoveryPort)return{available:!1,reason:"unavailable"};const a=e.domainState.getConversationMessage(o,r);if(void 0===a)return{available:!1,reason:"not-found"};if(!f(a))return{available:!1,reason:"invalid-state"};try{const t=await e.recoveryPort.get(o,r);V();const a=e.domainState.getConversationMessage(o,r);return void 0===a?{available:!1,reason:"not-found"}:f(a)?void 0===t?{available:!1,reason:"not-found"}:{available:!0,expiresAt:t.savedAt+864e5}:{available:!1,reason:"invalid-state"}}catch(e){V();return{available:!1,reason:"object"==typeof e&&null!==e&&"reason"in e?String(e.reason):"storage"}}},async resumeUpload(t,o){V();const r=v(t);if(void 0!==t.itemIndex||void 0===e.connection.recoverMediaUpload)throw y({code:"IM_SDK_MEDIA_RECOVERY_UNAVAILABLE",category:"state",operation:"media.resumeUpload",retryable:!1,conversation:r});try{const a=await e.connection.recoverMediaUpload(r,t.messageId,o.file);if(V(),!a.ok&&"paused"===a.reason)throw y({code:"IM_SDK_MEDIA_PAUSED",category:"state",operation:"media.resumeUpload",retryable:!1,conversation:r});if(!a.ok&&"cancelled"===a.reason)throw y({code:"IM_SDK_MEDIA_CANCELLED",category:"state",operation:"media.resumeUpload",retryable:!1,conversation:r});if(!a.ok)throw y({code:"IM_SDK_MEDIA_RECOVERY_UPLOAD_FAILED",category:"state",operation:"media.resumeUpload",retryable:!0,conversation:r})}catch(e){if(V(),"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code&&e.code.startsWith("IM_SDK_"))throw e;throw y({code:e instanceof Error&&"IM_MEDIA_RECOVERY_FILE_MISMATCH"===e.message?"IM_SDK_MEDIA_RECOVERY_FILE_MISMATCH":"IM_SDK_MEDIA_RECOVERY_FAILED",category:"state",operation:"media.resumeUpload",retryable:!1,conversation:r})}},download:function(e){try{return V(),te(G(e))}catch(e){return Promise.reject(e)}},prioritizeDownload:function(e){V();const t=v(e);U=p("download",t,e.messageId,e.itemIndex)},probeCached:async function(t){V();const o=c,r=t.map(e=>G(e,!1)),a=/* @__PURE__ */new Map,i=s(),d=r.map(e=>{const t=p("download",e.ref,e.messageId,e.itemIndex);return A.has(t)&&M.get(t)===e.resourceVersion&&i-(b.get(t)??0)<n});r.forEach((e,t)=>{if(d[t]||void 0===e.cacheKind||void 0===e.resourceVersion)return;const o={kind:e.cacheKind,messageId:e.messageId,resourceVersion:e.resourceVersion};a.set(JSON.stringify(o),o)});const l=[...a.values()];let m=l.map(()=>!1);if(l.length>0&&void 0!==e.assetCache){if(void 0===e.assetCache.hasMany)throw y({code:"IM_SDK_MEDIA_CACHE_PROBE_UNAVAILABLE",category:"contract",operation:"media.probeCached",retryable:!1});try{if(m=await e.assetCache.hasMany(l),m.length!==l.length||m.some(e=>"boolean"!=typeof e))throw new Error("媒体缓存查询结果数量或类型不符")}catch(t){throw V(),e.onAssetCacheEvent?.({operation:"get",outcome:"failed",kind:l[0].kind,messageId:l[0].messageId,cause:t}),y({code:"IM_SDK_MEDIA_CACHE_READ_FAILED",category:"state",operation:"media.probeCached",retryable:!0})}}if(V(),o!==c)throw y({code:"IM_SDK_MEDIA_CACHE_QUERY_STALE",category:"state",operation:"media.probeCached",retryable:!0});const u=new Map(l.map((e,t)=>[JSON.stringify(e),m[t]]));return Object.freeze(r.map((e,t)=>d[t]||!0===u.get(JSON.stringify({kind:e.cacheKind,messageId:e.messageId,resourceVersion:e.resourceVersion}))))},subscribeCacheChanges:e=>(V(),w.add(e),()=>w.delete(e)),getCached:async function(e){const t=G(e,!1);return void 0===t.cacheKind?null:await Z(t,!0)},prepareLocalPreview:async function(t){if(V(),r(t.signal),void 0===e.preparePreview)throw y({code:"IM_SDK_MEDIA_PREVIEW_UNAVAILABLE",category:"contract",operation:"media.prepareLocalPreview",retryable:!1});let o;try{o=await e.preparePreview({operationId:"media.prepareLocalPreview:"+ ++I,kind:t.kind,file:t.file,..."video"===t.kind&&t.includeDisplayPoster?{includeDisplayPoster:!0}:{},...void 0===t.signal?{}:{signal:t.signal}})}catch(o){if(!0===t.signal?.aborted||o instanceof Error&&"AbortError"===o.name)throw o;return e.onLocalPreviewError?.({kind:t.kind,byteLength:t.file.size,cause:o}),null}return V(),r(t.signal),!Number.isFinite(o.width)||!Number.isFinite(o.height)||o.width<=0||o.height<=0?(e.onLocalPreviewError?.({kind:t.kind,byteLength:t.file.size,cause:new Error(`预览端口返回了不可用的尺寸 ${o.width}×${o.height}`)}),null):"video"===t.kind?{width:o.width,height:o.height,...void 0===o.duration?{}:{duration:o.duration},...void 0===o.posterData?{}:{posterData:o.posterData},...t.includeDisplayPoster&&o.displayPosterData?.byteLength?{displayPoster:new Blob([o.displayPosterData],{type:a(o.displayPosterData)})}:{}}:{width:o.width,height:o.height}},prepareLocalVideoPoster:async function(t){if(V(),r(t.signal),void 0===e.prepareVideoPoster)throw y({code:"IM_SDK_MEDIA_PREVIEW_UNAVAILABLE",category:"contract",operation:"media.prepareLocalVideoPoster",retryable:!1});let o;try{o=await e.prepareVideoPoster({operationId:"media.prepareLocalVideoPoster:"+ ++I,kind:"video",file:t.file,...void 0===t.signal?{}:{signal:t.signal}})}catch(o){if(r(t.signal),o instanceof Error&&"AbortError"===o.name)throw o;return V(),e.onLocalPreviewError?.({kind:"video",byteLength:t.file.size,cause:o}),null}return r(t.signal),V(),!Number.isFinite(o.width)||!Number.isFinite(o.height)||o.width<=0||o.height<=0||!o.posterData?.byteLength?(e.onLocalPreviewError?.({kind:"video",byteLength:t.file.size,cause:new Error("视频封面解码没有返回有效尺寸和图片字节")}),null):new Blob([o.posterData],{type:a(o.posterData)})},prepareLocalImageThumbnail:async function(t){if(V(),r(t.signal),void 0===e.prepareImageThumbnail)throw y({code:"IM_SDK_MEDIA_PREVIEW_UNAVAILABLE",category:"contract",operation:"media.prepareLocalImageThumbnail",retryable:!1});try{const o=new Uint8Array(await t.file.slice(0,3).arrayBuffer());if(r(t.signal),V(),255!==o[0]||216!==o[1]||255!==o[2])return t.file;const i="image/jpeg"===t.file.type?t.file:t.file.slice(0,t.file.size,"image/jpeg"),n=await e.prepareImageThumbnail({operationId:"media.prepareLocalImageThumbnail:"+ ++I,kind:"image",file:i,...void 0===t.signal?{}:{signal:t.signal}});if(r(t.signal),V(),!Number.isFinite(n.width)||!Number.isFinite(n.height)||n.width<=0||n.height<=0||!n.posterData?.byteLength)throw new Error("图片缩略图解码没有返回有效尺寸和图片字节");return new Blob([n.posterData],{type:a(n.posterData)})}catch(o){if(r(t.signal),o instanceof Error&&"AbortError"===o.name)throw o;return V(),e.onLocalPreviewError?.({kind:"image",byteLength:t.file.size,cause:o}),null}}},clearCache:Y,prune:B,dispose(){if(t){t=!1,c+=1,ae();for(const e of D.values())e.controller.abort();R.dispose(),U=void 0,D.clear(),E.clear(),w.clear(),M.clear(),_.clear(),h.clear(),A.clear(),b.clear(),L.clear(),S.clear(),k=0}}}}export{c as createDefaultMediaAssetCacheStrategyRegistry,_ as createMediaTasksRuntime,u as toProductMediaTaskUpdate};
1
+ import{createImSdkError as e}from"./message.js";import{createMediaAssetCacheStrategyRegistry as t,mediaAssetResourceVersion as o}from"../../../im-core/src/ports/media-asset-cache-port.js";import{throwIfAborted as r}from"../../../im-core/src/abort.js";import{resolveMediaThumbnailMimeType as a}from"../../../im-core/src/media-thumbnail.js";import{isCryptoExecutionError as i}from"../../../im-core/src/ports/crypto-task-executor.js";const n=6048e5,s=1048576;function d(e){let t=0,o=!1;const r=[];function a(){if(!o)for(;t<e&&r.length>0;){r.sort((e,t)=>t.getPriority()-e.getPriority());const e=r.shift();if(e.signal.removeEventListener("abort",e.onAbort),e.signal.aborted){e.reject(new DOMException("媒体下载已取消","AbortError"));continue}t+=1;let o=!1;e.resolve(()=>{o||(o=!0,t=Math.max(0,t-1),a())})}}return{acquire:(e,t)=>o?Promise.reject(new Error("媒体下载并发控制器已释放")):new Promise((o,i)=>{const n={resolve:o,reject:i,signal:e,getPriority:t,onAbort:()=>{const e=r.indexOf(n);e>=0&&r.splice(e,1),i(new DOMException("媒体下载已取消","AbortError"))}};e.addEventListener("abort",n.onAbort,{once:!0}),r.push(n),a()}),dispose(){o=!0;for(const e of r.splice(0))e.signal.removeEventListener("abort",e.onAbort),e.reject(new Error("媒体下载并发控制器已释放"))}}}function c(){return t([{kind:"image",softMaxBytes:512*s,maxEntries:512,maxEntryBytes:30*s,maxIdleMs:n},{kind:"video",softMaxBytes:1792*s,maxEntries:64,maxEntryBytes:200*s,maxIdleMs:n},{kind:"file",softMaxBytes:512*s,maxEntries:128,maxEntryBytes:200*s,maxIdleMs:n}])}function l(e){return Number.isFinite(e)?Math.max(0,Math.min(100,Math.round(e))):0}function m(e){return Object.freeze({conversationType:e.conversationType,conversationId:e.conversationId})}function p(e,t,o,r){const a=`${e}:${encodeURIComponent(t.conversationType)}:${encodeURIComponent(t.conversationId)}:${encodeURIComponent(o)}`;return void 0===r?a:`${a}:${r}`}function u(e){const t=e.ref.conversationType,o=e.ref.conversationId;if("direct"!==t&&"group"!==t&&"channel"!==t||""===o.trim())throw y({code:"supergroup"===t?"IM_SDK_SUPERGROUP_UNSUPPORTED":"IM_SDK_MEDIA_TASK_REF_INVALID",category:"supergroup"===t?"unsupported":"contract",operation:"media.tasks.project",retryable:!1});const r=m({conversationType:t,conversationId:o});return g({id:p(e.direction,r,e.messageId),messageId:e.messageId,ref:r,direction:e.direction,state:e.state,percent:l(e.percent),...void 0===e.items?{}:{items:e.items},...void 0===e.attempt?{}:{attempt:e.attempt},...void 0===e.maxAttempts?{}:{maxAttempts:e.maxAttempts},...void 0===e.bytesTransferred?{}:{bytesTransferred:e.bytesTransferred},...void 0===e.bytesTotal?{}:{bytesTotal:e.bytesTotal},...void 0===e.recovery?{}:{recovery:e.recovery},...void 0===e.recoveryReason?{}:{recoveryReason:e.recoveryReason},...void 0===e.phase?{}:{phase:e.phase},...void 0===e.failure?{}:{error:I(e.failure,r)}})}function y(t){const o=e(t);return Object.assign(new Error(o.code),o,{name:"ImMediaTaskOperationError"})}function f(e){return!(void 0!==e.recalled||void 0!==e.deletedForEveryone||"failed"!==e.status&&"uploading"!==e.status||"media.cancelled"===e.failure?.displayCode&&!0!==e.failure.retryable||"media.uploadTimeout"===e.failure?.displayCode&&!1===e.failure.retryable)}function I(t,o){if(void 0===t)return;const r=t.displayCode,a=void 0===r?void 0:{"media.empty":{code:"IM_SDK_MEDIA_EMPTY",category:"validation",retryable:!1},"media.noCrypto":{code:"IM_SDK_MEDIA_CRYPTO_UNAVAILABLE",category:"contract",retryable:!1},"media.previewFailed":{code:"IM_SDK_MEDIA_PREVIEW_FAILED",category:"state",retryable:!1},"media.encryptFailed":{code:"IM_SDK_MEDIA_ENCRYPT_FAILED",category:"state",retryable:!1},"media.uploadFailed":{code:"IM_SDK_MEDIA_UPLOAD_FAILED",category:"network",retryable:!0},"media.uploadTimeout":{code:"IM_SDK_MEDIA_UPLOAD_TIMEOUT",category:"network",retryable:!0},"media.resumeUnavailable":{code:"IM_SDK_MEDIA_UPLOAD_RESTART_REQUIRED",category:"state",retryable:!0},"media.cleanupUnconfirmed":{code:"IM_SDK_MEDIA_UPLOAD_CLEANUP_UNCONFIRMED",category:"state",retryable:!0},"media.cancelled":{code:"IM_SDK_MEDIA_UPLOAD_CANCELED",category:"state",retryable:!0},"media.invalidDuration":{code:"IM_SDK_VOICE_DURATION_INVALID",category:"validation",retryable:!1},"media.uploadInterrupted":{code:"IM_SDK_MEDIA_UPLOAD_INTERRUPTED",category:"network",retryable:!0}}[r];return Object.freeze(e({...a??{code:"IM_SDK_MEDIA_UPLOAD_FAILED",category:"state",retryable:t.retryable??!1},...!1===t.retryable?{retryable:!1}:{},operation:"media.upload",conversation:o}))}function g(e){return Object.freeze({...e,ref:m(e.ref),...void 0===e.items?{}:{items:Object.freeze(e.items.map(e=>Object.freeze({...e})))},...void 0===e.error?{}:{error:Object.freeze({...e.error})}})}function v(e){const t=e?.conversation,o=t?.conversationType,r=t?.conversationId;if("supergroup"===o)throw y({code:"IM_SDK_SUPERGROUP_UNSUPPORTED",category:"unsupported",operation:"media.download",retryable:!1});if("direct"!==o&&"group"!==o&&"channel"!==o||"string"!=typeof r||""===r.trim()||"string"!=typeof e?.messageId||""===e.messageId.trim())throw y({code:"IM_SDK_MEDIA_MESSAGE_REF_INVALID",category:"validation",operation:"media.download",retryable:!1});return m({conversationType:o,conversationId:r})}function _(e){let t=!0;const s=e.now??Date.now;let c=0,I=0;const _=/* @__PURE__ */new Map,E=/* @__PURE__ */new Set,h=/* @__PURE__ */new Map,D=/* @__PURE__ */new Map,A=/* @__PURE__ */new Map,b=/* @__PURE__ */new Map,M=/* @__PURE__ */new Map,w=/* @__PURE__ */new Set;let T=!1;const L=/* @__PURE__ */new Map,S=/* @__PURE__ */new Set,C=e.maxDownloadCheckpointBytes??536870912;function K(e){return y({code:"IM_SDK_MEDIA_DOWNLOAD_RESTART_REQUIRED",category:"state",operation:"media.download",retryable:!0,conversation:e})}function O(e,t){L.delete(e),S.add(e);const o=_.get(e);if(void 0!==o){const e={...o,recoveryReason:t,..."failed"===o.state||"canceled"===o.state?{error:K(o.ref)}:{}};"running"===o.state?$(e):q(e)}}const R=d(3);let U;const P=e.maxCachedBlobs??8,N=e.maxCachedBlobBytes??67108864;let k=0;function x(){if(!t||!e.isActive())throw y({code:"IM_SDK_MEDIA_RUNTIME_INACTIVE",category:"state",operation:"media.tasks",retryable:!1})}function V(){return Object.freeze([..._.values()])}function F(){const t=V();for(const o of[...E])try{o(t)}catch(t){e.emitter.emit({type:"error",error:{scope:"unknown",message:"媒体任务订阅者回调异常",cause:t}})}}function z(){!T&&t&&e.isActive()&&(T=!0,queueMicrotask(()=>{if(T=!1,t&&e.isActive())for(const t of[...w])try{t()}catch(t){e.emitter.emit({type:"error",error:{scope:"unknown",message:"媒体缓存订阅者回调异常",cause:t}})}}))}function B(e){const t=A.get(e);void 0!==t&&(k-=t.size,A.delete(e),b.delete(e),M.delete(e),z())}function j(){if(!t||!e.isActive())return;const o=s();for(const[e,t]of L)!D.has(e)&&void 0!==t.idleSince&&o-t.idleSince>=864e5&&O(e,"download-checkpoint-expired");for(const[e,t]of b)!D.has(e)&&o-t>=n&&B(e);z()}function W(e,t){const o=A.get(e);if(void 0!==o){if(!(M.get(e)!==t||s()-b.get(e)>=n))return A.delete(e),A.set(e,o),b.set(e,s()),o;B(e)}}function Y(){c+=1,A.clear(),b.clear(),M.clear(),z(),k=0;for(const e of[...L.keys()])O(e,"download-checkpoint-cleared")}function H(e){_.delete(e),h.delete(e),L.delete(e),S.delete(e),B(e)}function $(e){_.set(e.id,g(e)),function(){for(;_.size>128;){const e=[..._.values()].find(e=>"completed"===e.state||"failed"===e.state||"canceled"===e.state);if(void 0===e)return;H(e.id)}}()}function q(o){if(!t||!e.isActive())return;$(o);const r=_.get(o.id);if(F(),!t||!e.isActive()||void 0===r||_.get(o.id)!==r)return;const a={id:r.id,messageId:r.messageId,ref:r.ref,direction:"download",state:r.state,percent:r.percent};e.emitter.emit({type:"media-task:updated",conversation:r.ref,task:a})}function J(e,t,o){if(B(e),!(t.size>N))for(A.set(e,t),M.set(e,o),z(),b.set(e,s()),k+=t.size;A.size>P||k>N;){const e=A.keys().next().value;if(void 0===e)break;B(e)}}function G(t,r=!0){const a=v(t),i=e.domainState.getConversationMessage(a,t.messageId);if(void 0===i)throw y({code:"IM_SDK_MEDIA_MESSAGE_NOT_FOUND",category:"state",operation:"media.download",retryable:!1,conversation:a});let n,s,d,c;if("image"===i.contentType)n=i.body.image,s=e.loaders?.loadImage,c="image";else if("video"===i.contentType)n=i.body.video,s=e.loaders?.loadVideo,c="video";else if("voice"===i.contentType)n=i.body.voice,s=e.loaders?.loadVoice;else if("file"===i.contentType)n=i.body.file,s=e.loaders?.loadFile,d=i.body.file?.mimeType,c="file";else if("filesAlbum"===i.contentType){const o=t.itemIndex;if(n=void 0===o?void 0:i.body.filesAlbum?.items[o],void 0===n)throw y({code:"IM_SDK_MEDIA_ALBUM_ITEM_INVALID",category:"validation",operation:"media.download",retryable:!1,conversation:a});s=e.loaders?.loadFile,c="file"}else if("mediaAlbum"===i.contentType){const o=i.body.mediaAlbum?.items,r=t.itemIndex,d=void 0===r||void 0===o?void 0:o[r];if(void 0===d)throw y({code:"IM_SDK_MEDIA_ALBUM_ITEM_INVALID",category:"validation",operation:"media.download",retryable:!1,conversation:a});n=d,s="video"===d.kind?e.loaders?.loadVideo:e.loaders?.loadImage,c=d.kind}if("mediaAlbum"!==i.contentType&&"filesAlbum"!==i.contentType&&void 0!==t.itemIndex)throw y({code:"IM_SDK_MEDIA_ALBUM_ITEM_INVALID",category:"validation",operation:"media.download",retryable:!1,conversation:a});if(void 0===n)throw y({code:"IM_SDK_MEDIA_MESSAGE_UNSUPPORTED",category:"unsupported",operation:"media.download",retryable:!1,conversation:a});if(r&&void 0===s)throw y({code:"IM_SDK_MEDIA_DOWNLOAD_UNAVAILABLE",category:"contract",operation:"media.download",retryable:!1,conversation:a});if(""===n.url.trim()||n.url.startsWith("blob:"))throw y({code:"IM_SDK_MEDIA_REMOTE_URL_UNAVAILABLE",category:"state",operation:"media.download",retryable:!1,conversation:a});return{ref:a,messageId:i.id,...void 0===t.itemIndex?{}:{itemIndex:t.itemIndex},...void 0===d?{}:{mimeType:d},...void 0===c?{}:{cacheKind:c,resourceVersion:o(n.url,{conversation:a,itemIndex:t.itemIndex})},...void 0===s?{}:{load:s},input:{url:n.url,...void 0===n.size?{}:{expectedBytes:n.size},...void 0===n.teaKey?{}:{teaKey:n.teaKey},...void 0===n.fileEncryptType?{}:{fileEncryptType:n.fileEncryptType}}}}function Q(e){return y({code:"IM_SDK_MEDIA_DOWNLOAD_CANCELED",category:"state",operation:"media.download",retryable:!0,conversation:e})}function X(){return y({code:"IM_SDK_MEDIA_RUNTIME_INACTIVE",category:"state",operation:"media.download",retryable:!1})}async function Z(t,o,r=c){if(x(),r!==c)return null;const a=p("download",t.ref,t.messageId,t.itemIndex),i=W(a,t.resourceVersion);if(void 0!==i)return i;if(void 0===e.assetCache||void 0===t.cacheKind||void 0===t.resourceVersion)return null;let n;try{n=await e.assetCache.get({kind:t.cacheKind,messageId:t.messageId,resourceVersion:t.resourceVersion}),e.onAssetCacheEvent?.({operation:"get",outcome:null===n?"miss":"hit",kind:t.cacheKind,messageId:t.messageId,...null===n?{}:{byteLength:n.blob.size}})}catch(r){if(e.onAssetCacheEvent?.({operation:"get",outcome:"failed",kind:t.cacheKind,messageId:t.messageId,cause:r}),o)throw y({code:"IM_SDK_MEDIA_CACHE_READ_FAILED",category:"state",operation:"media.getCached",retryable:!0,conversation:t.ref});return null}if(null===n)return null;if(x(),r!==c)return null;const s=n.blob,d=n.mimeType??t.mimeType??"",l=s.type===d?s:s.slice(0,s.size,d);return J(a,l,t.resourceVersion),l}function ee(e,t){j();const o=L.get(e);if(void 0!==o&&o.url!==t.input.url&&O(e,"download-object-changed"),S.has(e)){const o=K(t.ref),r=_.get(e);throw void 0===r||"failed"!==r.state&&"canceled"!==r.state||q({...r,error:o}),o}return o?.state}function te(o,r=!1){const a=c,n=p("download",o.ref,o.messageId,o.itemIndex),d=D.get(n);if(void 0!==d&&!d.controller.signal.aborted)return d.promise;if(!r){const e=W(n,o.resourceVersion);if(void 0!==e)return q({id:n,ref:m(o.ref),messageId:o.messageId,...void 0===o.itemIndex?{}:{itemIndex:o.itemIndex},direction:"download",state:"completed",percent:100}),Promise.resolve(e)}B(n);const u=(()=>{const e=ee(n,o);return void 0===e?{percent:0}:{percent:Math.min(99,Math.round(e.bytesDownloaded/e.bytesTotal*100)),bytesTransferred:e.bytesDownloaded,bytesTotal:e.bytesTotal}})(),f=m(o.ref);h.set(n,Object.freeze({conversation:f,messageId:o.messageId,...void 0===o.itemIndex?{}:{itemIndex:o.itemIndex}}));const I={id:n,messageId:o.messageId,ref:f,direction:"download",...void 0===o.itemIndex?{}:{itemIndex:o.itemIndex}},g=new AbortController,v=Promise.resolve().then(async()=>{let d;try{if(!t||!e.isActive())throw X();if(g.signal.aborted)throw Q(f);if(d=await R.acquire(g.signal,()=>U===n?1:0),!t||!e.isActive())throw X();if(g.signal.aborted)throw Q(f);if(q({...I,...u,state:"running"}),!t||!e.isActive())throw X();if(g.signal.aborted)throw Q(f);if(!r&&void 0!==e.assetCache&&void 0!==o.cacheKind&&void 0!==o.resourceVersion){const e=await Z(o,!1,a);if(null!==e){if(g.signal.aborted)throw Q(f);return L.delete(n),S.delete(n),q({..._.get(n),...I,state:"completed",percent:100,error:void 0,recoveryReason:void 0}),e}}const i=o.load;if(void 0===i)throw y({code:"IM_SDK_MEDIA_DOWNLOAD_UNAVAILABLE",category:"contract",operation:"media.download",retryable:!1,conversation:f});const s=ee(n,o);if(void 0!==u.bytesTransferred&&(void 0===s||a!==c))throw O(n,"download-checkpoint-cleared"),K(f);const m=await i({...o.input,getPriority:()=>U===n?1:0,...void 0===s?{}:{resume:s},onResumable:r=>{t&&e.isActive()&&a===c&&D.get(n)?.controller===g&&function(e,t,o){L.delete(e),L.set(e,{url:t,state:o}),S.delete(e);let r=[...L.values()].reduce((e,t)=>e+t.state.bytesDownloaded,0);for(;L.size>8||r>C;){const e=L.entries().next().value;if(void 0===e)break;r-=e[1].state.bytesDownloaded,O(e[0],"download-checkpoint-limit")}}(n,o.input.url,r)},onResumeInvalidated:()=>{t&&e.isActive()&&a===c&&D.get(n)?.controller===g&&O(n,"download-checkpoint-invalid")},signal:g.signal,onTransferProgress:o=>{const r=_.get(n);t&&e.isActive()&&!g.signal.aborted&&D.get(n)?.controller===g&&"running"===r?.state&&q({...r,state:"running",percent:Math.min(99,l(o.percent)),bytesTransferred:o.bytesTransferred,bytesTotal:o.bytesTotal,phase:o.bytesTotal>0&&o.bytesTransferred>=o.bytesTotal?"finalizing":"transferring"})},onProgress:o=>{const r=_.get(n);if(!t||!e.isActive()||g.signal.aborted||D.get(n)?.controller!==g||"running"!==r?.state)return;const a=Math.min(99,l(o));a<=r.percent||q({...r,state:"running",percent:a})}});if(!t||!e.isActive())throw X();if(g.signal.aborted)throw Q(f);const p=m instanceof Blob?void 0:m;let v=void 0===p?m:new Blob([p],void 0===o.mimeType?void 0:{type:o.mimeType});if(void 0!==o.mimeType&&v.type!==o.mimeType&&(v=v.slice(0,v.size,o.mimeType)),a===c&&J(n,v,o.resourceVersion),a===c&&void 0!==e.assetCache&&void 0!==o.cacheKind&&void 0!==o.resourceVersion){const t=v.size;e.assetCache.put({kind:o.cacheKind,messageId:o.messageId,resourceVersion:o.resourceVersion,blob:v,...void 0===o.mimeType?{}:{mimeType:o.mimeType}}).then(r=>{z(),e.onAssetCacheEvent?.({operation:"put",outcome:r,kind:o.cacheKind,messageId:o.messageId,byteLength:t})}).catch(r=>{e.onAssetCacheEvent?.({operation:"put",outcome:"failed",kind:o.cacheKind,messageId:o.messageId,byteLength:t,cause:r})})}if(L.delete(n),S.delete(n),q({..._.get(n),...I,state:"completed",percent:100,error:void 0,recoveryReason:void 0}),!t||!e.isActive())throw X();return v}catch(o){if(!t||!e.isActive())throw X();if(g.signal.aborted||"object"==typeof o&&null!==o&&"code"in o&&"IM_SDK_MEDIA_DOWNLOAD_CANCELED"===o.code){const e=Q(f);throw D.get(n)?.controller===g&&"canceled"!==_.get(n)?.state&&q({..._.get(n),...I,state:"canceled",percent:_.get(n)?.percent??0,error:S.has(n)?K(f):e}),e}const r=S.has(n)?K(f):i(o)?y({code:"IM_SDK_CRYPTO_EXECUTION_FAILED",category:"state",operation:"crypto.execute",retryable:"queue-full"===o.reason,conversation:f,details:{reason:o.reason}}):o instanceof Error&&"ImMediaTaskOperationError"===o.name?o:y({code:"IM_SDK_MEDIA_DOWNLOAD_FAILED",category:"network",operation:"media.download",retryable:!0,conversation:f});throw D.get(n)?.controller===g&&q({..._.get(n),...I,state:"failed",percent:_.get(n)?.percent??0,error:r}),r}finally{if(d?.(),D.get(n)?.controller===g){D.delete(n);const e=L.get(n);void 0!==e&&(e.idleSince=s())}}});return D.set(n,{controller:g,promise:v}),q({...I,...u,state:"queued"}),v}function oe(e,t){x();const o=_.get(e);if(void 0===o)throw y({code:"IM_SDK_MEDIA_TASK_NOT_FOUND",category:"state",operation:t,retryable:!1});return o}function re(e,t){return y({code:"IM_SDK_MEDIA_TASK_INVALID_STATE",category:"state",operation:t,retryable:!1,conversation:e.ref,details:Object.freeze({state:e.state,direction:e.direction})})}const ae=e.emitter.subscribe(e=>{var o,r;t&&"media-task:updated"===e.type&&"upload"===e.task.direction&&(o=e.conversation,r=e.task.ref,o.conversationType===r.conversationType&&o.conversationId===r.conversationId&&($(u(e.task)),F()))});return{api:{async clearCache(){x(),e.connection.invalidateMediaAssetCacheWrites?.(),Y();try{await(e.assetCache?.clear())}catch(t){throw x(),e.emitter.emit({type:"error",error:{scope:"storage",message:"媒体缓存清理失败",cause:t}}),y({code:"IM_SDK_MEDIA_CACHE_CLEAR_FAILED",category:"state",operation:"media.clearCache",retryable:!0})}x(),z()},getSnapshot:()=>(x(),V()),subscribe:e=>(x(),E.add(e),()=>E.delete(e)),async cancel(t,o){const r=oe(t,"media.cancel");if("queued"!==r.state&&"running"!==r.state&&("upload"!==r.direction||"paused"!==r.state))throw re(r,"media.cancel");if("upload"===r.direction){if(!(void 0===o?e.connection.cancelMediaUpload(r.messageId):e.connection.cancelMediaUpload(r.messageId,o)))throw y({code:"IM_SDK_MEDIA_TASK_CONTROL_REJECTED",category:"state",operation:"media.cancel",retryable:!1,conversation:r.ref});return}const a=D.get(t);if(void 0===a)throw re(r,"media.cancel");a.controller.abort();const i=S.has(t)?K(r.ref):Q(r.ref);q({...r,state:"canceled",error:i})},async pause(t){const o=oe(t,"media.pause");if("upload"!==o.direction||"queued"!==o.state&&"running"!==o.state)throw re(o,"media.pause");if(!await(e.connection.pauseMediaUpload?.(o.messageId)))throw y({code:"IM_SDK_MEDIA_TASK_CONTROL_REJECTED",category:"state",operation:"media.pause",retryable:!1,conversation:o.ref});x()},async resume(t){const o=oe(t,"media.resume");if("upload"!==o.direction||"paused"!==o.state)throw re(o,"media.resume");if(!e.connection.resumeMediaUpload?.(o.messageId))throw y({code:"IM_SDK_MEDIA_TASK_CONTROL_REJECTED",category:"state",operation:"media.resume",retryable:!1,conversation:o.ref})},async retry(t,o){const r=oe(t,"media.retry");if("failed"!==r.state&&"canceled"!==r.state)throw re(r,"media.retry");if("upload"===r.direction){if(void 0!==o?.restartDownload)throw re(r,"media.retry");if(("IM_SDK_MEDIA_UPLOAD_RESTART_REQUIRED"===r.error?.code||"IM_SDK_MEDIA_UPLOAD_CLEANUP_UNCONFIRMED"===r.error?.code)&&!0!==o?.restartUpload)throw y({code:"IM_SDK_MEDIA_UPLOAD_RESTART_REQUIRED",category:"state",operation:"media.retry",retryable:!0,conversation:r.ref});if(!(void 0===o?e.connection.retryMediaUpload(r.messageId):e.connection.retryMediaUpload(r.messageId,o)))throw y({code:"IM_SDK_MEDIA_TASK_CONTROL_REJECTED",category:"state",operation:"media.retry",retryable:!1,conversation:r.ref});return}if(void 0!==o?.restartUpload)throw re(r,"media.retry");if(D.has(t)&&!D.get(t).controller.signal.aborted)throw y({code:"IM_SDK_MEDIA_TASK_IN_FLIGHT",category:"state",operation:"media.retry",retryable:!0,conversation:r.ref});const a=h.get(t);if(void 0===a)throw y({code:"IM_SDK_MEDIA_TASK_NOT_FOUND",category:"state",operation:"media.retry",retryable:!1});!0===o?.restartDownload&&(L.delete(t),S.delete(t)),await te(G(a),!0)},async getUploadRecovery(t){x();const o=v(t);if(void 0!==t.itemIndex)return{available:!1,reason:"unsupported"};const r=t.messageId;if(void 0===e.recoveryPort)return{available:!1,reason:"unavailable"};const a=e.domainState.getConversationMessage(o,r);if(void 0===a)return{available:!1,reason:"not-found"};if(!f(a))return{available:!1,reason:"invalid-state"};try{const t=await e.recoveryPort.get(o,r);x();const a=e.domainState.getConversationMessage(o,r);return void 0===a?{available:!1,reason:"not-found"}:f(a)?void 0===t?{available:!1,reason:"not-found"}:{available:!0,expiresAt:t.savedAt+864e5}:{available:!1,reason:"invalid-state"}}catch(e){x();return{available:!1,reason:"object"==typeof e&&null!==e&&"reason"in e?String(e.reason):"storage"}}},async resumeUpload(t,o){x();const r=v(t);if(void 0!==t.itemIndex||void 0===e.connection.recoverMediaUpload)throw y({code:"IM_SDK_MEDIA_RECOVERY_UNAVAILABLE",category:"state",operation:"media.resumeUpload",retryable:!1,conversation:r});try{const a=await e.connection.recoverMediaUpload(r,t.messageId,o.file);if(x(),!a.ok&&"paused"===a.reason)throw y({code:"IM_SDK_MEDIA_PAUSED",category:"state",operation:"media.resumeUpload",retryable:!1,conversation:r});if(!a.ok&&"cancelled"===a.reason)throw y({code:"IM_SDK_MEDIA_CANCELLED",category:"state",operation:"media.resumeUpload",retryable:!1,conversation:r});if(!a.ok)throw y({code:"IM_SDK_MEDIA_RECOVERY_UPLOAD_FAILED",category:"state",operation:"media.resumeUpload",retryable:!0,conversation:r})}catch(e){if(x(),"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code&&e.code.startsWith("IM_SDK_"))throw e;throw y({code:e instanceof Error&&"IM_MEDIA_RECOVERY_FILE_MISMATCH"===e.message?"IM_SDK_MEDIA_RECOVERY_FILE_MISMATCH":"IM_SDK_MEDIA_RECOVERY_FAILED",category:"state",operation:"media.resumeUpload",retryable:!1,conversation:r})}},download:function(e){try{return x(),te(G(e))}catch(e){return Promise.reject(e)}},prioritizeDownload:function(e){x();const t=v(e);U=p("download",t,e.messageId,e.itemIndex)},probeCached:async function(t){x();const o=c,r=t.map(e=>G(e,!1)),a=/* @__PURE__ */new Map,i=s(),d=r.map(e=>{const t=p("download",e.ref,e.messageId,e.itemIndex);return A.has(t)&&M.get(t)===e.resourceVersion&&i-(b.get(t)??0)<n});r.forEach((e,t)=>{if(d[t]||void 0===e.cacheKind||void 0===e.resourceVersion)return;const o={kind:e.cacheKind,messageId:e.messageId,resourceVersion:e.resourceVersion};a.set(JSON.stringify(o),o)});const l=[...a.values()];let m=l.map(()=>!1);if(l.length>0&&void 0!==e.assetCache){if(void 0===e.assetCache.hasMany)throw y({code:"IM_SDK_MEDIA_CACHE_PROBE_UNAVAILABLE",category:"contract",operation:"media.probeCached",retryable:!1});try{if(m=await e.assetCache.hasMany(l),m.length!==l.length||m.some(e=>"boolean"!=typeof e))throw new Error("媒体缓存查询结果数量或类型不符")}catch(t){throw x(),e.onAssetCacheEvent?.({operation:"get",outcome:"failed",kind:l[0].kind,messageId:l[0].messageId,cause:t}),y({code:"IM_SDK_MEDIA_CACHE_READ_FAILED",category:"state",operation:"media.probeCached",retryable:!0})}}if(x(),o!==c)throw y({code:"IM_SDK_MEDIA_CACHE_QUERY_STALE",category:"state",operation:"media.probeCached",retryable:!0});const u=new Map(l.map((e,t)=>[JSON.stringify(e),m[t]]));return Object.freeze(r.map((e,t)=>d[t]||!0===u.get(JSON.stringify({kind:e.cacheKind,messageId:e.messageId,resourceVersion:e.resourceVersion}))))},subscribeCacheChanges:e=>(x(),w.add(e),()=>w.delete(e)),getCached:async function(e){const t=G(e,!1);return void 0===t.cacheKind?null:await Z(t,!0)},prepareLocalPreview:async function(t){if(x(),r(t.signal),void 0===e.preparePreview)throw y({code:"IM_SDK_MEDIA_PREVIEW_UNAVAILABLE",category:"contract",operation:"media.prepareLocalPreview",retryable:!1});let o;try{o=await e.preparePreview({operationId:"media.prepareLocalPreview:"+ ++I,kind:t.kind,file:t.file,..."video"===t.kind&&t.includeDisplayPoster?{includeDisplayPoster:!0}:{},...void 0===t.signal?{}:{signal:t.signal}})}catch(o){if(!0===t.signal?.aborted||o instanceof Error&&"AbortError"===o.name)throw o;return e.onLocalPreviewError?.({kind:t.kind,byteLength:t.file.size,cause:o}),null}return x(),r(t.signal),!Number.isFinite(o.width)||!Number.isFinite(o.height)||o.width<=0||o.height<=0?(e.onLocalPreviewError?.({kind:t.kind,byteLength:t.file.size,cause:new Error(`预览端口返回了不可用的尺寸 ${o.width}×${o.height}`)}),null):"video"===t.kind?{width:o.width,height:o.height,...void 0===o.duration?{}:{duration:o.duration},...void 0===o.posterData?{}:{posterData:o.posterData},...t.includeDisplayPoster&&o.displayPosterData?.byteLength?{displayPoster:new Blob([o.displayPosterData],{type:a(o.displayPosterData)})}:{}}:{width:o.width,height:o.height}},prepareLocalVideoPoster:async function(t){if(x(),r(t.signal),void 0===e.prepareVideoPoster)throw y({code:"IM_SDK_MEDIA_PREVIEW_UNAVAILABLE",category:"contract",operation:"media.prepareLocalVideoPoster",retryable:!1});let o;try{o=await e.prepareVideoPoster({operationId:"media.prepareLocalVideoPoster:"+ ++I,kind:"video",file:t.file,...void 0===t.signal?{}:{signal:t.signal}})}catch(o){if(r(t.signal),o instanceof Error&&"AbortError"===o.name)throw o;return x(),e.onLocalPreviewError?.({kind:"video",byteLength:t.file.size,cause:o}),null}return r(t.signal),x(),!Number.isFinite(o.width)||!Number.isFinite(o.height)||o.width<=0||o.height<=0||!o.posterData?.byteLength?(e.onLocalPreviewError?.({kind:"video",byteLength:t.file.size,cause:new Error("视频封面解码没有返回有效尺寸和图片字节")}),null):new Blob([o.posterData],{type:a(o.posterData)})},prepareLocalImageThumbnail:async function(t){if(x(),r(t.signal),void 0===e.prepareImageThumbnail)throw y({code:"IM_SDK_MEDIA_PREVIEW_UNAVAILABLE",category:"contract",operation:"media.prepareLocalImageThumbnail",retryable:!1});try{const o=new Uint8Array(await t.file.slice(0,3).arrayBuffer());if(r(t.signal),x(),255!==o[0]||216!==o[1]||255!==o[2])return t.file;const i="image/jpeg"===t.file.type?t.file:t.file.slice(0,t.file.size,"image/jpeg"),n=await e.prepareImageThumbnail({operationId:"media.prepareLocalImageThumbnail:"+ ++I,kind:"image",file:i,...void 0===t.signal?{}:{signal:t.signal}});if(r(t.signal),x(),!Number.isFinite(n.width)||!Number.isFinite(n.height)||n.width<=0||n.height<=0||!n.posterData?.byteLength)throw new Error("图片缩略图解码没有返回有效尺寸和图片字节");return new Blob([n.posterData],{type:a(n.posterData)})}catch(o){if(r(t.signal),o instanceof Error&&"AbortError"===o.name)throw o;return x(),e.onLocalPreviewError?.({kind:"image",byteLength:t.file.size,cause:o}),null}}},clearCache:Y,prune:j,dispose(){if(t){t=!1,c+=1,ae();for(const e of D.values())e.controller.abort();R.dispose(),U=void 0,D.clear(),E.clear(),w.clear(),M.clear(),_.clear(),h.clear(),A.clear(),b.clear(),L.clear(),S.clear(),k=0}}}}export{c as createDefaultMediaAssetCacheStrategyRegistry,_ as createMediaTasksRuntime,u as toProductMediaTaskUpdate};
package/dist/sdk.d.ts CHANGED
@@ -5186,7 +5186,7 @@ interface ImMediaTasksApi {
5186
5186
  clearCache: () => Promise<void>;
5187
5187
  /**
5188
5188
  * 按输入顺序查询完整本机媒体是否可用;不下载、不读取 Blob、不续缓存期限或创建任务。
5189
- * 仅支持图片/视频(含媒体合集);未配置持久缓存时只检查内存。
5189
+ * 支持图片、视频和文件(含各自合集);未配置持久缓存时只检查内存。
5190
5190
  * @throws 不支持轻量查询或存储读取失败时明确拒绝,不伪装成未命中。
5191
5191
  * @example const [available] = await client.media.probeCached([messageRef])
5192
5192
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "k2-im",
3
3
  "type": "module",
4
- "version": "0.2.11",
4
+ "version": "0.2.12",
5
5
  "private": false,
6
6
  "license": "MIT",
7
7
  "publishConfig": {