@atkonoffice/sdk 1.7.0 → 1.8.0

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.
@@ -1 +1 @@
1
- var y={};var n={backendBase:"",launchPath:"/atkonoffice-rpc/launch",wsTicketPath:"/atkonoffice-rpc/ws-ticket",fetchImpl:null,initialized:!1,ws:null,wsUrl:"",pairId:"",nodeBase:"",headers:null,eventHandlers:{},wsReconnectAttempt:0,wsReconnectTimer:null,wsTicketInFlight:!1,wsStopped:!1,wsBackoffExhausted:!1,channelLostAnnounced:!1,channelRestoreConfirmTimer:null,pairing:!1,launchTicket:"",openParams:null,fallbackUrl:"",pairingPrevTitle:"",pairingTitleSaved:!1,pairingRecoverTimer:null,pairingTimeoutTimer:null,pairTimeoutMs:5e3,pairRecoverMs:1e3,titleRelayInstalled:!1,trustedFrameOrigins:null,onPairDowngrade:null,replayOpen:null,launchInFlight:!1,inFlightOpen:null};function x(){n.launchInFlight=!1,n.inFlightOpen=null}var U="atkonoffice.ws.session",Q=12,Z=3e5,Te=1e3,A="channelLost",B="channelRestored",D=["documentSaved","documentOpened","documentBeforeSave","documentEmbedFailed","shellClosed",A,B,"error"],ee="shell.closed",P={"doc.saved":"documentSaved","doc.opened":"documentOpened","doc.beforeSave":"documentBeforeSave",[ee]:"shellClosed"},R="atkonoffice-launch=",H="\u2007",F="pair.ready",Ee="launch.open",be="doc.embedFailed",M="__atkonofficeTitle",te="atkonoffice-install-guide";function ne(e){return e&&e.endsWith("/")?e.slice(0,-1):e}function Re(e,t){if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function W(e,t,o){let r=e.indexOf("?")===-1?"?":"&";return e+r+t+"="+o}function G(e){return!!e&&Object.keys(e).length>0}function b(e){return e&&e.message?e.message:String(e)}function I(e,t,o){if(t==null)return;let r=String(t).trim();r&&(e[r]=o==null?"":String(o))}function xe(e){return e?typeof e=="string"?e:typeof e=="object"?Object.keys(e).map(t=>t+"="+String(e[t])).join("; "):"":""}function ke(e){let t;if(typeof TextEncoder<"u"){let o=new TextEncoder().encode(e),r="";for(let i=0;i<o.length;i++)r+=String.fromCharCode(o[i]);t=r}else t=unescape(encodeURIComponent(e));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(){try{return typeof document<"u"&&typeof document.title=="string"?document.title:""}catch{return""}}function oe(){if(typeof window>"u")return!1;try{return window.top!==window.self}catch{return!0}}function j(e){try{let t=document.createElement("iframe");t.style.display="none",t.src=e,document.body.appendChild(t),setTimeout(()=>{try{document.body.removeChild(t)}catch{}},1e3)}catch{window.location.href=e}}function Y(e){return!!(typeof e.launchTicket=="string"&&e.launchTicket&&typeof e.wsUrl=="string"&&e.wsUrl&&typeof e.wsTicket=="string"&&e.wsTicket&&typeof document<"u"&&typeof WebSocket<"u")}var l={CONFIG:"config",LAUNCH:"launch",CHANNEL:"channel"},re={backend_base_missing:l.CONFIG,doc_id_missing:l.CONFIG,fetch_unavailable:l.CONFIG,ws_unsupported:l.CONFIG,ws_ticket_backend_missing:l.CONFIG,ws_ticket_node_mismatch:l.CONFIG,launch_request_failed:l.LAUNCH,launch_http_error:l.LAUNCH,launch_response_not_json:l.LAUNCH,launch_response_invalid:l.LAUNCH,launch_open_frame_send_failed:l.LAUNCH,ws_url_missing:l.CHANNEL,ws_ticket_missing:l.CHANNEL,ws_connect_failed:l.CHANNEL,ws_error:l.CHANNEL,headers_frame_send_failed:l.CHANNEL,ws_no_pair_to_resume:l.CHANNEL,ws_backoff_exhausted:l.CHANNEL,ws_gave_up:l.CHANNEL,ws_ticket_http_error:l.CHANNEL,ws_ticket_response_invalid:l.CHANNEL,ws_ticket_refresh_failed:l.CHANNEL};function a(e,t){let o=new Error(t);return o.code=e,o.category=re[e],o}function ie(){return typeof n.fetchImpl=="function"?n.fetchImpl:typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):null}function ht(){let e=ie();if(!e)throw a("fetch_unavailable","atkonoffice: no fetch available \u2014 pass fetchImpl via config in non-browser hosts");return e}async function V(e,t){let o;try{o=await ht()(n.backendBase+n.launchPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(r){throw r&&re[r.code]?r:a("launch_request_failed",t+" request failed \u2014 "+b(r))}if(!o.ok)throw a("launch_http_error",t+" endpoint returned HTTP "+o.status);try{return await o.json()}catch(r){throw a("launch_response_not_json",t+" response was not JSON \u2014 "+b(r))}}var T={PERM:"PERM",SLOW:"SLOW",RETRY:"RETRY"},se=":",gt=[[T.PERM+se,T.PERM],[T.SLOW+se,T.SLOW],[T.RETRY+se,T.RETRY]];function Oe(e){if(typeof e!="string"||!e)return T.RETRY;for(let t of gt)if(e.indexOf(t[0])===0)return t[1];return T.RETRY}function Se(e){n.launchTicket=e.launchTicket,n.openParams=e.openParams&&typeof e.openParams=="object"?e.openParams:{},n.fallbackUrl=e.launchUrl,n.pairing||(n.pairingTitleSaved=!1),n.pairing=!0,ae(),yt()}function Ce(){if(!(!n.pairing||typeof document>"u")){if(!n.pairingTitleSaved){let e=k();e.indexOf(R)<0&&(n.pairingPrevTitle=e,n.pairingTitleSaved=!0)}Pe(),_t()}}function Pe(){O(K(n.wsUrl,n.pairId,n.launchTicket))}function K(e,t,o){let r=ke(JSON.stringify({wsUrl:e,pairId:t,launchTicket:o}));return H+R+r}function O(e){try{typeof document<"u"&&(document.title=e)}catch{}if(oe())try{let t={};t[M]=e,window.top.postMessage(t,"*")}catch{}}function ae(){n.titleRelayInstalled||typeof window>"u"||typeof window.addEventListener!="function"||oe()||(n.titleRelayInstalled=!0,window.addEventListener("message",e=>{if(!wt(e&&e.origin))return;let t=e&&e.data;if(t&&typeof t=="object"&&typeof t[M]=="string")try{document.title=t[M]}catch{}}))}function wt(e){let t=n.trustedFrameOrigins;return!t||t.length===0?!0:typeof e=="string"&&t.indexOf(e)!==-1}function _t(){n.pairingRecoverTimer||typeof setInterval>"u"||(n.pairingRecoverTimer=setInterval(()=>{n.pairing&&k().indexOf(R)<0&&Pe()},n.pairRecoverMs))}function yt(){n.pairingTimeoutTimer||typeof setTimeout>"u"||(n.pairingTimeoutTimer=setTimeout(()=>{n.pairingTimeoutTimer=null,Ne(!0)},n.pairTimeoutMs))}function Ie(){if(!n.pairing)return;let e=n.ws;Ne(!1),x(),e&&Tt(e)}function Tt(e){let t={v:1,type:"event",op:Ee,ts:Math.floor(Date.now()/1e3),payload:{pair_id:n.pairId,openParams:n.openParams||{}}};try{e.send(JSON.stringify(t))}catch(o){u("error",a("launch_open_frame_send_failed","atkonoffice: failed to send launch.open frame \u2014 "+b(o)))}}function Ne(e){n.pairingRecoverTimer&&(clearInterval(n.pairingRecoverTimer),n.pairingRecoverTimer=null),n.pairingTimeoutTimer&&(clearTimeout(n.pairingTimeoutTimer),n.pairingTimeoutTimer=null);let t=n.pairing;n.pairing=!1,n.pairingTitleSaved&&(O(n.pairingPrevTitle),n.pairingTitleSaved=!1),e&&t&&(j(n.fallbackUrl),typeof n.onPairDowngrade=="function"&&n.onPairDowngrade())}var Et="documentEmbedFailed";function ve(e){u(Et,e||{})}function ce(e,t,o){if(!(!e||typeof sessionStorage>"u"))try{sessionStorage.setItem(U,JSON.stringify({pairId:e,wsUrl:t,nodeBase:o||""}))}catch{}}function Ae(){if(n.pairId)return{pairId:n.pairId,wsUrl:n.wsUrl,nodeBase:n.nodeBase};if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(U);return e?JSON.parse(e):null}catch{return null}}function bt(){n.pairId="",n.wsUrl="",n.nodeBase=""}function Be(){if(!(typeof sessionStorage>"u"))try{sessionStorage.removeItem(U)}catch{}}function Le(){bt(),Be()}function J(){if(n.ws||n.wsReconnectTimer||n.wsTicketInFlight||n.wsStopped||!n.backendBase)return;let e=Ae();!e||!e.pairId||(n.pairId=e.pairId,n.wsUrl=e.wsUrl||n.wsUrl,n.nodeBase=e.nodeBase||n.nodeBase,n.wsReconnectAttempt=0,De(e.pairId,t=>X(t)))}function X(e){if(typeof WebSocket>"u"){u("error",a("ws_unsupported","atkonoffice: WebSocket unavailable in this host \u2014 document events disabled"));return}if(!n.wsUrl){u("error",a("ws_url_missing","atkonoffice: no wsUrl \u2014 cannot open the document-event channel"));return}if(!e){u("error",a("ws_ticket_missing","atkonoffice: missing ws_ticket \u2014 cannot subscribe to document events"));return}le();let t=W(n.wsUrl,"ticket",encodeURIComponent(e)),o;try{o=new WebSocket(t)}catch(r){u("error",a("ws_connect_failed","atkonoffice: WS connect failed \u2014 "+b(r))),N();return}n.ws=o,o.onopen=()=>{n.wsBackoffExhausted&&ce(n.pairId,n.wsUrl,n.nodeBase),n.wsReconnectAttempt=0,n.wsStopped=!1,n.wsBackoffExhausted=!1,Rt(o),Ot(o),n.pairing&&Ce()},o.onmessage=r=>{St(r&&r.data)},o.onerror=()=>{u("error",a("ws_error","atkonoffice: WS error on the document-event channel"))},o.onclose=r=>{if(n.ws===o&&(n.ws=null),fe(),Oe(r&&r.reason)===T.PERM){xt("server closed it permanently; reopen the document from the page to start a new session");return}N()}}function Ue(e){n.channelLostAnnounced||(n.channelLostAnnounced=!0,u(A,{reason:e}))}function Rt(e){fe(),n.channelLostAnnounced&&(n.channelRestoreConfirmTimer=setTimeout(()=>{n.channelRestoreConfirmTimer=null,!(n.ws!==e||!n.channelLostAnnounced)&&(n.channelLostAnnounced=!1,u(B,{}))},Te))}function fe(){n.channelRestoreConfirmTimer&&(clearTimeout(n.channelRestoreConfirmTimer),n.channelRestoreConfirmTimer=null)}function xt(e){n.wsStopped=!0,n.wsBackoffExhausted=!1,le(),Le();let t=a("ws_gave_up","atkonoffice: document-event channel lost \u2014 "+e);t.terminal=!0,u("error",t),Ue("rejected")}function kt(e){n.wsBackoffExhausted=!0,Be();let t=a("ws_backoff_exhausted","atkonoffice: document-event channel still unreachable "+e+" \u2014 left fast reconnect, now probing every "+Math.round(Z/1e3)+"s until it comes back");t.terminal=!1,u("error",t),Ue("unreachable")}function le(){n.wsReconnectTimer&&(clearTimeout(n.wsReconnectTimer),n.wsReconnectTimer=null),fe();let e=n.ws;if(n.ws=null,e){e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{e.close(1e3,"client_close")}catch{}}}function Ot(e){if(!G(n.headers))return;let t={v:1,type:"event",op:"client.headers",ts:Math.floor(Date.now()/1e3),payload:{headers:n.headers}};try{e.send(JSON.stringify(t))}catch(o){u("error",a("headers_frame_send_failed","atkonoffice: failed to send headers frame \u2014 "+b(o)))}}function St(e){if(typeof e!="string")return;let t;try{t=JSON.parse(e)}catch{return}if(!t||t.type!=="event")return;if(t.op===F){Ie();return}if(t.op===be){ve(t.payload||{});return}let o=P[t.op];o&&u(o,t.payload||{}),t.op===ee&&(n.wsBackoffExhausted=!1,Le(),le())}function N(){if(n.wsReconnectTimer||n.wsStopped)return;let e=Ae();if(!e||!e.pairId){u("error",a("ws_no_pair_to_resume","atkonoffice: document-event channel dropped and no pair to resume"));return}let t=n.wsReconnectAttempt>=Q,o;if(t)o=Z;else{let r=n.wsReconnectAttempt+1;n.wsReconnectAttempt=r,o=Math.min(3e4,500*Math.pow(2,r-1))}n.wsReconnectTimer=setTimeout(()=>{n.wsReconnectTimer=null,n.nodeBase=e.nodeBase||n.nodeBase,De(e.pairId,r=>{n.pairId=e.pairId,n.wsUrl=e.wsUrl||n.wsUrl,X(r)})},o),t&&!n.wsBackoffExhausted&&kt("after "+Q+" consecutive fast reconnect attempts")}async function De(e,t){let o=ie();if(!o||!n.backendBase){u("error",a("ws_ticket_backend_missing","atkonoffice: cannot refresh ws_ticket \u2014 backend not configured")),N();return}n.wsTicketInFlight=!0;let r=Re(n.nodeBase,n.backendBase)?n.nodeBase:n.backendBase;try{let i=await o(r+n.wsTicketPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pairId:e,backendBase:r})});if(!i.ok){u("error",a("ws_ticket_http_error","atkonoffice: ws_ticket refresh returned HTTP "+i.status)),N();return}let s=await i.json();if(!s||typeof s.wsTicket!="string"||!s.wsTicket){u("error",a("ws_ticket_response_invalid","atkonoffice: ws_ticket refresh response missing wsTicket")),N();return}typeof s.wsUrl=="string"&&s.wsUrl&&(n.nodeBase&&n.wsUrl&&s.wsUrl!==n.wsUrl?u("error",a("ws_ticket_node_mismatch","atkonoffice: ws_ticket refresh was served by a different backend instance than this session \u2014 expected "+n.wsUrl+", got "+s.wsUrl+" (multi-instance: check the load balancer routes this session node prefix to that instance)")):n.wsUrl=s.wsUrl),t(s.wsTicket)}catch(i){u("error",a("ws_ticket_refresh_failed","atkonoffice: ws_ticket refresh failed \u2014 "+b(i))),N()}finally{n.wsTicketInFlight=!1}}function Ct(e){let t=n.eventHandlers[e];return!!t&&t.length>0}function Pt(e){for(let t in P)if(P.hasOwnProperty(t)&&P[t]===e)return!0;return!1}function He(e){return Pt(e)||e===A||e===B}function Fe(){return D.some(e=>He(e)&&Ct(e))}function u(e,t){let o=n.eventHandlers[e];if(!o||o.length===0){if(e==="error")try{console.error("[atkonoffice] "+(t&&t.message?t.message:t))}catch{}return}for(let r of o.slice())try{r(t)}catch{}}function Me(e,t){if(typeof e!="string"||D.indexOf(e)===-1)throw new TypeError('atkonoffice.on: unknown event "'+e+'" (expected one of '+D.join(", ")+")");if(typeof t!="function")throw new TypeError("atkonoffice.on: handler must be a function");return n.eventHandlers[e]||(n.eventHandlers[e]=[]),n.eventHandlers[e].push(t),He(e)&&J(),y}function We(){Nt(n.pairTimeoutMs).then(e=>{x(),e.installed||At(e.clientDownloadUrl)})}function It(e){let t=e.indexOf(R);if(t<0)return null;let o=t;for(;o>0&&e.charAt(o-1)===H;)o-=1;return e.slice(0,o)}function Nt(e){return new Promise(t=>{let o=!1,r=null,i=null,s=null,h=!1,c="",g="",w=()=>{if(i&&(clearTimeout(i),i=null),s&&(clearInterval(s),s=null),h)O(c),h=!1;else{let p=It(k());p!==null&&O(p)}if(r){r.onopen=r.onmessage=r.onerror=r.onclose=null;try{r.close(1e3,"probe_done")}catch{}r=null}},m=p=>{o||(o=!0,w(),t({installed:p,clientDownloadUrl:g}))};i=setTimeout(()=>m(!1),e),vt().then(p=>{if(p&&typeof p.clientDownloadUrl=="string"&&(g=p.clientDownloadUrl),o||!Y(p)){m(!1);return}let $=p.wsUrl,we=typeof p.pairId=="string"?p.pairId:"",_e=p.launchTicket;ae();let S;try{S=new WebSocket(W($,"ticket",encodeURIComponent(p.wsTicket)))}catch{m(!1);return}r=S,S.onopen=()=>{let C=k();C.indexOf(R)<0&&(c=C,h=!0),O(K($,we,_e)),s=setInterval(()=>{!o&&k().indexOf(R)<0&&O(K($,we,_e))},n.pairRecoverMs)},S.onmessage=C=>{let ye=C&&C.data;if(typeof ye!="string")return;let L;try{L=JSON.parse(ye)}catch{return}L&&L.type==="event"&&L.op===F&&m(!0)},S.onerror=()=>{},S.onclose=()=>{}}).catch(()=>{m(!1)})})}async function vt(){return V({docId:"",pageUrl:"",user:"",backendBase:n.backendBase},"atkonoffice: launch-probe")}function At(e){if(typeof document>"u"||!document.body||typeof document.createElement!="function")return null;ue();let t=document.createElement("div");t.setAttribute("data-atkonoffice-guide",te),t.style.cssText="position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.45);font:14px/1.6 system-ui,-apple-system,sans-serif;";let o=document.createElement("div");o.style.cssText="background:#fff;color:#222;max-width:420px;width:86%;border-radius:8px;padding:24px;box-shadow:0 8px 32px rgba(0,0,0,0.25);box-sizing:border-box;";let r=document.createElement("h2");r.textContent="\u9700\u8981\u5B89\u88C5\u7F16\u8F91\u5668\u5BA2\u6237\u7AEF",r.style.cssText="margin:0 0 12px;font-size:18px;";let i=document.createElement("p");i.style.cssText="margin:0 0 20px;color:#444;",i.textContent=e?"\u672A\u68C0\u6D4B\u5230\u672C\u673A\u5DF2\u5B89\u88C5\u7F16\u8F91\u5668\u5BA2\u6237\u7AEF\u3002\u8BF7\u5148\u4E0B\u8F7D\u5E76\u5B89\u88C5,\u5B89\u88C5\u5B8C\u6210\u540E\u70B9\u300C\u6211\u5DF2\u5B89\u88C5,\u91CD\u8BD5\u300D\u3002":"\u672A\u68C0\u6D4B\u5230\u672C\u673A\u5DF2\u5B89\u88C5\u7F16\u8F91\u5668\u5BA2\u6237\u7AEF,\u4E14\u672A\u914D\u7F6E\u4E0B\u8F7D\u5730\u5740\u3002\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u83B7\u53D6\u5B89\u88C5\u5305,\u5B89\u88C5\u5B8C\u6210\u540E\u70B9\u300C\u6211\u5DF2\u5B89\u88C5,\u91CD\u8BD5\u300D\u3002";let s=document.createElement("div");s.style.cssText="display:flex;gap:10px;justify-content:flex-end;flex-wrap:wrap;";let h="font:inherit;padding:8px 16px;border-radius:6px;cursor:pointer;border:1px solid #ccc;background:#f6f6f6;color:#222;",c="font:inherit;padding:8px 16px;border-radius:6px;cursor:pointer;border:1px solid #1a6dd6;background:#1a6dd6;color:#fff;text-decoration:none;display:inline-block;";if(e){let m=document.createElement("a");m.textContent="\u4E0B\u8F7D\u5BA2\u6237\u7AEF",m.href=e,m.target="_blank",m.rel="noopener noreferrer",m.style.cssText=c,s.appendChild(m)}let g=document.createElement("button");g.type="button",g.textContent="\u6211\u5DF2\u5B89\u88C5,\u91CD\u8BD5",g.style.cssText=h,g.addEventListener("click",()=>{ue();try{typeof n.replayOpen=="function"&&n.replayOpen()}catch{}});let w=document.createElement("button");return w.type="button",w.textContent="\u5173\u95ED",w.style.cssText=h,w.addEventListener("click",()=>ue()),s.appendChild(g),s.appendChild(w),o.appendChild(r),o.appendChild(i),o.appendChild(s),t.appendChild(o),document.body.appendChild(t),t}function ue(){if(!(typeof document>"u"||typeof document.querySelector!="function"))try{let e=document.querySelector('[data-atkonoffice-guide="'+te+'"]');e&&typeof e.remove=="function"?e.remove():e&&e.parentNode&&typeof e.parentNode.removeChild=="function"&&e.parentNode.removeChild(e)}catch{}}function Ge(e){if(!e||typeof e!="object")throw new TypeError("atkonoffice.config requires an options object");if(typeof e.backendBase=="string"&&(n.backendBase=ne(e.backendBase)),typeof e.launchPath=="string"&&e.launchPath&&(n.launchPath=e.launchPath),typeof e.wsTicketPath=="string"&&e.wsTicketPath&&(n.wsTicketPath=e.wsTicketPath),typeof e.fetchImpl=="function"&&(n.fetchImpl=e.fetchImpl),Array.isArray(e.trustedFrameOrigins)){let t=e.trustedFrameOrigins.filter(o=>typeof o=="string"&&o);n.trustedFrameOrigins=t.length>0?t:null}return n.initialized=!0,Fe()&&J(),y}function de(e){if(n.launchInFlight)return n.inFlightOpen;n.launchInFlight=!0;let t=Bt(e);return n.launchInFlight&&(n.inFlightOpen=t),t}async function Bt(e){try{let t=e||{};if(!n.backendBase)throw a("backend_base_missing","atkonoffice.open: backendBase not configured \u2014 call atkonoffice.config({ backendBase }) first");let o=t.pageUrl!=null?String(t.pageUrl):"",r=t.params||{},i=r.docId!=null?String(r.docId):"";if(!o&&!i)throw a("doc_id_missing","atkonoffice.open: docId is required \u2014 call open({ params: { docId, \u2026 } }) (page-less \u6A21\u5F0F\u4E0B\u65E0\u4E1A\u52A1\u9875\u53EF\u951A docId\uFF0C\u4E0B\u8F7D/\u4FDD\u5B58\u5747 docId \u7ED1\u5B9A)");let s={pageUrl:o,params:r,backendBase:n.backendBase},h=Dt(t.options);h&&(s.options=h),typeof t.pageApi=="string"&&t.pageApi&&(s.pageApi=t.pageApi),t.storage&&typeof t.storage=="object"&&Object.keys(t.storage).length>0&&(s.storage=t.storage);let c=await V(s,"atkonoffice.open: launch");if(!c||typeof c.launchUrl!="string"||!c.launchUrl)throw a("launch_response_invalid","atkonoffice.open: launch endpoint response missing launchUrl");let g=Lt(t);n.headers=G(g)?g:null;let w=Y(c);return n.replayOpen=()=>de(e),n.onPairDowngrade=w?We:null,typeof c.wsTicket=="string"&&c.wsTicket&&typeof c.wsUrl=="string"&&c.wsUrl&&(n.wsUrl=c.wsUrl,n.pairId=typeof c.pairId=="string"?c.pairId:"",n.nodeBase=Ut(c),ce(n.pairId,n.wsUrl,n.nodeBase),n.wsReconnectAttempt=0,n.wsStopped=!1,n.wsBackoffExhausted=!1,n.wsTicketInFlight=!1,w&&Se(c),X(c.wsTicket)),w||(j(c.launchUrl),x()),{launchUrl:c.launchUrl,downloadUrl:typeof c.downloadUrl=="string"?c.downloadUrl:"",pairId:n.pairId,wsUrl:n.wsUrl}}catch(t){throw x(),t}}function Lt(e){let t={},o=e.headers;if(Array.isArray(o)){for(let i of o)if(Array.isArray(i)&&i.length>=2)I(t,i[0],i[1]);else if(typeof i=="string"&&i.indexOf(":")!==-1){let s=i.indexOf(":");I(t,i.slice(0,s),i.slice(s+1).trim())}}else if(o&&typeof o=="object")for(let i of Object.keys(o))I(t,i,o[i]);let r=xe(e.cookie);return r&&I(t,"Cookie",r),e.storage&&typeof e.storage=="object"&&I(t,"X-Atkonoffice-Storage",JSON.stringify(e.storage)),t}function Ut(e){let t=e&&e.openParams?e.openParams.backend:null;return typeof t=="string"&&t?ne(t):""}function Dt(e){if(!e||typeof e!="object")return null;let t={};return typeof e.width=="number"&&(t.width=e.width),typeof e.height=="number"&&(t.height=e.height),typeof e.modal=="boolean"&&(t.modal=e.modal),Object.keys(t).length>0?t:null}var d={};var je="atkonoffice-doc-host",pe="__atkonofficeDocHostEvent",me=["documentSaved","documentOpened","documentBeforeSave","error","controlReady","compareDiff"],Ye={"doc.saved":"documentSaved","doc.opened":"documentOpened","doc.beforeSave":"documentBeforeSave","compare.diff":"compareDiff"},Ve="controlReady",Ke="toolbarClick",Je="readbackResult",Xe="messageBoxResult",f={eventHandlers:{},hintShown:!1,toolbarButtons:{},toolbarSeq:0,readbackPending:{},readbackSeq:0,messageBoxPending:{},messageBoxSeq:0};function qe(e,t,o){if(typeof e!="string")throw new TypeError("atkonoffice embed.addCustomToolButton: caption must be a string");if(typeof o!="function")throw new TypeError("atkonoffice embed.addCustomToolButton: onClick must be a function");if(typeof window>"u")return null;_();let r=typeof t=="number"&&isFinite(t)?Math.trunc(t):0,i="btn-"+ ++f.toolbarSeq;return f.toolbarButtons[i]=o,E("toolbarAdd",JSON.stringify({buttonId:i,caption:e,iconIndex:r}))?{remove:function(){delete f.toolbarButtons[i],E("toolbarRemove",JSON.stringify({buttonId:i}))}}:(delete f.toolbarButtons[i],et(),null)}function ze(e){if(typeof e!="boolean")throw new TypeError("atkonoffice embed.setCustomToolbarVisible: visible must be a boolean");return typeof window>"u"?d:(_(),E("toolbarSetVisible",JSON.stringify({visible:e})),d)}function $e(e){let t=e&&e.buttonId;if(typeof t!="string"||!t)return;let o=f.toolbarButtons[t];if(typeof o=="function")try{o()}catch(r){tt("addCustomToolButton onClick threw: "+(r&&r.message?r.message:r))}}function q(){if(typeof window>"u")return null;let e=window.atkonofficeCtrl=window.atkonofficeCtrl||{};return typeof e.save!="function"&&(e.save=function(t){let o=t&&typeof t=="object"?JSON.stringify(t):void 0;return typeof e._WebSave=="function"?e._WebSave(o):E("save",o)}),typeof e.exec!="function"&&(e.exec=function(t){return typeof t!="string"||!t?!1:E("executeJs",t)}),typeof e.setSavePath!="function"&&(e.setSavePath=function(t){return typeof t!="string"||!t?!1:E("setSavePath",t)}),e}function Qe(e){let t=q();return t&&typeof t.save=="function"?t.save(e):!1}function Ze(e){let t=q();return t&&typeof t.setSavePath=="function"?t.setSavePath(e):!1}function E(e,t){if(typeof window>"u")return!1;let o=window.__atkonofficeDocHost;return o&&typeof o.sendCommand=="function"?(t!=null?o.sendCommand(e,t):o.sendCommand(e),!0):!1}var Ht=15e3;function v(e,t){if(typeof window>"u")return Promise.resolve({ok:!1,error:"non-browser"});_();let o=++f.readbackSeq,r=JSON.stringify({rid:o,method:e,args:Array.isArray(t)?t:[]});return new Promise(i=>{let s=setTimeout(function(){he(o,{ok:!1,error:"timeout"})},Ht);s&&typeof s.unref=="function"&&s.unref(),f.readbackPending[o]={resolve:i,timer:s},E("readback",r)||he(o,{ok:!1,error:"shell-absent"})})}function he(e,t){let o=f.readbackPending[e];o&&(delete f.readbackPending[e],clearTimeout(o.timer),o.resolve(t))}function nt(e){let t=e&&e.rid;typeof t=="number"&&he(t,{ok:!!(e&&e.ok),value:e?e.value:void 0,error:e?e.error:void 0})}var Ft=6e5;function ot(e){if(typeof window>"u")return Promise.resolve({ok:!1,error:"non-browser"});_();let t=e&&typeof e=="object"?e:{},o=++f.messageBoxSeq,r=JSON.stringify({rid:o,type:t.type,title:t.title,text:t.text,buttons:t.buttons});return new Promise(i=>{let s=setTimeout(function(){ge(o,{ok:!1,error:"timeout"})},Ft);s&&typeof s.unref=="function"&&s.unref(),f.messageBoxPending[o]={resolve:i,timer:s},E("messageBox",r)||ge(o,{ok:!1,error:"shell-absent"})})}function ge(e,t){let o=f.messageBoxPending[e];o&&(delete f.messageBoxPending[e],clearTimeout(o.timer),o.resolve(t))}function rt(e){let t=e&&e.rid;typeof t=="number"&&ge(t,{ok:!!(e&&e.ok),button:e?e.button:void 0,error:e?e.error:void 0})}function _(){Mt(),q()}function st(e,t){if(typeof e!="string"||me.indexOf(e)===-1)throw new TypeError('atkonoffice embed.on: unknown event "'+e+'" (expected one of '+me.join(", ")+")");if(typeof t!="function")throw new TypeError("atkonoffice embed.on: handler must be a function");return _(),f.eventHandlers[e]||(f.eventHandlers[e]=[]),f.eventHandlers[e].push(t),d}function Mt(){typeof window>"u"||typeof window[pe]=="function"||(window[pe]=function(e,t){if(e===Ve){it("controlReady",t||{});return}if(e===Ke){$e(t||{});return}if(e===Je){nt(t||{});return}if(e===Xe){rt(t||{});return}let o=Ye[e];o&&it(o,t||{})})}function it(e,t){let o=f.eventHandlers[e];if(!o||o.length===0){if(e==="error")try{console.error("[atkonoffice embed] "+(t&&t.message?t.message:t))}catch{}return}for(let r of o.slice())try{r(t)}catch{}}function et(){if(!f.hintShown){f.hintShown=!0;try{console.info("[atkonoffice embed] <"+je+"> \u672A\u88AB\u5B9A\u4E49 \u2014\u2014 \u8BF7\u5728\u5DF2\u5B89\u88C5 atkonoffice \u5BA2\u6237\u7AEF\u7684\u58F3\u5185\u6253\u5F00\u672C\u7F16\u8F91\u9875;\u666E\u901A\u6D4F\u89C8\u5668\u91CC\u5B83\u662F\u7A7A\u76D2(\u4E0D\u5F71\u54CD\u9875\u9762\u5176\u4F59\u90E8\u5206)\u3002")}catch{}}}function tt(e){try{console.warn("[atkonoffice embed] "+e)}catch{}}function at(e){if(typeof e!="function")throw new TypeError("atkonoffice embed.onBeforeSave: fn must be a function");return _(),ft("onBeforeSave",e),d}function ct(e){if(typeof e!="function")throw new TypeError("atkonoffice embed.onBeforeClose: fn must be a function");return _(),ft("onBeforeClose",e),d}function ft(e,t){if(typeof window>"u")return!1;let o=window.__atkonofficeDocHost;return o&&typeof o[e]=="function"?(o[e](t),!0):!1}var Wt="AO_";function z(e){return!!(e&&e.ok&&Number(e.value)>0)}function lt(e,t){if(typeof e!="string"||!e)return Promise.resolve(!1);let o=typeof t=="string"?t:t==null?"":String(t),r={};return r[e]=o,v("Word_FillDataRegion",[JSON.stringify(r)]).then(z)}function ut(e,t){if(typeof e!="string"||!e)return Promise.resolve(!1);let o=typeof t=="string"?t:t==null?"":String(t);return v("Word_AddDataRegion",[e,o]).then(z)}function dt(e){return typeof e!="string"||!e?Promise.resolve(!1):v("Word_DeleteDataRegion",[e]).then(z)}function pt(e){return typeof e!="string"||!e?Promise.resolve(!1):v("Word_LocateDataRegion",[e]).then(z)}function mt(e){let t=typeof e=="string"?e:Wt;return v("BookmarksAsJson",[]).then(function(o){if(!o||!o.ok)return[];let r;try{r=JSON.parse(o.value)}catch{return[]}return Array.isArray(r)?r.filter(function(i){return typeof i=="string"&&(t===""||i.indexOf(t)===0)}):[]})}d.on=st;d.addCustomToolButton=qe;d.setCustomToolbarVisible=ze;d.save=Qe;d.setSavePath=Ze;d.showMessageBox=ot;d.onBeforeSave=at;d.onBeforeClose=ct;d.word={fillDataRegion:lt,addDataRegion:ut,deleteDataRegion:dt,locateDataRegion:pt,listDataRegions:mt};y.config=Ge;y.open=de;y.on=Me;y.session=d;var Gt=y,yo=Gt;export{Gt as atkonoffice,yo as default};
1
+ var y={};var n={backendBase:"",launchPath:"/atkonoffice/rpc/launch",wsTicketPath:"/atkonoffice/rpc/ws-ticket",fetchImpl:null,initialized:!1,ws:null,wsUrl:"",pairId:"",nodeBase:"",headers:null,eventHandlers:{},wsReconnectAttempt:0,wsReconnectTimer:null,wsTicketInFlight:!1,wsStopped:!1,wsBackoffExhausted:!1,channelLostAnnounced:!1,channelRestoreConfirmTimer:null,pairing:!1,launchTicket:"",openParams:null,fallbackUrl:"",pairingPrevTitle:"",pairingTitleSaved:!1,pairingRecoverTimer:null,pairingTimeoutTimer:null,pairTimeoutMs:5e3,pairRecoverMs:1e3,titleRelayInstalled:!1,trustedFrameOrigins:null,onPairDowngrade:null,replayOpen:null,launchInFlight:!1,inFlightOpen:null};function x(){n.launchInFlight=!1,n.inFlightOpen=null}var U="atkonoffice.ws.session",Q=12,Z=3e5,Te=1e3,A="channelLost",B="channelRestored",D=["documentSaved","documentOpened","documentBeforeSave","documentEmbedFailed","shellClosed",A,B,"error"],ee="shell.closed",P={"doc.saved":"documentSaved","doc.opened":"documentOpened","doc.beforeSave":"documentBeforeSave",[ee]:"shellClosed"},R="atkonoffice-launch=",H="\u2007",F="pair.ready",Ee="launch.open",be="doc.embedFailed",M="__atkonofficeTitle",te="atkonoffice-install-guide";function ne(e){return e&&e.endsWith("/")?e.slice(0,-1):e}function Re(e,t){if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function W(e,t,o){let r=e.indexOf("?")===-1?"?":"&";return e+r+t+"="+o}function G(e){return!!e&&Object.keys(e).length>0}function b(e){return e&&e.message?e.message:String(e)}function I(e,t,o){if(t==null)return;let r=String(t).trim();r&&(e[r]=o==null?"":String(o))}function xe(e){return e?typeof e=="string"?e:typeof e=="object"?Object.keys(e).map(t=>t+"="+String(e[t])).join("; "):"":""}function ke(e){let t;if(typeof TextEncoder<"u"){let o=new TextEncoder().encode(e),r="";for(let i=0;i<o.length;i++)r+=String.fromCharCode(o[i]);t=r}else t=unescape(encodeURIComponent(e));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(){try{return typeof document<"u"&&typeof document.title=="string"?document.title:""}catch{return""}}function oe(){if(typeof window>"u")return!1;try{return window.top!==window.self}catch{return!0}}function j(e){try{let t=document.createElement("iframe");t.style.display="none",t.src=e,document.body.appendChild(t),setTimeout(()=>{try{document.body.removeChild(t)}catch{}},1e3)}catch{window.location.href=e}}function Y(e){return!!(typeof e.launchTicket=="string"&&e.launchTicket&&typeof e.wsUrl=="string"&&e.wsUrl&&typeof e.wsTicket=="string"&&e.wsTicket&&typeof document<"u"&&typeof WebSocket<"u")}var l={CONFIG:"config",LAUNCH:"launch",CHANNEL:"channel"},re={backend_base_missing:l.CONFIG,doc_id_missing:l.CONFIG,fetch_unavailable:l.CONFIG,ws_unsupported:l.CONFIG,ws_ticket_backend_missing:l.CONFIG,ws_ticket_node_mismatch:l.CONFIG,launch_request_failed:l.LAUNCH,launch_http_error:l.LAUNCH,launch_response_not_json:l.LAUNCH,launch_response_invalid:l.LAUNCH,launch_open_frame_send_failed:l.LAUNCH,ws_url_missing:l.CHANNEL,ws_ticket_missing:l.CHANNEL,ws_connect_failed:l.CHANNEL,ws_error:l.CHANNEL,headers_frame_send_failed:l.CHANNEL,ws_no_pair_to_resume:l.CHANNEL,ws_backoff_exhausted:l.CHANNEL,ws_gave_up:l.CHANNEL,ws_ticket_http_error:l.CHANNEL,ws_ticket_response_invalid:l.CHANNEL,ws_ticket_refresh_failed:l.CHANNEL};function a(e,t){let o=new Error(t);return o.code=e,o.category=re[e],o}function ie(){return typeof n.fetchImpl=="function"?n.fetchImpl:typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):null}function ht(){let e=ie();if(!e)throw a("fetch_unavailable","atkonoffice: no fetch available \u2014 pass fetchImpl via config in non-browser hosts");return e}async function V(e,t){let o;try{o=await ht()(n.backendBase+n.launchPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(r){throw r&&re[r.code]?r:a("launch_request_failed",t+" request failed \u2014 "+b(r))}if(!o.ok)throw a("launch_http_error",t+" endpoint returned HTTP "+o.status);try{return await o.json()}catch(r){throw a("launch_response_not_json",t+" response was not JSON \u2014 "+b(r))}}var T={PERM:"PERM",SLOW:"SLOW",RETRY:"RETRY"},se=":",gt=[[T.PERM+se,T.PERM],[T.SLOW+se,T.SLOW],[T.RETRY+se,T.RETRY]];function Oe(e){if(typeof e!="string"||!e)return T.RETRY;for(let t of gt)if(e.indexOf(t[0])===0)return t[1];return T.RETRY}function Se(e){n.launchTicket=e.launchTicket,n.openParams=e.openParams&&typeof e.openParams=="object"?e.openParams:{},n.fallbackUrl=e.launchUrl,n.pairing||(n.pairingTitleSaved=!1),n.pairing=!0,ae(),yt()}function Ce(){if(!(!n.pairing||typeof document>"u")){if(!n.pairingTitleSaved){let e=k();e.indexOf(R)<0&&(n.pairingPrevTitle=e,n.pairingTitleSaved=!0)}Pe(),_t()}}function Pe(){O(K(n.wsUrl,n.pairId,n.launchTicket))}function K(e,t,o){let r=ke(JSON.stringify({wsUrl:e,pairId:t,launchTicket:o}));return H+R+r}function O(e){try{typeof document<"u"&&(document.title=e)}catch{}if(oe())try{let t={};t[M]=e,window.top.postMessage(t,"*")}catch{}}function ae(){n.titleRelayInstalled||typeof window>"u"||typeof window.addEventListener!="function"||oe()||(n.titleRelayInstalled=!0,window.addEventListener("message",e=>{if(!wt(e&&e.origin))return;let t=e&&e.data;if(t&&typeof t=="object"&&typeof t[M]=="string")try{document.title=t[M]}catch{}}))}function wt(e){let t=n.trustedFrameOrigins;return!t||t.length===0?!0:typeof e=="string"&&t.indexOf(e)!==-1}function _t(){n.pairingRecoverTimer||typeof setInterval>"u"||(n.pairingRecoverTimer=setInterval(()=>{n.pairing&&k().indexOf(R)<0&&Pe()},n.pairRecoverMs))}function yt(){n.pairingTimeoutTimer||typeof setTimeout>"u"||(n.pairingTimeoutTimer=setTimeout(()=>{n.pairingTimeoutTimer=null,Ne(!0)},n.pairTimeoutMs))}function Ie(){if(!n.pairing)return;let e=n.ws;Ne(!1),x(),e&&Tt(e)}function Tt(e){let t={v:1,type:"event",op:Ee,ts:Math.floor(Date.now()/1e3),payload:{pair_id:n.pairId,openParams:n.openParams||{}}};try{e.send(JSON.stringify(t))}catch(o){u("error",a("launch_open_frame_send_failed","atkonoffice: failed to send launch.open frame \u2014 "+b(o)))}}function Ne(e){n.pairingRecoverTimer&&(clearInterval(n.pairingRecoverTimer),n.pairingRecoverTimer=null),n.pairingTimeoutTimer&&(clearTimeout(n.pairingTimeoutTimer),n.pairingTimeoutTimer=null);let t=n.pairing;n.pairing=!1,n.pairingTitleSaved&&(O(n.pairingPrevTitle),n.pairingTitleSaved=!1),e&&t&&(j(n.fallbackUrl),typeof n.onPairDowngrade=="function"&&n.onPairDowngrade())}var Et="documentEmbedFailed";function ve(e){u(Et,e||{})}function ce(e,t,o){if(!(!e||typeof sessionStorage>"u"))try{sessionStorage.setItem(U,JSON.stringify({pairId:e,wsUrl:t,nodeBase:o||""}))}catch{}}function Ae(){if(n.pairId)return{pairId:n.pairId,wsUrl:n.wsUrl,nodeBase:n.nodeBase};if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(U);return e?JSON.parse(e):null}catch{return null}}function bt(){n.pairId="",n.wsUrl="",n.nodeBase=""}function Be(){if(!(typeof sessionStorage>"u"))try{sessionStorage.removeItem(U)}catch{}}function Le(){bt(),Be()}function J(){if(n.ws||n.wsReconnectTimer||n.wsTicketInFlight||n.wsStopped||!n.backendBase)return;let e=Ae();!e||!e.pairId||(n.pairId=e.pairId,n.wsUrl=e.wsUrl||n.wsUrl,n.nodeBase=e.nodeBase||n.nodeBase,n.wsReconnectAttempt=0,De(e.pairId,t=>X(t)))}function X(e){if(typeof WebSocket>"u"){u("error",a("ws_unsupported","atkonoffice: WebSocket unavailable in this host \u2014 document events disabled"));return}if(!n.wsUrl){u("error",a("ws_url_missing","atkonoffice: no wsUrl \u2014 cannot open the document-event channel"));return}if(!e){u("error",a("ws_ticket_missing","atkonoffice: missing ws_ticket \u2014 cannot subscribe to document events"));return}le();let t=W(n.wsUrl,"ticket",encodeURIComponent(e)),o;try{o=new WebSocket(t)}catch(r){u("error",a("ws_connect_failed","atkonoffice: WS connect failed \u2014 "+b(r))),N();return}n.ws=o,o.onopen=()=>{n.wsBackoffExhausted&&ce(n.pairId,n.wsUrl,n.nodeBase),n.wsReconnectAttempt=0,n.wsStopped=!1,n.wsBackoffExhausted=!1,Rt(o),Ot(o),n.pairing&&Ce()},o.onmessage=r=>{St(r&&r.data)},o.onerror=()=>{u("error",a("ws_error","atkonoffice: WS error on the document-event channel"))},o.onclose=r=>{if(n.ws===o&&(n.ws=null),fe(),Oe(r&&r.reason)===T.PERM){xt("server closed it permanently; reopen the document from the page to start a new session");return}N()}}function Ue(e){n.channelLostAnnounced||(n.channelLostAnnounced=!0,u(A,{reason:e}))}function Rt(e){fe(),n.channelLostAnnounced&&(n.channelRestoreConfirmTimer=setTimeout(()=>{n.channelRestoreConfirmTimer=null,!(n.ws!==e||!n.channelLostAnnounced)&&(n.channelLostAnnounced=!1,u(B,{}))},Te))}function fe(){n.channelRestoreConfirmTimer&&(clearTimeout(n.channelRestoreConfirmTimer),n.channelRestoreConfirmTimer=null)}function xt(e){n.wsStopped=!0,n.wsBackoffExhausted=!1,le(),Le();let t=a("ws_gave_up","atkonoffice: document-event channel lost \u2014 "+e);t.terminal=!0,u("error",t),Ue("rejected")}function kt(e){n.wsBackoffExhausted=!0,Be();let t=a("ws_backoff_exhausted","atkonoffice: document-event channel still unreachable "+e+" \u2014 left fast reconnect, now probing every "+Math.round(Z/1e3)+"s until it comes back");t.terminal=!1,u("error",t),Ue("unreachable")}function le(){n.wsReconnectTimer&&(clearTimeout(n.wsReconnectTimer),n.wsReconnectTimer=null),fe();let e=n.ws;if(n.ws=null,e){e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{e.close(1e3,"client_close")}catch{}}}function Ot(e){if(!G(n.headers))return;let t={v:1,type:"event",op:"client.headers",ts:Math.floor(Date.now()/1e3),payload:{headers:n.headers}};try{e.send(JSON.stringify(t))}catch(o){u("error",a("headers_frame_send_failed","atkonoffice: failed to send headers frame \u2014 "+b(o)))}}function St(e){if(typeof e!="string")return;let t;try{t=JSON.parse(e)}catch{return}if(!t||t.type!=="event")return;if(t.op===F){Ie();return}if(t.op===be){ve(t.payload||{});return}let o=P[t.op];o&&u(o,t.payload||{}),t.op===ee&&(n.wsBackoffExhausted=!1,Le(),le())}function N(){if(n.wsReconnectTimer||n.wsStopped)return;let e=Ae();if(!e||!e.pairId){u("error",a("ws_no_pair_to_resume","atkonoffice: document-event channel dropped and no pair to resume"));return}let t=n.wsReconnectAttempt>=Q,o;if(t)o=Z;else{let r=n.wsReconnectAttempt+1;n.wsReconnectAttempt=r,o=Math.min(3e4,500*Math.pow(2,r-1))}n.wsReconnectTimer=setTimeout(()=>{n.wsReconnectTimer=null,n.nodeBase=e.nodeBase||n.nodeBase,De(e.pairId,r=>{n.pairId=e.pairId,n.wsUrl=e.wsUrl||n.wsUrl,X(r)})},o),t&&!n.wsBackoffExhausted&&kt("after "+Q+" consecutive fast reconnect attempts")}async function De(e,t){let o=ie();if(!o||!n.backendBase){u("error",a("ws_ticket_backend_missing","atkonoffice: cannot refresh ws_ticket \u2014 backend not configured")),N();return}n.wsTicketInFlight=!0;let r=Re(n.nodeBase,n.backendBase)?n.nodeBase:n.backendBase;try{let i=await o(r+n.wsTicketPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pairId:e,backendBase:r})});if(!i.ok){u("error",a("ws_ticket_http_error","atkonoffice: ws_ticket refresh returned HTTP "+i.status)),N();return}let s=await i.json();if(!s||typeof s.wsTicket!="string"||!s.wsTicket){u("error",a("ws_ticket_response_invalid","atkonoffice: ws_ticket refresh response missing wsTicket")),N();return}typeof s.wsUrl=="string"&&s.wsUrl&&(n.nodeBase&&n.wsUrl&&s.wsUrl!==n.wsUrl?u("error",a("ws_ticket_node_mismatch","atkonoffice: ws_ticket refresh was served by a different backend instance than this session \u2014 expected "+n.wsUrl+", got "+s.wsUrl+" (multi-instance: check the load balancer routes this session node prefix to that instance)")):n.wsUrl=s.wsUrl),t(s.wsTicket)}catch(i){u("error",a("ws_ticket_refresh_failed","atkonoffice: ws_ticket refresh failed \u2014 "+b(i))),N()}finally{n.wsTicketInFlight=!1}}function Ct(e){let t=n.eventHandlers[e];return!!t&&t.length>0}function Pt(e){for(let t in P)if(P.hasOwnProperty(t)&&P[t]===e)return!0;return!1}function He(e){return Pt(e)||e===A||e===B}function Fe(){return D.some(e=>He(e)&&Ct(e))}function u(e,t){let o=n.eventHandlers[e];if(!o||o.length===0){if(e==="error")try{console.error("[atkonoffice] "+(t&&t.message?t.message:t))}catch{}return}for(let r of o.slice())try{r(t)}catch{}}function Me(e,t){if(typeof e!="string"||D.indexOf(e)===-1)throw new TypeError('atkonoffice.on: unknown event "'+e+'" (expected one of '+D.join(", ")+")");if(typeof t!="function")throw new TypeError("atkonoffice.on: handler must be a function");return n.eventHandlers[e]||(n.eventHandlers[e]=[]),n.eventHandlers[e].push(t),He(e)&&J(),y}function We(){Nt(n.pairTimeoutMs).then(e=>{x(),e.installed||At(e.clientDownloadUrl)})}function It(e){let t=e.indexOf(R);if(t<0)return null;let o=t;for(;o>0&&e.charAt(o-1)===H;)o-=1;return e.slice(0,o)}function Nt(e){return new Promise(t=>{let o=!1,r=null,i=null,s=null,h=!1,c="",g="",w=()=>{if(i&&(clearTimeout(i),i=null),s&&(clearInterval(s),s=null),h)O(c),h=!1;else{let p=It(k());p!==null&&O(p)}if(r){r.onopen=r.onmessage=r.onerror=r.onclose=null;try{r.close(1e3,"probe_done")}catch{}r=null}},m=p=>{o||(o=!0,w(),t({installed:p,clientDownloadUrl:g}))};i=setTimeout(()=>m(!1),e),vt().then(p=>{if(p&&typeof p.clientDownloadUrl=="string"&&(g=p.clientDownloadUrl),o||!Y(p)){m(!1);return}let $=p.wsUrl,we=typeof p.pairId=="string"?p.pairId:"",_e=p.launchTicket;ae();let S;try{S=new WebSocket(W($,"ticket",encodeURIComponent(p.wsTicket)))}catch{m(!1);return}r=S,S.onopen=()=>{let C=k();C.indexOf(R)<0&&(c=C,h=!0),O(K($,we,_e)),s=setInterval(()=>{!o&&k().indexOf(R)<0&&O(K($,we,_e))},n.pairRecoverMs)},S.onmessage=C=>{let ye=C&&C.data;if(typeof ye!="string")return;let L;try{L=JSON.parse(ye)}catch{return}L&&L.type==="event"&&L.op===F&&m(!0)},S.onerror=()=>{},S.onclose=()=>{}}).catch(()=>{m(!1)})})}async function vt(){return V({docId:"",pageUrl:"",user:"",backendBase:n.backendBase},"atkonoffice: launch-probe")}function At(e){if(typeof document>"u"||!document.body||typeof document.createElement!="function")return null;ue();let t=document.createElement("div");t.setAttribute("data-atkonoffice-guide",te),t.style.cssText="position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.45);font:14px/1.6 system-ui,-apple-system,sans-serif;";let o=document.createElement("div");o.style.cssText="background:#fff;color:#222;max-width:420px;width:86%;border-radius:8px;padding:24px;box-shadow:0 8px 32px rgba(0,0,0,0.25);box-sizing:border-box;";let r=document.createElement("h2");r.textContent="\u9700\u8981\u5B89\u88C5\u7F16\u8F91\u5668\u5BA2\u6237\u7AEF",r.style.cssText="margin:0 0 12px;font-size:18px;";let i=document.createElement("p");i.style.cssText="margin:0 0 20px;color:#444;",i.textContent=e?"\u672A\u68C0\u6D4B\u5230\u672C\u673A\u5DF2\u5B89\u88C5\u7F16\u8F91\u5668\u5BA2\u6237\u7AEF\u3002\u8BF7\u5148\u4E0B\u8F7D\u5E76\u5B89\u88C5,\u5B89\u88C5\u5B8C\u6210\u540E\u70B9\u300C\u6211\u5DF2\u5B89\u88C5,\u91CD\u8BD5\u300D\u3002":"\u672A\u68C0\u6D4B\u5230\u672C\u673A\u5DF2\u5B89\u88C5\u7F16\u8F91\u5668\u5BA2\u6237\u7AEF,\u4E14\u672A\u914D\u7F6E\u4E0B\u8F7D\u5730\u5740\u3002\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u83B7\u53D6\u5B89\u88C5\u5305,\u5B89\u88C5\u5B8C\u6210\u540E\u70B9\u300C\u6211\u5DF2\u5B89\u88C5,\u91CD\u8BD5\u300D\u3002";let s=document.createElement("div");s.style.cssText="display:flex;gap:10px;justify-content:flex-end;flex-wrap:wrap;";let h="font:inherit;padding:8px 16px;border-radius:6px;cursor:pointer;border:1px solid #ccc;background:#f6f6f6;color:#222;",c="font:inherit;padding:8px 16px;border-radius:6px;cursor:pointer;border:1px solid #1a6dd6;background:#1a6dd6;color:#fff;text-decoration:none;display:inline-block;";if(e){let m=document.createElement("a");m.textContent="\u4E0B\u8F7D\u5BA2\u6237\u7AEF",m.href=e,m.target="_blank",m.rel="noopener noreferrer",m.style.cssText=c,s.appendChild(m)}let g=document.createElement("button");g.type="button",g.textContent="\u6211\u5DF2\u5B89\u88C5,\u91CD\u8BD5",g.style.cssText=h,g.addEventListener("click",()=>{ue();try{typeof n.replayOpen=="function"&&n.replayOpen()}catch{}});let w=document.createElement("button");return w.type="button",w.textContent="\u5173\u95ED",w.style.cssText=h,w.addEventListener("click",()=>ue()),s.appendChild(g),s.appendChild(w),o.appendChild(r),o.appendChild(i),o.appendChild(s),t.appendChild(o),document.body.appendChild(t),t}function ue(){if(!(typeof document>"u"||typeof document.querySelector!="function"))try{let e=document.querySelector('[data-atkonoffice-guide="'+te+'"]');e&&typeof e.remove=="function"?e.remove():e&&e.parentNode&&typeof e.parentNode.removeChild=="function"&&e.parentNode.removeChild(e)}catch{}}function Ge(e){if(!e||typeof e!="object")throw new TypeError("atkonoffice.config requires an options object");if(typeof e.backendBase=="string"&&(n.backendBase=ne(e.backendBase)),typeof e.launchPath=="string"&&e.launchPath&&(n.launchPath=e.launchPath),typeof e.wsTicketPath=="string"&&e.wsTicketPath&&(n.wsTicketPath=e.wsTicketPath),typeof e.fetchImpl=="function"&&(n.fetchImpl=e.fetchImpl),Array.isArray(e.trustedFrameOrigins)){let t=e.trustedFrameOrigins.filter(o=>typeof o=="string"&&o);n.trustedFrameOrigins=t.length>0?t:null}return n.initialized=!0,Fe()&&J(),y}function de(e){if(n.launchInFlight)return n.inFlightOpen;n.launchInFlight=!0;let t=Bt(e);return n.launchInFlight&&(n.inFlightOpen=t),t}async function Bt(e){try{let t=e||{};if(!n.backendBase)throw a("backend_base_missing","atkonoffice.open: backendBase not configured \u2014 call atkonoffice.config({ backendBase }) first");let o=t.pageUrl!=null?String(t.pageUrl):"",r=t.params||{},i=r.docId!=null?String(r.docId):"";if(!o&&!i)throw a("doc_id_missing","atkonoffice.open: docId is required \u2014 call open({ params: { docId, \u2026 } }) (page-less \u6A21\u5F0F\u4E0B\u65E0\u4E1A\u52A1\u9875\u53EF\u951A docId\uFF0C\u4E0B\u8F7D/\u4FDD\u5B58\u5747 docId \u7ED1\u5B9A)");let s={pageUrl:o,params:r,backendBase:n.backendBase},h=Dt(t.options);h&&(s.options=h),typeof t.pageApi=="string"&&t.pageApi&&(s.pageApi=t.pageApi),t.storage&&typeof t.storage=="object"&&Object.keys(t.storage).length>0&&(s.storage=t.storage);let c=await V(s,"atkonoffice.open: launch");if(!c||typeof c.launchUrl!="string"||!c.launchUrl)throw a("launch_response_invalid","atkonoffice.open: launch endpoint response missing launchUrl");let g=Lt(t);n.headers=G(g)?g:null;let w=Y(c);return n.replayOpen=()=>de(e),n.onPairDowngrade=w?We:null,typeof c.wsTicket=="string"&&c.wsTicket&&typeof c.wsUrl=="string"&&c.wsUrl&&(n.wsUrl=c.wsUrl,n.pairId=typeof c.pairId=="string"?c.pairId:"",n.nodeBase=Ut(c),ce(n.pairId,n.wsUrl,n.nodeBase),n.wsReconnectAttempt=0,n.wsStopped=!1,n.wsBackoffExhausted=!1,n.wsTicketInFlight=!1,w&&Se(c),X(c.wsTicket)),w||(j(c.launchUrl),x()),{launchUrl:c.launchUrl,downloadUrl:typeof c.downloadUrl=="string"?c.downloadUrl:"",pairId:n.pairId,wsUrl:n.wsUrl}}catch(t){throw x(),t}}function Lt(e){let t={},o=e.headers;if(Array.isArray(o)){for(let i of o)if(Array.isArray(i)&&i.length>=2)I(t,i[0],i[1]);else if(typeof i=="string"&&i.indexOf(":")!==-1){let s=i.indexOf(":");I(t,i.slice(0,s),i.slice(s+1).trim())}}else if(o&&typeof o=="object")for(let i of Object.keys(o))I(t,i,o[i]);let r=xe(e.cookie);return r&&I(t,"Cookie",r),e.storage&&typeof e.storage=="object"&&I(t,"X-Atkonoffice-Storage",JSON.stringify(e.storage)),t}function Ut(e){let t=e&&e.openParams?e.openParams.backend:null;return typeof t=="string"&&t?ne(t):""}function Dt(e){if(!e||typeof e!="object")return null;let t={};return typeof e.width=="number"&&(t.width=e.width),typeof e.height=="number"&&(t.height=e.height),typeof e.modal=="boolean"&&(t.modal=e.modal),Object.keys(t).length>0?t:null}var d={};var je="atkonoffice-doc-host",pe="__atkonofficeDocHostEvent",me=["documentSaved","documentOpened","documentBeforeSave","error","controlReady","compareDiff"],Ye={"doc.saved":"documentSaved","doc.opened":"documentOpened","doc.beforeSave":"documentBeforeSave","compare.diff":"compareDiff"},Ve="controlReady",Ke="toolbarClick",Je="readbackResult",Xe="messageBoxResult",f={eventHandlers:{},hintShown:!1,toolbarButtons:{},toolbarSeq:0,readbackPending:{},readbackSeq:0,messageBoxPending:{},messageBoxSeq:0};function qe(e,t,o){if(typeof e!="string")throw new TypeError("atkonoffice embed.addCustomToolButton: caption must be a string");if(typeof o!="function")throw new TypeError("atkonoffice embed.addCustomToolButton: onClick must be a function");if(typeof window>"u")return null;_();let r=typeof t=="number"&&isFinite(t)?Math.trunc(t):0,i="btn-"+ ++f.toolbarSeq;return f.toolbarButtons[i]=o,E("toolbarAdd",JSON.stringify({buttonId:i,caption:e,iconIndex:r}))?{remove:function(){delete f.toolbarButtons[i],E("toolbarRemove",JSON.stringify({buttonId:i}))}}:(delete f.toolbarButtons[i],et(),null)}function ze(e){if(typeof e!="boolean")throw new TypeError("atkonoffice embed.setCustomToolbarVisible: visible must be a boolean");return typeof window>"u"?d:(_(),E("toolbarSetVisible",JSON.stringify({visible:e})),d)}function $e(e){let t=e&&e.buttonId;if(typeof t!="string"||!t)return;let o=f.toolbarButtons[t];if(typeof o=="function")try{o()}catch(r){tt("addCustomToolButton onClick threw: "+(r&&r.message?r.message:r))}}function q(){if(typeof window>"u")return null;let e=window.atkonofficeCtrl=window.atkonofficeCtrl||{};return typeof e.save!="function"&&(e.save=function(t){let o=t&&typeof t=="object"?JSON.stringify(t):void 0;return typeof e._WebSave=="function"?e._WebSave(o):E("save",o)}),typeof e.exec!="function"&&(e.exec=function(t){return typeof t!="string"||!t?!1:E("executeJs",t)}),typeof e.setSavePath!="function"&&(e.setSavePath=function(t){return typeof t!="string"||!t?!1:E("setSavePath",t)}),e}function Qe(e){let t=q();return t&&typeof t.save=="function"?t.save(e):!1}function Ze(e){let t=q();return t&&typeof t.setSavePath=="function"?t.setSavePath(e):!1}function E(e,t){if(typeof window>"u")return!1;let o=window.__atkonofficeDocHost;return o&&typeof o.sendCommand=="function"?(t!=null?o.sendCommand(e,t):o.sendCommand(e),!0):!1}var Ht=15e3;function v(e,t){if(typeof window>"u")return Promise.resolve({ok:!1,error:"non-browser"});_();let o=++f.readbackSeq,r=JSON.stringify({rid:o,method:e,args:Array.isArray(t)?t:[]});return new Promise(i=>{let s=setTimeout(function(){he(o,{ok:!1,error:"timeout"})},Ht);s&&typeof s.unref=="function"&&s.unref(),f.readbackPending[o]={resolve:i,timer:s},E("readback",r)||he(o,{ok:!1,error:"shell-absent"})})}function he(e,t){let o=f.readbackPending[e];o&&(delete f.readbackPending[e],clearTimeout(o.timer),o.resolve(t))}function nt(e){let t=e&&e.rid;typeof t=="number"&&he(t,{ok:!!(e&&e.ok),value:e?e.value:void 0,error:e?e.error:void 0})}var Ft=6e5;function ot(e){if(typeof window>"u")return Promise.resolve({ok:!1,error:"non-browser"});_();let t=e&&typeof e=="object"?e:{},o=++f.messageBoxSeq,r=JSON.stringify({rid:o,type:t.type,title:t.title,text:t.text,buttons:t.buttons});return new Promise(i=>{let s=setTimeout(function(){ge(o,{ok:!1,error:"timeout"})},Ft);s&&typeof s.unref=="function"&&s.unref(),f.messageBoxPending[o]={resolve:i,timer:s},E("messageBox",r)||ge(o,{ok:!1,error:"shell-absent"})})}function ge(e,t){let o=f.messageBoxPending[e];o&&(delete f.messageBoxPending[e],clearTimeout(o.timer),o.resolve(t))}function rt(e){let t=e&&e.rid;typeof t=="number"&&ge(t,{ok:!!(e&&e.ok),button:e?e.button:void 0,error:e?e.error:void 0})}function _(){Mt(),q()}function st(e,t){if(typeof e!="string"||me.indexOf(e)===-1)throw new TypeError('atkonoffice embed.on: unknown event "'+e+'" (expected one of '+me.join(", ")+")");if(typeof t!="function")throw new TypeError("atkonoffice embed.on: handler must be a function");return _(),f.eventHandlers[e]||(f.eventHandlers[e]=[]),f.eventHandlers[e].push(t),d}function Mt(){typeof window>"u"||typeof window[pe]=="function"||(window[pe]=function(e,t){if(e===Ve){it("controlReady",t||{});return}if(e===Ke){$e(t||{});return}if(e===Je){nt(t||{});return}if(e===Xe){rt(t||{});return}let o=Ye[e];o&&it(o,t||{})})}function it(e,t){let o=f.eventHandlers[e];if(!o||o.length===0){if(e==="error")try{console.error("[atkonoffice embed] "+(t&&t.message?t.message:t))}catch{}return}for(let r of o.slice())try{r(t)}catch{}}function et(){if(!f.hintShown){f.hintShown=!0;try{console.info("[atkonoffice embed] <"+je+"> \u672A\u88AB\u5B9A\u4E49 \u2014\u2014 \u8BF7\u5728\u5DF2\u5B89\u88C5 atkonoffice \u5BA2\u6237\u7AEF\u7684\u58F3\u5185\u6253\u5F00\u672C\u7F16\u8F91\u9875;\u666E\u901A\u6D4F\u89C8\u5668\u91CC\u5B83\u662F\u7A7A\u76D2(\u4E0D\u5F71\u54CD\u9875\u9762\u5176\u4F59\u90E8\u5206)\u3002")}catch{}}}function tt(e){try{console.warn("[atkonoffice embed] "+e)}catch{}}function at(e){if(typeof e!="function")throw new TypeError("atkonoffice embed.onBeforeSave: fn must be a function");return _(),ft("onBeforeSave",e),d}function ct(e){if(typeof e!="function")throw new TypeError("atkonoffice embed.onBeforeClose: fn must be a function");return _(),ft("onBeforeClose",e),d}function ft(e,t){if(typeof window>"u")return!1;let o=window.__atkonofficeDocHost;return o&&typeof o[e]=="function"?(o[e](t),!0):!1}var Wt="AO_";function z(e){return!!(e&&e.ok&&Number(e.value)>0)}function lt(e,t){if(typeof e!="string"||!e)return Promise.resolve(!1);let o=typeof t=="string"?t:t==null?"":String(t),r={};return r[e]=o,v("Word_FillDataRegion",[JSON.stringify(r)]).then(z)}function ut(e,t){if(typeof e!="string"||!e)return Promise.resolve(!1);let o=typeof t=="string"?t:t==null?"":String(t);return v("Word_AddDataRegion",[e,o]).then(z)}function dt(e){return typeof e!="string"||!e?Promise.resolve(!1):v("Word_DeleteDataRegion",[e]).then(z)}function pt(e){return typeof e!="string"||!e?Promise.resolve(!1):v("Word_LocateDataRegion",[e]).then(z)}function mt(e){let t=typeof e=="string"?e:Wt;return v("BookmarksAsJson",[]).then(function(o){if(!o||!o.ok)return[];let r;try{r=JSON.parse(o.value)}catch{return[]}return Array.isArray(r)?r.filter(function(i){return typeof i=="string"&&(t===""||i.indexOf(t)===0)}):[]})}d.on=st;d.addCustomToolButton=qe;d.setCustomToolbarVisible=ze;d.save=Qe;d.setSavePath=Ze;d.showMessageBox=ot;d.onBeforeSave=at;d.onBeforeClose=ct;d.word={fillDataRegion:lt,addDataRegion:ut,deleteDataRegion:dt,locateDataRegion:pt,listDataRegions:mt};y.config=Ge;y.open=de;y.on=Me;y.session=d;var Gt=y,yo=Gt;export{Gt as atkonoffice,yo as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atkonoffice/sdk",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "Browser-side SDK for the atkonoffice editor shell",
5
5
  "homepage": "https://atkon.yunhuichongming.cn",
6
6
  "type": "module",