@atkonoffice/sdk 1.9.0 → 1.11.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.
@@ -152,6 +152,13 @@ export interface AtkonofficeSessionEvent {
152
152
  }
153
153
 
154
154
 
155
+ export interface AtkonofficeSessionFailureEvent {
156
+
157
+ reason: string
158
+ [key: string]: unknown
159
+ }
160
+
161
+
155
162
  export interface AtkonofficeToolButtonHandle {
156
163
 
157
164
  remove(): void
@@ -216,6 +223,39 @@ export interface AtkonofficeSessionWord {
216
223
  locateDataRegion(name: string): Promise<boolean>
217
224
 
218
225
  listDataRegions(prefix?: string): Promise<string[]>
226
+
227
+ setDataRegionLock(name: string, lock: AtkonofficeDataRegionLock): Promise<boolean>
228
+
229
+ receipt: AtkonofficeSessionWordReceipt
230
+ }
231
+
232
+
233
+ export interface AtkonofficeDataRegionLock {
234
+
235
+ contents?: boolean
236
+
237
+ control?: boolean
238
+ }
239
+
240
+
241
+ export type AtkonofficeDataRegionReceipt<T> =
242
+ | { ok: true; value: T; error?: undefined }
243
+ | { ok: false; value?: undefined; error: string }
244
+
245
+
246
+ export interface AtkonofficeSessionWordReceipt {
247
+
248
+ fillDataRegion(name: string, value: string): Promise<AtkonofficeDataRegionReceipt<number>>
249
+
250
+ addDataRegion(name: string, caption?: string): Promise<AtkonofficeDataRegionReceipt<number>>
251
+
252
+ deleteDataRegion(name: string): Promise<AtkonofficeDataRegionReceipt<number>>
253
+
254
+ locateDataRegion(name: string): Promise<AtkonofficeDataRegionReceipt<number>>
255
+
256
+ listDataRegions(prefix?: string): Promise<AtkonofficeDataRegionReceipt<string[]>>
257
+
258
+ setDataRegionLock(name: string, lock: AtkonofficeDataRegionLock): Promise<AtkonofficeDataRegionReceipt<number>>
219
259
  }
220
260
 
221
261
 
@@ -258,6 +298,10 @@ export interface AtkonofficeSession {
258
298
 
259
299
  on(event: 'controlReady', handler: (payload: AtkonofficeSessionEvent) => void): AtkonofficeSession
260
300
 
301
+ on(event: 'documentReady', handler: (payload: AtkonofficeSessionEvent) => void): AtkonofficeSession
302
+
303
+ on(event: 'documentFailed', handler: (payload: AtkonofficeSessionFailureEvent) => void): AtkonofficeSession
304
+
261
305
  on(event: 'compareDiff', handler: (diff: AtkonofficeCompareDiff) => void): AtkonofficeSession
262
306
 
263
307
  on(event: 'error', handler: (err: Error) => void): AtkonofficeSession
@@ -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 w={};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 k(){n.launchInFlight=!1,n.inFlightOpen=null}var H="atkonoffice.ws.session",ee=12,te=3e5,Ne=1e3,B="channelLost",L="channelRestored",F=["documentSaved","documentOpened","documentBeforeSave","documentEmbedFailed","shellClosed",B,L,"error"],ne="shell.closed",N={"doc.saved":"documentSaved","doc.opened":"documentOpened","doc.beforeSave":"documentBeforeSave",[ne]:"shellClosed"},b="atkonoffice-launch=",M="\u2007",W="pair.ready",ve="launch.open",Ae="doc.embedFailed",Y="__atkonofficeTitle",oe="atkonoffice-install-guide";function re(e){return e&&e.endsWith("/")?e.slice(0,-1):e}function Be(e,t){if(!e||!t)return!1;try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function j(e,t,o){let r=e.indexOf("?")===-1?"?":"&";return e+r+t+"="+o}function G(e){return!!e&&Object.keys(e).length>0}function R(e){return e&&e.message?e.message:String(e)}function v(e,t,o){if(t==null)return;let r=String(t).trim();r&&(e[r]=o==null?"":String(o))}function Le(e){return e?typeof e=="string"?e:typeof e=="object"?Object.keys(e).map(t=>t+"="+String(e[t])).join("; "):"":""}function De(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 O(){try{return typeof document<"u"&&typeof document.title=="string"?document.title:""}catch{return""}}function ie(){if(typeof window>"u")return!1;try{return window.top!==window.self}catch{return!0}}function V(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 J(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"},se={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 c(e,t){let o=new Error(t);return o.code=e,o.category=se[e],o}function ae(){return typeof n.fetchImpl=="function"?n.fetchImpl:typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):null}function Ct(){let e=ae();if(!e)throw c("fetch_unavailable","atkonoffice: no fetch available \u2014 pass fetchImpl via config in non-browser hosts");return e}async function K(e,t){let o;try{o=await Ct()(n.backendBase+n.launchPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(r){throw r&&se[r.code]?r:c("launch_request_failed",t+" request failed \u2014 "+R(r))}if(!o.ok)throw c("launch_http_error",t+" endpoint returned HTTP "+o.status);try{return await o.json()}catch(r){throw c("launch_response_not_json",t+" response was not JSON \u2014 "+R(r))}}var T={PERM:"PERM",SLOW:"SLOW",RETRY:"RETRY"},ce=":",Pt=[[T.PERM+ce,T.PERM],[T.SLOW+ce,T.SLOW],[T.RETRY+ce,T.RETRY]];function Ue(e){if(typeof e!="string"||!e)return T.RETRY;for(let t of Pt)if(e.indexOf(t[0])===0)return t[1];return T.RETRY}function He(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,fe(),vt()}function Fe(){if(!(!n.pairing||typeof document>"u")){if(!n.pairingTitleSaved){let e=O();e.indexOf(b)<0&&(n.pairingPrevTitle=e,n.pairingTitleSaved=!0)}Me(),Nt()}}function Me(){S(X(n.wsUrl,n.pairId,n.launchTicket))}function X(e,t,o){let r=De(JSON.stringify({wsUrl:e,pairId:t,launchTicket:o}));return M+b+r}function S(e){try{typeof document<"u"&&(document.title=e)}catch{}if(ie())try{let t={};t[Y]=e,window.top.postMessage(t,"*")}catch{}}function fe(){n.titleRelayInstalled||typeof window>"u"||typeof window.addEventListener!="function"||ie()||(n.titleRelayInstalled=!0,window.addEventListener("message",e=>{if(!It(e&&e.origin))return;let t=e&&e.data;if(t&&typeof t=="object"&&typeof t[Y]=="string")try{document.title=t[Y]}catch{}}))}function It(e){let t=n.trustedFrameOrigins;return!t||t.length===0?!0:typeof e=="string"&&t.indexOf(e)!==-1}function Nt(){n.pairingRecoverTimer||typeof setInterval>"u"||(n.pairingRecoverTimer=setInterval(()=>{n.pairing&&O().indexOf(b)<0&&Me()},n.pairRecoverMs))}function vt(){n.pairingTimeoutTimer||typeof setTimeout>"u"||(n.pairingTimeoutTimer=setTimeout(()=>{n.pairingTimeoutTimer=null,Ye(!0)},n.pairTimeoutMs))}function We(){if(!n.pairing)return;let e=n.ws;Ye(!1),k(),e&&At(e)}function At(e){let t={v:1,type:"event",op:ve,ts:Math.floor(Date.now()/1e3),payload:{pair_id:n.pairId,openParams:n.openParams||{}}};try{e.send(JSON.stringify(t))}catch(o){u("error",c("launch_open_frame_send_failed","atkonoffice: failed to send launch.open frame \u2014 "+R(o)))}}function Ye(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&&(S(n.pairingPrevTitle),n.pairingTitleSaved=!1),e&&t&&(V(n.fallbackUrl),typeof n.onPairDowngrade=="function"&&n.onPairDowngrade())}var Bt="documentEmbedFailed";function je(e){u(Bt,e||{})}function le(e,t,o){if(!(!e||typeof sessionStorage>"u"))try{sessionStorage.setItem(H,JSON.stringify({pairId:e,wsUrl:t,nodeBase:o||""}))}catch{}}function Ge(){if(n.pairId)return{pairId:n.pairId,wsUrl:n.wsUrl,nodeBase:n.nodeBase};if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(H);return e?JSON.parse(e):null}catch{return null}}function Lt(){n.pairId="",n.wsUrl="",n.nodeBase=""}function Ve(){if(!(typeof sessionStorage>"u"))try{sessionStorage.removeItem(H)}catch{}}function Je(){Lt(),Ve()}function q(){if(n.ws||n.wsReconnectTimer||n.wsTicketInFlight||n.wsStopped||!n.backendBase)return;let e=Ge();!e||!e.pairId||(n.pairId=e.pairId,n.wsUrl=e.wsUrl||n.wsUrl,n.nodeBase=e.nodeBase||n.nodeBase,n.wsReconnectAttempt=0,Xe(e.pairId,t=>z(t)))}function z(e){if(typeof WebSocket>"u"){u("error",c("ws_unsupported","atkonoffice: WebSocket unavailable in this host \u2014 document events disabled"));return}if(!n.wsUrl){u("error",c("ws_url_missing","atkonoffice: no wsUrl \u2014 cannot open the document-event channel"));return}if(!e){u("error",c("ws_ticket_missing","atkonoffice: missing ws_ticket \u2014 cannot subscribe to document events"));return}de();let t=j(n.wsUrl,"ticket",encodeURIComponent(e)),o;try{o=new WebSocket(t)}catch(r){u("error",c("ws_connect_failed","atkonoffice: WS connect failed \u2014 "+R(r))),A();return}n.ws=o,o.onopen=()=>{n.wsBackoffExhausted&&le(n.pairId,n.wsUrl,n.nodeBase),n.wsReconnectAttempt=0,n.wsStopped=!1,n.wsBackoffExhausted=!1,Dt(o),Ft(o),n.pairing&&Fe()},o.onmessage=r=>{Mt(r&&r.data)},o.onerror=()=>{u("error",c("ws_error","atkonoffice: WS error on the document-event channel"))},o.onclose=r=>{if(n.ws===o&&(n.ws=null),ue(),Ue(r&&r.reason)===T.PERM){Ut("server closed it permanently; reopen the document from the page to start a new session");return}A()}}function Ke(e){n.channelLostAnnounced||(n.channelLostAnnounced=!0,u(B,{reason:e}))}function Dt(e){ue(),n.channelLostAnnounced&&(n.channelRestoreConfirmTimer=setTimeout(()=>{n.channelRestoreConfirmTimer=null,!(n.ws!==e||!n.channelLostAnnounced)&&(n.channelLostAnnounced=!1,u(L,{}))},Ne))}function ue(){n.channelRestoreConfirmTimer&&(clearTimeout(n.channelRestoreConfirmTimer),n.channelRestoreConfirmTimer=null)}function Ut(e){n.wsStopped=!0,n.wsBackoffExhausted=!1,de(),Je();let t=c("ws_gave_up","atkonoffice: document-event channel lost \u2014 "+e);t.terminal=!0,u("error",t),Ke("rejected")}function Ht(e){n.wsBackoffExhausted=!0,Ve();let t=c("ws_backoff_exhausted","atkonoffice: document-event channel still unreachable "+e+" \u2014 left fast reconnect, now probing every "+Math.round(te/1e3)+"s until it comes back");t.terminal=!1,u("error",t),Ke("unreachable")}function de(){n.wsReconnectTimer&&(clearTimeout(n.wsReconnectTimer),n.wsReconnectTimer=null),ue();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 Ft(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",c("headers_frame_send_failed","atkonoffice: failed to send headers frame \u2014 "+R(o)))}}function Mt(e){if(typeof e!="string")return;let t;try{t=JSON.parse(e)}catch{return}if(!t||t.type!=="event")return;if(t.op===W){We();return}if(t.op===Ae){je(t.payload||{});return}let o=N[t.op];o&&u(o,t.payload||{}),t.op===ne&&(n.wsBackoffExhausted=!1,Je(),de())}function A(){if(n.wsReconnectTimer||n.wsStopped)return;let e=Ge();if(!e||!e.pairId){u("error",c("ws_no_pair_to_resume","atkonoffice: document-event channel dropped and no pair to resume"));return}let t=n.wsReconnectAttempt>=ee,o;if(t)o=te;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,Xe(e.pairId,r=>{n.pairId=e.pairId,n.wsUrl=e.wsUrl||n.wsUrl,z(r)})},o),t&&!n.wsBackoffExhausted&&Ht("after "+ee+" consecutive fast reconnect attempts")}async function Xe(e,t){let o=ae();if(!o||!n.backendBase){u("error",c("ws_ticket_backend_missing","atkonoffice: cannot refresh ws_ticket \u2014 backend not configured")),A();return}n.wsTicketInFlight=!0;let r=Be(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",c("ws_ticket_http_error","atkonoffice: ws_ticket refresh returned HTTP "+i.status)),A();return}let s=await i.json();if(!s||typeof s.wsTicket!="string"||!s.wsTicket){u("error",c("ws_ticket_response_invalid","atkonoffice: ws_ticket refresh response missing wsTicket")),A();return}typeof s.wsUrl=="string"&&s.wsUrl&&(n.nodeBase&&n.wsUrl&&s.wsUrl!==n.wsUrl?u("error",c("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",c("ws_ticket_refresh_failed","atkonoffice: ws_ticket refresh failed \u2014 "+R(i))),A()}finally{n.wsTicketInFlight=!1}}function Wt(e){let t=n.eventHandlers[e];return!!t&&t.length>0}function Yt(e){for(let t in N)if(N.hasOwnProperty(t)&&N[t]===e)return!0;return!1}function qe(e){return Yt(e)||e===B||e===L}function ze(){return F.some(e=>qe(e)&&Wt(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 $e(e,t){if(typeof e!="string"||F.indexOf(e)===-1)throw new TypeError('atkonoffice.on: unknown event "'+e+'" (expected one of '+F.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),qe(e)&&q(),w}function Qe(){Gt(n.pairTimeoutMs).then(e=>{k(),e.installed||Jt(e.clientDownloadUrl)})}function jt(e){let t=e.indexOf(b);if(t<0)return null;let o=t;for(;o>0&&e.charAt(o-1)===M;)o-=1;return e.slice(0,o)}function Gt(e){return new Promise(t=>{let o=!1,r=null,i=null,s=null,h=!1,f="",g="",y=()=>{if(i&&(clearTimeout(i),i=null),s&&(clearInterval(s),s=null),h)S(f),h=!1;else{let p=jt(O());p!==null&&S(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,y(),t({installed:p,clientDownloadUrl:g}))};i=setTimeout(()=>m(!1),e),Vt().then(p=>{if(p&&typeof p.clientDownloadUrl=="string"&&(g=p.clientDownloadUrl),o||!J(p)){m(!1);return}let Z=p.wsUrl,Ce=typeof p.pairId=="string"?p.pairId:"",Pe=p.launchTicket;fe();let P;try{P=new WebSocket(j(Z,"ticket",encodeURIComponent(p.wsTicket)))}catch{m(!1);return}r=P,P.onopen=()=>{let I=O();I.indexOf(b)<0&&(f=I,h=!0),S(X(Z,Ce,Pe)),s=setInterval(()=>{!o&&O().indexOf(b)<0&&S(X(Z,Ce,Pe))},n.pairRecoverMs)},P.onmessage=I=>{let Ie=I&&I.data;if(typeof Ie!="string")return;let U;try{U=JSON.parse(Ie)}catch{return}U&&U.type==="event"&&U.op===W&&m(!0)},P.onerror=()=>{},P.onclose=()=>{}}).catch(()=>{m(!1)})})}async function Vt(){return K({docId:"",pageUrl:"",user:"",backendBase:n.backendBase},"atkonoffice: launch-probe")}function Jt(e){if(typeof document>"u"||!document.body||typeof document.createElement!="function")return null;pe();let t=document.createElement("div");t.setAttribute("data-atkonoffice-guide",oe),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;",f="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=f,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",()=>{pe();try{typeof n.replayOpen=="function"&&n.replayOpen()}catch{}});let y=document.createElement("button");return y.type="button",y.textContent="\u5173\u95ED",y.style.cssText=h,y.addEventListener("click",()=>pe()),s.appendChild(g),s.appendChild(y),o.appendChild(r),o.appendChild(i),o.appendChild(s),t.appendChild(o),document.body.appendChild(t),t}function pe(){if(!(typeof document>"u"||typeof document.querySelector!="function"))try{let e=document.querySelector('[data-atkonoffice-guide="'+oe+'"]');e&&typeof e.remove=="function"?e.remove():e&&e.parentNode&&typeof e.parentNode.removeChild=="function"&&e.parentNode.removeChild(e)}catch{}}function Ze(e){if(!e||typeof e!="object")throw new TypeError("atkonoffice.config requires an options object");if(typeof e.backendBase=="string"&&(n.backendBase=re(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,ze()&&q(),w}function me(e){if(n.launchInFlight)return n.inFlightOpen;n.launchInFlight=!0;let t=Kt(e);return n.launchInFlight&&(n.inFlightOpen=t),t}async function Kt(e){try{let t=e||{};if(!n.backendBase)throw c("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 c("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=zt(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 f=await K(s,"atkonoffice.open: launch");if(!f||typeof f.launchUrl!="string"||!f.launchUrl)throw c("launch_response_invalid","atkonoffice.open: launch endpoint response missing launchUrl");let g=Xt(t);n.headers=G(g)?g:null;let y=J(f);return n.replayOpen=()=>me(e),n.onPairDowngrade=y?Qe:null,typeof f.wsTicket=="string"&&f.wsTicket&&typeof f.wsUrl=="string"&&f.wsUrl&&(n.wsUrl=f.wsUrl,n.pairId=typeof f.pairId=="string"?f.pairId:"",n.nodeBase=qt(f),le(n.pairId,n.wsUrl,n.nodeBase),n.wsReconnectAttempt=0,n.wsStopped=!1,n.wsBackoffExhausted=!1,n.wsTicketInFlight=!1,y&&He(f),z(f.wsTicket)),y||(V(f.launchUrl),k()),{launchUrl:f.launchUrl,downloadUrl:typeof f.downloadUrl=="string"?f.downloadUrl:"",pairId:n.pairId,wsUrl:n.wsUrl}}catch(t){throw k(),t}}function Xt(e){let t={},o=e.headers;if(Array.isArray(o)){for(let i of o)if(Array.isArray(i)&&i.length>=2)v(t,i[0],i[1]);else if(typeof i=="string"&&i.indexOf(":")!==-1){let s=i.indexOf(":");v(t,i.slice(0,s),i.slice(s+1).trim())}}else if(o&&typeof o=="object")for(let i of Object.keys(o))v(t,i,o[i]);let r=Le(e.cookie);return r&&v(t,"Cookie",r),e.storage&&typeof e.storage=="object"&&v(t,"X-Atkonoffice-Storage",JSON.stringify(e.storage)),t}function qt(e){let t=e&&e.openParams?e.openParams.backend:null;return typeof t=="string"&&t?re(t):""}function zt(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 et="atkonoffice-doc-host",he="__atkonofficeDocHostEvent",ge=["documentSaved","documentOpened","documentBeforeSave","error","controlReady","compareDiff","documentReady","documentFailed"],ye="doc.ready",_e="doc.embedFailed",we="doc.opened",$={"doc.saved":"documentSaved",[we]:"documentOpened","doc.beforeSave":"documentBeforeSave","compare.diff":"compareDiff",[ye]:"documentReady",[_e]:"documentFailed"},tt="controlReady",nt="toolbarClick",ot="readbackResult",rt="messageBoxResult",a={eventHandlers:{},hintShown:!1,toolbarButtons:{},toolbarSeq:0,readbackPending:{},readbackSeq:0,messageBoxPending:{},messageBoxSeq:0,docTerminal:null};function it(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-"+ ++a.toolbarSeq;return a.toolbarButtons[i]=o,E("toolbarAdd",JSON.stringify({buttonId:i,caption:e,iconIndex:r}))?{remove:function(){delete a.toolbarButtons[i],E("toolbarRemove",JSON.stringify({buttonId:i}))}}:(delete a.toolbarButtons[i],lt(),null)}function st(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 at(e){let t=e&&e.buttonId;if(typeof t!="string"||!t)return;let o=a.toolbarButtons[t];if(typeof o=="function")try{o()}catch(r){ut("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 ct(e){let t=Q();return t&&typeof t.save=="function"?t.save(e):!1}function ft(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 $t=15e3;function C(e,t){if(typeof window>"u")return Promise.resolve({ok:!1,error:"non-browser"});_();let o=++a.readbackSeq,r=JSON.stringify({rid:o,method:e,args:Array.isArray(t)?t:[]});return new Promise(i=>{let s=setTimeout(function(){Te(o,{ok:!1,error:"timeout"})},$t);s&&typeof s.unref=="function"&&s.unref(),a.readbackPending[o]={resolve:i,timer:s},E("readback",r)||Te(o,{ok:!1,error:"shell-absent"})})}function Te(e,t){let o=a.readbackPending[e];o&&(delete a.readbackPending[e],clearTimeout(o.timer),o.resolve(t))}function dt(e){let t=e&&e.rid;typeof t=="number"&&Te(t,e.ok?{ok:!0,value:e.value,error:void 0}:{ok:!1,value:void 0,error:e.error||"invoke failed"})}var Qt=6e5;function pt(e){if(typeof window>"u")return Promise.resolve({ok:!1,error:"non-browser"});_();let t=e&&typeof e=="object"?e:{},o=++a.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(){Ee(o,{ok:!1,error:"timeout"})},Qt);s&&typeof s.unref=="function"&&s.unref(),a.messageBoxPending[o]={resolve:i,timer:s},E("messageBox",r)||Ee(o,{ok:!1,error:"shell-absent"})})}function Ee(e,t){let o=a.messageBoxPending[e];o&&(delete a.messageBoxPending[e],clearTimeout(o.timer),o.resolve(t))}function mt(e){let t=e&&e.rid;typeof t=="number"&&Ee(t,{ok:!!(e&&e.ok),button:e?e.button:void 0,error:e?e.error:void 0})}function ht(e,t){if(e===we){a.docTerminal=null;return}(e===ye||e===_e)&&(a.docTerminal={event:$[e],payload:t||{}})}function gt(e,t){!a.docTerminal||a.docTerminal.event!==e||typeof setTimeout=="function"&&setTimeout(function(){let o=a.docTerminal;if(!(!o||o.event!==e))try{t(o.payload)}catch{}},0)}function _(){Zt(),Q()}function _t(e,t){if(typeof e!="string"||ge.indexOf(e)===-1)throw new TypeError('atkonoffice embed.on: unknown event "'+e+'" (expected one of '+ge.join(", ")+")");if(typeof t!="function")throw new TypeError("atkonoffice embed.on: handler must be a function");return _(),a.eventHandlers[e]||(a.eventHandlers[e]=[]),a.eventHandlers[e].push(t),gt(e,t),d}function Zt(){typeof window>"u"||typeof window[he]=="function"||(window[he]=function(e,t){if(e===tt){yt("controlReady",t||{});return}if(e===nt){at(t||{});return}if(e===ot){dt(t||{});return}if(e===rt){mt(t||{});return}ht(e,t||{});let o=$[e];o&&yt(o,t||{})})}function yt(e,t){let o=a.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 lt(){if(!a.hintShown){a.hintShown=!0;try{console.info("[atkonoffice embed] <"+et+"> \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 ut(e){try{console.warn("[atkonoffice embed] "+e)}catch{}}function wt(e){if(typeof e!="function")throw new TypeError("atkonoffice embed.onBeforeSave: fn must be a function");return _(),Et("onBeforeSave",e),d}function Tt(e){if(typeof e!="function")throw new TypeError("atkonoffice embed.onBeforeClose: fn must be a function");return _(),Et("onBeforeClose",e),d}function Et(e,t){if(typeof window>"u")return!1;let o=window.__atkonofficeDocHost;return o&&typeof o[e]=="function"?(o[e](t),!0):!1}var en="AO_";function D(e){return!!(e&&e.ok&&Number(e.value)>0)}function x(){return Promise.resolve({ok:!1,error:"bad-args"})}function Rt(e,t){return Re(e,t).then(D)}function Re(e,t){if(typeof e!="string"||!e)return x();let o=typeof t=="string"?t:t==null?"":String(t),r={};return r[e]=o,C("Word_FillDataRegion",[JSON.stringify(r)])}function bt(e,t){return be(e,t).then(D)}function be(e,t){if(typeof e!="string"||!e)return x();let o=typeof t=="string"?t:t==null?"":String(t);return C("Word_AddDataRegion",[e,o])}function xt(e){return xe(e).then(D)}function xe(e){return typeof e!="string"||!e?x():C("Word_DeleteDataRegion",[e])}function kt(e){return ke(e).then(D)}function ke(e){return typeof e!="string"||!e?x():C("Word_LocateDataRegion",[e])}function Ot(e){return Oe(e).then(function(t){return t.ok?t.value:[]})}function Oe(e){let t=typeof e=="string"?e:en;return C("BookmarksAsJson",[]).then(function(o){if(!o||!o.ok)return{ok:!1,error:o&&o.error||"invoke failed"};let r;try{r=JSON.parse(o.value)}catch{r=null}return Array.isArray(r)?{ok:!0,value:r.filter(function(i){return typeof i=="string"&&(t===""||i.indexOf(t)===0)})}:{ok:!1,error:"bad-value"}})}function St(e,t){return Se(e,t).then(D)}function Se(e,t){if(typeof e!="string"||!e||!t||typeof t!="object"||Array.isArray(t))return x();let o={};for(let r of["contents","control"])if(t[r]!==void 0){if(typeof t[r]!="boolean")return x();o[r]=t[r]}return Object.keys(o).length?C("Word_SetDataRegionLock",[e,JSON.stringify(o)]):x()}d.on=_t;d.addCustomToolButton=it;d.setCustomToolbarVisible=st;d.save=ct;d.setSavePath=ft;d.showMessageBox=pt;d.onBeforeSave=wt;d.onBeforeClose=Tt;d.word={fillDataRegion:Rt,addDataRegion:bt,deleteDataRegion:xt,locateDataRegion:kt,listDataRegions:Ot,setDataRegionLock:St,receipt:{fillDataRegion:Re,addDataRegion:be,deleteDataRegion:xe,locateDataRegion:ke,listDataRegions:Oe,setDataRegionLock:Se}};w.config=Ze;w.open=me;w.on=$e;w.session=d;var tn=w,Lo=tn;export{tn as atkonoffice,Lo as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atkonoffice/sdk",
3
- "version": "1.9.0",
3
+ "version": "1.11.0",
4
4
  "description": "Browser-side SDK for the atkonoffice editor shell",
5
5
  "homepage": "https://atkon.yunhuichongming.cn",
6
6
  "type": "module",