@kition/kit-table-ui 0.1.0 → 0.1.1

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.
@@ -0,0 +1 @@
1
+ import{C as e,D as t,E as n,S as r,T as i,_ as a,a as o,b as s,f as c,g as l,h as u,i as d,m as f,o as p,p as m,v as h,w as g,x as _,y as v}from"./kit-ui-protocol-BNgs-zwK.js";function y(e,t){return new f(-32e3,t,{reason:e})}var b=e=>new f(-32602,e),x=e=>Object.prototype.toString.call(e)===`[object ArrayBuffer]`;function S(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(t+1).toLowerCase():``}var C=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;function w(e){let t=(e.split(/[\\/]/).pop()??``).replace(/[\u0000-\u001f\u007f<>:"|?*]/g,``).trim().replace(/^\.+/,``).replace(/[. ]+$/,``),n=t.indexOf(`.`),r=n<0?t:t.slice(0,n);if(C.test(r)&&(t=`${r}_${t.slice(r.length)}`),t.length>255){let e=S(t);t=e?`${t.slice(0,254-e.length)}.${e}`:t.slice(0,255)}return t||`Untitled`}async function T(e,t){let n=e.lastIndexOf(`.`),[r,i]=n>0?[e.slice(0,n),e.slice(n)]:[e,``];for(let n=1;n<1e4;n+=1){let a=n===1?e:`${r} ${n}${i}`;if(!await t(a))return a}throw y(`io-error`,`no unused name is left for this file`)}function E(){let e=new Uint8Array(16);return crypto.getRandomValues(e),`fh_`+Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}var D=e=>e.split(/[\\/]/).filter(Boolean).pop()??e,O=()=>globalThis.navigator?.userActivation?.isActive??!0,k=e=>(e??[]).map(e=>e.replace(/^\./,``).toLowerCase());function A(e,t,n){let r=[];return{append:async e=>void r.push(e),commit:async()=>{let i=new Uint8Array(r.reduce((e,t)=>e+t.byteLength,0)),a=0;for(let e of r)i.set(e,a),a+=e.byteLength;let o=await e.commit(t(),i,n());return r=[],o},abort:async()=>{r=[]}}}var j=[`files/pick`,`files/create`,`files/stat`,`files/read`,`files/list`,`files/write`,`files/release`,`files/print`];function M(e){let{storage:t}=e,n=E().slice(3),r={read:k(e.manifest?.read),create:k(e.manifest?.create),folders:e.manifest?.folders===!0,print:e.manifest?.print===!0},i=t.name??D,a=e.gesture??O,o=new Map,s=!1,c=0,l=[`files`,...e.pick?[`files-pick`]:[],...e.print?[`print`]:[]],u=e=>({handle:e.handle,name:e.name,kind:e.kind,...e.size===void 0?{}:{size:e.size},...e.mime===void 0?{}:{mime:e.mime},version:e.version,rights:[...e.rights]}),d=(t,r,a,s,c={})=>{let l={handle:E(),session:n,kit:e.kit,principal:e.principal,flow:s,rights:a,kind:r?.kind??`file`,name:c.name??i(t),ref:t,folder:c.folder??null,accept:c.accept??[],mime:c.mime??r?.mime,version:r?.version??null,size:r?.size,committed:!1,staging:null,staged:0,written:0,expected:null};o.set(l.handle,l);let{handle:u,session:d,kit:f,principal:p,kind:m,name:h}=l;return e.log?.({handle:u,session:d,kit:f,principal:p,flow:s,rights:[...a],kind:m,name:h}),l},p=(e,t,n)=>{if(s)throw y(`file-not-granted`,`the session has ended`);let r=typeof e==`string`?o.get(e):void 0;if(!r)throw y(`file-not-granted`,`this handle was not granted to this session`);if(t&&!r.rights.includes(t))throw y(`file-not-granted`,`this handle has no ${t} right`);if(n&&r.kind!==n)throw y(`file-not-granted`,`this handle is not a ${n}`);return r},m=async e=>{try{return await e()}catch(e){throw e instanceof f?e:y(`io-error`,`the host could not reach the file`)}},h=async e=>{o.delete(e.handle);let t=e.staging;e.staging=null,t&&await t.abort().catch(()=>{})},g=e=>{if(!a())throw y(`no-gesture`,`${e} needs a person's gesture in the kit`)},_=async(e,n)=>{let r=new Set([...o.values()].filter(e=>e.rights.includes(`create`)&&e.kind===`file`&&!e.committed).map(e=>e.ref)),i=await T(n,async n=>{let i=t.child(e,n);return r.has(i)||await t.stat(i)!==null});return{name:i,ref:t.child(e,i)}},v=(e,t=r.read)=>{let n=S(e);if(!r.read.includes(n)||!t.includes(n))throw y(`not-allowed`,`the kit may not read .${n||`(none)`} files`)},C=e=>{let t=S(e);if(!r.create.includes(t))throw y(`not-allowed`,`the kit may not create .${t||`(none)`} files`)},j=(e,t)=>{let n=k(e);if(n.some(e=>!t.includes(e)))throw y(`not-allowed`,`the kit asked for a file type its manifest does not declare`);return n.length?n:t},M=async n=>{if(!e.pick)throw y(`unsupported`,`this host has no picker`);if(n?.mode!==`open`&&n?.mode!==`folder`&&n?.mode!==`save`)throw b(`mode is open, folder, or save`);if(g(`files/pick`),n.mode===`folder`&&!r.folders)throw y(`not-allowed`,`the kit may not ask for folders`);let a=j(n.accept,n.mode===`save`?r.create:r.read);n.mode===`save`&&n.suggestedName!=null&&C(w(n.suggestedName));let o=await m(()=>e.pick(n)),s=[];for(let c of n.mode===`open`&&!n.multiple?o.slice(0,1):o){let o=await m(()=>t.stat(c));if(n.mode===`folder`){if(o?.kind!==`folder`)continue;let e=r.create.length?[`read`,`create`]:[`read`];s.push(u(d(c,o,e,`pick`,{accept:a})))}else if(n.mode===`open`){if(o?.kind!==`file`||!a.includes(S(i(c))))continue;s.push(u(d(c,o,[`read`],`pick`)))}else{if(!a.includes(S(i(c))))throw y(`not-allowed`,`the kit may not create this file type`);if(o?.kind===`folder`)continue;if(o&&e.readOnly)throw y(`not-allowed`,`a read-only session replaces no file`);s.push(u(d(c,o,o?[`write`]:[`create`],`pick`)));break}}return{files:s}},N=async e=>{if(typeof e?.suggestedName!=`string`)throw b(`suggestedName is a string`);let t=e.folder===void 0?null:p(e.folder,`create`,`folder`),n=w(e.suggestedName);C(n);let{name:r,ref:i}=await m(()=>_(t?.ref??null,n));return u(d(i,null,[`create`],`create`,{name:r,folder:t?.ref??null,mime:typeof e.mime==`string`?e.mime:void 0}))},P=async({handle:e,offset:n,length:r})=>{let i=p(e,`read`,`file`),a=n??0;if(!Number.isSafeInteger(a)||a<0||r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw b(`offset and length are whole numbers`);let o=await m(()=>t.read(i.ref,a,r));return i.version=o.version,i.size=o.size,o},F=async({handle:e})=>{let n=p(e,`read`,`folder`),a=await m(()=>t.list(n.ref)),o=[];for(let e of a){if(!n.accept.includes(S(i(e)))||!r.read.includes(S(i(e))))continue;let a=await m(()=>t.stat(e));a?.kind===`file`&&o.push(u(d(e,a,[`read`],`list`)))}return{files:o}},I=async n=>{let r=p(n?.handle,void 0,`file`),i=r.rights.includes(`create`);if(!i&&!r.rights.includes(`write`))throw y(`file-not-granted`,`this handle has no create or write right`);if(i&&r.committed)throw y(`already-committed`,`this file was already committed`);if(!x(n.bytes))throw b(`bytes is an ArrayBuffer`);if(n.offset!==r.staged)throw b(`offset is ${r.staged}, the bytes staged so far`);let a=n.bytes.byteLength;if(e.quota?.perGrant!==void 0&&r.written+a>e.quota.perGrant||e.quota?.perSession!==void 0&&c+a>e.quota.perSession)throw y(`quota`,`this write passes the host's cap`);if(n.final&&!i){if(typeof n.expected!=`string`)throw y(`conflict`,`the final chunk carries the version it replaces`);if(await m(()=>t.unsaved?.(r.ref)??!1))throw y(`unsaved-edits`,`the file is open with unsaved edits`);r.expected=n.expected}if(!r.staging){let e=()=>i?{mode:`create`}:{mode:`replace`,expected:r.expected??``};r.staging=t.stage?t.stage(r.ref,e):A(t,()=>r.ref,e)}let o=r.staging;if(await m(()=>o.append(new Uint8Array(n.bytes.slice(0)))),r.staged+=a,r.written+=a,c+=a,!n.final)return{};let s=await L(r,o,i);return r.staging=null,r.staged=0,r.expected=null,r.version=s.version,i&&(r.committed=!0),{version:s.version}},L=async(e,n,r)=>{for(let i=0;;i+=1)try{return await m(()=>n.commit())}catch(n){let a=n instanceof f&&n.data?.reason===`conflict`;if(!r||!a||e.flow!==`create`||t.stage||i>=8)throw n;let o=await m(()=>_(e.folder,e.name));e.ref=o.ref,e.name=o.name}},R=async({handles:e})=>{for(let t of Array.isArray(e)?e:[]){let e=typeof t==`string`?o.get(t):void 0;e&&await h(e)}return{}},z=async t=>{if(!e.print)throw y(`unsupported`,`this host does not print`);if(!r.print)throw y(`not-allowed`,`the kit may not print`);g(`files/print`);let n;if(!t||typeof t!=`object`)throw b(`a print takes PDF bytes or a handle`);if(`handle`in t){let e=p(t.handle,`read`,`file`);if(S(e.name)!==`pdf`&&e.mime!==`application/pdf`)throw y(`not-allowed`,`only a PDF prints`);n=await B(e.ref)}else{if(t.mime!==`application/pdf`||!x(t.bytes))throw b(`a print takes PDF bytes or a handle`);n=new Uint8Array(t.bytes.slice(0))}let i=typeof t.title==`string`?t.title:``;return{printed:await m(()=>e.print({bytes:n,title:i}))===!0}},B=async e=>{let n=[],r=0;for(;;){let{bytes:i,size:a}=await m(()=>t.read(e,r,void 0));if(n.push(new Uint8Array(i)),r+=i.byteLength,r>=a||i.byteLength===0)break}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.byteLength;return i},V={"files/pick":M,"files/create":N,"files/stat":async({handle:e})=>{let n=p(e);if(n.rights.includes(`create`)&&!n.committed&&n.kind===`file`)return u(n);let r=await m(()=>t.stat(n.ref));if(!r)throw y(`file-not-granted`,`the file is gone`);return Object.assign(n,{version:r.version,size:r.size,mime:r.mime??n.mime}),u(n)},"files/read":P,"files/list":F,"files/write":I,"files/release":R,"files/print":z};return{id:n,capabilities:l,grant:async(n,a,{flow:o,approved:c})=>{if(s)throw y(`file-not-granted`,`the session has ended`);let l=await m(()=>t.stat(n)),f=i(n);if(a.includes(`write`)){if(e.readOnly)throw y(`not-allowed`,`a read-only session replaces no file`);if(o===`agent`&&c!==!0)throw y(`not-allowed`,`an agent replaces a file only through a draft or the person's approval`);if(l?.kind!==`file`)throw y(`not-allowed`,`there is no such file to replace`);C(f)}if(a.includes(`read`)){if(!l)throw y(`not-allowed`,`there is no such file`);if(l.kind===`file`)v(f);else if(!r.folders)throw y(`not-allowed`,`the kit may not read folders`)}if(a.includes(`create`)&&(!l||l.kind===`file`)){if(l)throw y(`not-allowed`,`a create grant never names an existing file`);C(f)}return u(d(n,l,[...new Set(a)],o,l?.kind===`folder`?{accept:r.read}:{}))},revoke:async t=>{let n=[];for(let e of t){let t=o.get(e);t&&(await h(t),n.push(e))}n.length&&e.revoked?.(n)},grants:()=>[...o.values()].map(({handle:e,session:t,kit:n,principal:r,flow:i,rights:a,kind:o,name:s})=>({handle:e,session:t,kit:n,principal:r,flow:i,rights:[...a],kind:o,name:s})),serve:async(t,n)=>{if(e.trace?.(t,n),s)throw y(`file-not-granted`,`the session has ended`);return V[t](n)},end:async()=>{s=!0;for(let e of[...o.values()])await h(e)}}}function N(e){if(/^([A-Za-z]:)?[\\/]/.test(e))return null;let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))if(n&&n!==`.`){if(n===`..`){if(!t.length)return null;t.pop()}else t.push(n)}return t.length?t.join(`/`):null}function P(e,t,n){let r=N(e),i=[];for(let a of n){let n=typeof a?.path==`string`?N(a.path):null;if(!n||n===r||n.split(`/`).some(e=>e.startsWith(`.`)))continue;let o=n.split(`/`).pop(),s=o.includes(`.`)?o.slice(o.lastIndexOf(`.`)+1).toLowerCase():``;if(!t.accept.includes(s))continue;let c={path:m(e,n),name:o,version:typeof a.version==`string`?a.version:null};if(i.some(e=>e.path===c.path)||i.push(c),!t.multiple)break}return i}function F(e){throw new f(-32601,`${e} is not supported by this host`)}function I(t,m){let{handlers:y}=m,b={agent:y.openAgent,"pick-file":y.pick,replica:y.replicaRead&&y.replicaWrite,customize:y.customize,lease:y.leases,presence:y.presence},x=Object.entries(b).filter(([,e])=>e).map(([e])=>e);y.generate&&x.push(`generate`),y.open&&x.push(`open-file`),y.openUrl&&x.push(`open-url`);let S=m.document.readOnly===!0;y.pickLinks&&!S&&x.push(`links-pick`),y.fetchImage&&!S&&x.push(`fetch-image`);let C=Object.entries(y.actions??{}).filter(([,e])=>typeof e==`function`);x.push(...C.map(([e])=>`${l}${e}`));let w=Object.entries(y.services??{}).filter(([e,t])=>typeof t==`function`&&s.includes(e)&&r(e,m.document));x.push(...w.map(([e])=>`${g}${e}`)),y.comments&&x.push(`comment-anchors`),m.files&&x.push(`files`,...m.files.pick?[`files-pick`]:[],...m.files.print?[`print`]:[]);let T=m.timeoutMs??12e4,E=(t,r)=>{let o=new MessageChannel,s=new h(o.port1,`h`),l=null;s.handle(`host/read`,e=>y.read(e)),s.handle(`host/stamp`,e=>y.stamp(e)),s.handle(`host/write`,e=>y.write(e)),s.handle(`host/pick`,e=>y.pick?y.pick(e):F(`host/pick`)),s.handle(`host/openAgent`,async e=>(y.openAgent||F(`host/openAgent`),await y.openAgent(e),{}));let{replicaRead:g,replicaWrite:b}=y;s.handle(`host/replicaRead`,e=>g&&b?g(e):F(`host/replicaRead`)),s.handle(`host/replicaWrite`,async e=>((!g||!b)&&F(`host/replicaWrite`),await b(e),{})),s.handle(`host/customize`,async e=>(y.customize||F(`host/customize`),await y.customize(e),{})),s.handle(`host/leaseAcquire`,e=>y.leases?y.leases.acquire(e):F(`host/leaseAcquire`)),s.handle(`host/leaseRelease`,async e=>(y.leases||F(`host/leaseRelease`),await y.leases.release(e),{})),s.handle(`host/leases`,async()=>(y.leases||F(`host/leases`),{leases:await y.leases.list()})),s.handle(`host/generate`,e=>{if(y.generate||F(`host/generate`),!n(e?.purpose,l))throw new f(-32e3,`a kit may not generate for ${JSON.stringify(e?.purpose)}`,{reason:`not-allowed`});return y.generate(e)}),s.handle(`host/action`,e=>{let t=typeof e?.id==`string`?C.find(([t])=>t===e.id)?.[1]:void 0;if(!t)throw new f(-32e3,`this host does not serve the action ${String(e?.id)}`,{reason:`not-allowed`});return t(e.params&&typeof e.params==`object`?e.params:{})}),s.handle(`host/open`,async e=>{y.open||F(`host/open`);let t=v(e);if(!t)throw new f(-32602,`host/open needs a link with a path, a name, or a docId`);return{opened:(await y.open(t))?.opened!==!1}}),s.handle(`host/openUrl`,async t=>{if(y.openUrl||F(`host/openUrl`),!e(t?.url))throw new f(-32e3,`a host opens only https:, http:, and mailto: addresses`,{reason:`not-allowed`});return{opened:(await y.openUrl({url:t.url}))?.opened!==!1}}),s.handle(`host/fetchImage`,async e=>{if(y.fetchImage||F(`host/fetchImage`),S)throw new f(-32e3,`a read-only document fetches no pictures`,{reason:`read-only`});if(!i(e?.url))throw new f(-32e3,`a host fetches only https: and http: addresses`,{reason:`not-allowed`});let t=await y.fetchImage({url:e.url});if(!(t?.bytes instanceof ArrayBuffer)||!a.includes(t.mime))throw new f(-32e3,`${e.url} is not a picture`,{reason:`unsupported`});return{bytes:t.bytes,mime:t.mime}}),s.handle(`links/pick`,async e=>{if(y.pickLinks||F(`links/pick`),S)throw new f(-32e3,`a read-only document links no files`,{reason:`read-only`});let t=u(e);if(!t)throw new f(-32602,`links/pick needs a purpose and at least one extension without the dot`);return{links:P(m.document.path,t,await y.pickLinks(t)??[])}});let T=m.files?M({...m.files,readOnly:S,revoked:e=>s.notify(`files/revoked`,{handles:e})}):null;if(T)for(let e of j)s.handle(e,t=>T.serve(e,t));s.on(`document/conflicts`,e=>y.conflicts?.(e)),s.on(`document/schema`,e=>{let t=c(e);t&&y.schema?.(t)}),s.on(`draft/changed`,e=>y.draftChanged?.(e)),s.on(`presence/set`,e=>{let t=p(e);t&&y.presence?.(t)}),s.on(`document/changed`,e=>y.changed(e)),s.on(`replica/changed`,e=>y.replicaChanged?.(e)),s.on(`host/notify`,e=>y.notify?.(e)),s.on(`host/shortcut`,e=>y.shortcut?.(e)),s.on(`ui/action`,e=>y.action?.(e)),s.handle(`host/service`,e=>{let t=e?.service,n=w.find(([e])=>e===t)?.[1];if(!n)throw new f(-32e3,`this host does not serve ${String(t)}`,{reason:`not-allowed`});let r=_(e);if(!r)throw new f(-32602,`bad params for ${String(t)}`);return n(r.params)}),s.on(`comments/activated`,e=>{typeof e?.id==`string`&&e.id&&y.comments?.activated(e.id)}),t.postMessage({kitionKitUi:1,protocol:d,id:r},m.origin,[o.port2]);let E={...m.document,bytes:m.document.bytes?.slice(0)},D=s.request(`ui/initialize`,{protocol:d,host:m.host,document:E,theme:m.theme,locale:m.locale,shortcuts:m.shortcuts,capabilities:x,capabilitySets:m.capabilitySets??[],ui:m.ui},{transfer:!0});return D.then(e=>{l=typeof e?.kit?.id==`string`?e.kit.id:null},()=>{}),{peer:s,files:T,initialized:D}};return new Promise((e,n)=>{let r=null,i=e=>{e?.peer.close(),e?.files?.end()},a=()=>{clearTimeout(c),window.removeEventListener(`message`,l),m.signal?.removeEventListener(`abort`,s)},s=()=>{a(),i(r),n(Error(`the kit mount was abandoned`))};if(m.signal?.aborted){n(Error(`the kit mount was abandoned`));return}m.signal?.addEventListener(`abort`,s);let c=setTimeout(()=>{a(),i(r),n(Error(`the kit did not open the document in time`))},T),l=s=>{if(s.source!==t.contentWindow||!o(s.data)||s.data.ready!==`kition-kit-ui/1`||m.origin!==`*`&&s.origin!==m.origin||r?.id===s.data.id)return;i(r);let{peer:c,files:l,initialized:u}=E(s.source,s.data.id);r={peer:c,files:l,id:s.data.id},u.then(t=>{r?.peer===c&&(a(),e(L(c,t,l)))},e=>{r?.peer===c&&(a(),l?.end(),n(e instanceof Error?e:Error(String(e))))})};window.addEventListener(`message`,l),t.contentWindow?.postMessage({kitionKitUi:1,hello:d},m.origin)})}function L(e,n,r){return{kit:n.kit,capabilities:n.capabilities,state:()=>e.request(`document/state`,{}),save:()=>e.request(`document/save`,{}),fileChanged:t=>e.notify(`document/fileChanged`,{version:t}),fileHeld:t=>e.notify(`document/held`,{version:t}),setTheme:t=>e.notify(`ui/theme`,{theme:t}),setLocale:t=>e.notify(`ui/locale`,{locale:t}),focus:()=>e.notify(`ui/focus`,{}),configure:t=>e.notify(`ui/configure`,{ui:t}),leasesChanged:t=>e.notify(`lease/changed`,{leases:t}),peersChanged:t=>e.notify(`presence/peers`,{peers:t}),reveal:t=>e.notify(`document/reveal`,{view:t}),showComments:n=>{let r=n.flatMap(e=>{let n=t(e.anchor);return n&&typeof e.id==`string`?[{id:e.id,anchor:n,resolved:e.resolved===!0,count:Number.isSafeInteger(e.count)?e.count:0}]:[]});e.notify(`comments/show`,{threads:r})},locateComments:async t=>{if(!n.capabilities.includes(`comment-anchors`))return t.map(()=>!1);let{found:r}=await e.request(`comments/locate`,{anchors:t});return t.map((e,t)=>r?.[t]===!0)},onPresence:t=>e.on(`presence/set`,e=>{let n=p(e);n&&t(n)}),elements:()=>e.request(`ui/elements`,{}),check:async t=>n.capabilities.includes(`check`)?(await e.request(`document/check`,t?.draft?{draft:!0}:{})).diagnostics:[],ai:{inspect:t=>e.request(`ai/inspect`,t??{}),commands:t=>e.request(`ai/commands`,{query:t}),run:(t,n,r)=>e.request(`ai/run`,{steps:t,save:n,...r?.draft?{draft:!0}:{},...r?.origin?{origin:r.origin}:{},...r?.originLabel==null?{}:{originLabel:r.originLabel}}),preview:(t,n)=>e.request(`ai/preview`,n?.draft?{maxSize:t,draft:!0}:{maxSize:t}),version:async()=>(await e.request(`ai/version`,{})).version,premise:(t,n)=>e.request(`ai/premise`,{method:t,params:n}),changes:(t,n)=>e.request(`ai/changes`,n?{since:t,schema:n}:{since:t})},draft:{state:()=>e.request(`draft/state`,{}),ready:()=>e.request(`draft/ready`,{}),reopen:()=>e.request(`draft/reopen`,{}),compare:t=>e.request(`draft/compare`,t??{}),merge:(t,n)=>e.request(`draft/merge`,n?{origin:t,schema:n}:{origin:t}),discard:()=>e.request(`draft/discard`,{})},replica:{version:async()=>(await e.request(`replica/version`,{})).version,exportChanges:t=>e.request(`replica/export`,{since:t}),importChanges:(t,n)=>e.request(`replica/import`,{changes:t,blobs:n}),info:async()=>(await e.request(`replica/info`,{})).docId,onChanged:t=>e.on(`replica/changed`,e=>t(e.version))},model:{describe:t=>e.request(`model/describe`,t?{schema:t}:{}),batch:t=>e.request(`model/batch`,t)},files:r&&{grant:r.grant,revoke:r.revoke,grants:r.grants},close:()=>{e.close(),r?.end()}}}var R=new Set([`purpose`,`title`]),z=new Set([`mime`]),B=/^(application|audio|example|font|haptics|image|message|model|multipart|text|video)\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(\s*;\s*[a-z0-9!#$&^_.+-]+=("[^"\\/]*"|[^\s;"\\/]+))*$/i,V=/(^|[\s"'(=])(\/(?:Users|home|root|var|tmp|private|Volumes|mnt|media|etc|opt|srv|data|workspace)\b|[A-Za-z]:[\\/]|\\\\[^\\\s]|~[\\/]|file:)/i;function H(e,t=!1){return V.test(e)?!0:!t&&(/[\\/]/.test(e)||/^\.\.?$/.test(e))}function U(e){return B.test(e)}function W(e,t,n,r,i=0){if(typeof e==`string`)(n===`mime`?!U(e)&&H(e):H(e,n===`free`))&&r.push({at:t,value:e});else if(!(typeof e!=`object`||!e||i>8||e instanceof ArrayBuffer||ArrayBuffer.isView(e))){if(Array.isArray(e))e.forEach((e,a)=>W(e,`${t}[${a}]`,n,r,i+1));else for(let[n,a]of Object.entries(e))W(a,t?`${t}.${n}`:n,R.has(n)?`free`:z.has(n)?`mime`:`name`,r,i+1)}}function G(e){let t=[];for(let{method:n,params:r}of e){if(!n.startsWith(`files/`))continue;let e=[];W(r,``,`name`,e);for(let r of e)t.push({method:n,...r})}return t}var K={pdf:`application/pdf`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,txt:`text/plain`,json:`application/json`},q=e=>e.split(`/`).some(e=>e.startsWith(`.`)||e===``),J=e=>e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;function Y(e,t,n=new Set){let r=t=>n.has(t)||[...e.keys()].some(e=>e.startsWith(`${t}/`));return{stat:t=>{if(q(t))return null;let n=e.get(t);if(n){let e=K[t.split(`.`).pop()?.toLowerCase()??``];return{kind:`file`,size:n.bytes.byteLength,version:String(n.version),...e?{mime:e}:{}}}return r(t)?{kind:`folder`,version:null}:null},read:async(t,n,r)=>{let i=q(t)?void 0:e.get(t);if(!i)throw y(`file-not-granted`,`the file is gone`);let a=r===void 0?i.bytes.byteLength:Math.min(i.bytes.byteLength,n+r);return{bytes:i.bytes.slice(n,a),version:String(i.version),size:i.bytes.byteLength}},list:t=>{let r=new Set;for(let i of[...e.keys(),...n]){if(!i.startsWith(`${t}/`)||q(i))continue;let e=i.slice(t.length+1);r.add(`${t}/${e.split(`/`)[0]}`)}return[...r].sort()},child:(e,n)=>{let r=e??t();return r?`${r}/${n}`:n},commit:async(t,i,a)=>{let o=e.get(t);if(a.mode===`create`&&(o||r(t)))throw y(`conflict`,`a file with this name exists`);if(a.mode===`replace`&&(!o||String(o.version)!==a.expected))throw y(`conflict`,`the file changed since it was read`);!r(J(t))&&J(t)!==``&&n.add(J(t));let s=(o?.version??0)+1;return e.set(t,{bytes:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),version:s}),{version:String(s)}}}}var X={light:{colorScheme:`light`,tokens:{"--kit-primary":`#5645d4`,"--kit-surface":`#ffffff`,"--kit-surface-muted":`#fafaf9`,"--kit-canvas":`#f6f5f4`,"--kit-text":`#1a1a1a`,"--kit-text-muted":`#5d5b54`,"--kit-border":`#e5e3df`}},dark:{colorScheme:`dark`,tokens:{"--kit-primary":`#8b7ff0`,"--kit-surface":`#1b1e23`,"--kit-surface-muted":`#22262c`,"--kit-canvas":`#15171b`,"--kit-text":`#eceff1`,"--kit-text-muted":`#a9b0ba`,"--kit-border":`#33373e`}}};function Z(e,t){let n=t.split(`.`).pop()?.toLowerCase()??``;return!e?.length||e.some(e=>e.replace(/^\./,``).toLowerCase()===n)}function ee(e){return e!==`viewer`&&e!==`commenter`?{}:{readOnly:!0,comments:{me:`dev-${e}`,name:e===`viewer`?`Viewer`:`Commenter`,canComment:e===`commenter`,othersReadOnly:!1}}}function Q(e){let t=[];for(let n of e.split(`/`))if(n&&n!==`.`){if(n===`..`){if(!t.length)return null;t.pop()}else t.push(n)}return t.join(`/`)}function te(e,t,n){let r=t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``;if(e.path){let t=Q(e.path.startsWith(`/`)?e.path:`${r}/${e.path}`);return t?{path:t,exists:n.has(t)}:null}if(!e.name||e.name.includes(`/`))return null;let i=t.includes(`.`)?t.slice(t.lastIndexOf(`.`)):``,a=e=>(e.split(`/`).pop()??``).replace(/\.[^.]*$/,``).toLowerCase(),o=[...n.keys()].filter(t=>a(t)===e.name.toLowerCase()),s=o.find(e=>e.endsWith(i))??o[0];if(s)return{path:s,exists:!0};let c=Q(`${r}/${e.name}${i}`);return c?{path:c,exists:!1}:null}var $=[`menus`,`line`,`classic`,`focus`];function ne(e){let t=[];for(let n of(e??``).split(`,`).map(e=>e.trim()).filter(Boolean))$.includes(n)?t.push(n):console.warn(`kit-dev-host: ?modes= names an unknown display mode "${n}" (one of ${$.join(`, `)})`);return t.length?{allowed:t,default:t[0]}:void 0}function re(e={}){let t=new Map,n=document.getElementById(`kit`),r=document.getElementById(`status`),i=document.getElementById(`file`),a=[],o=e.entry??`./index.html`,s=e.pickable??/\.(png|jpe?g|gif|svg|webp)$/i,c=null,l=e.presence===!0||new URLSearchParams(location.search).get(`presence`)===`1`,u=[],d=[],p=[],m=new Set,h=[],g=[],_=[],v=[],y=e.generate===!0||new URLSearchParams(location.search).get(`generate`)===`1`,b=[],x=[],S=e.open===!0||new URLSearchParams(location.search).get(`open`)===`1`,C=[],w=[],T=[],E=``,D=`kit-dev-host:personal:${location.pathname}`,O=[],k=new URLSearchParams(location.search).get(`scheme`)===`dark`?`dark`:`light`,A=ne(new URLSearchParams(location.search).get(`modes`)),j=A?{modes:A}:{},M=()=>{try{return JSON.parse(localStorage.getItem(D)??`[]`)}catch{return[]}},N=()=>({...j,personal:{hide:M()}}),P=document.createElement(`details`);P.innerHTML=`<summary>UI configuration</summary><textarea rows="6" cols="60" spellcheck="false">{}</textarea><button type="button">Apply</button><select><option value="light">Light</option><option value="dark">Dark</option></select>`,r.parentElement?.append(P);let F=P.querySelector(`textarea`),L=P.querySelector(`select`);L.value=k,P.querySelector(`button`).addEventListener(`click`,()=>{try{R(JSON.parse(F.value))}catch(e){r.textContent=`configuration: ${e instanceof Error?e.message:String(e)}`}}),L.addEventListener(`change`,()=>z(L.value===`dark`?`dark`:`light`));function R(e){j={hide:e.hide,disable:e.disable,add:e.add,modes:e.modes??A},F.value=JSON.stringify(j,null,2),c?.configure(N())}function z(e){k=e,L.value=e,c?.setTheme(X[e])}async function B(i,f,b={}){c?.close(),E=i,t.set(i,{bytes:f,version:1}),r.textContent=`opening ${i}…`,n.src=`${o}?${Date.now()}`;let x=t.get(i);try{c=await I(n,{origin:location.origin,host:{name:`Development host`,version:`1`},document:{path:i,name:i.split(`/`).pop()??i,bytes:x.bytes.slice(0),version:String(x.version),lend:e.lend?{root:new URL(e.lend.root,location.href).href,folder:e.lend.folder}:void 0,...ee(new URLSearchParams(location.search).get(`role`)),...b.view?{view:b.view}:{}},theme:X[k],locale:new URLSearchParams(location.search).get(`locale`)??navigator.language,shortcuts:[`Cmd+W`,`Cmd+N`,`Cmd+O`,`Cmd+,`],ui:N(),handlers:{read:({path:e,offset:n,length:r})=>{let i=t.get(e);if(!i)throw Error(`${e} is not in the workspace`);let a=n??0;return{bytes:n!=null||r!=null?i.bytes.slice(a,r==null?void 0:a+r):i.bytes.slice(0),version:String(i.version),size:i.bytes.byteLength}},stamp:({path:e})=>({version:t.has(e)?String(t.get(e).version):null}),write:({path:e,bytes:n,mode:r})=>{let i=e;if(r!==`save`)for(let n=2;t.has(i);n+=1)i=e.replace(/(\.[^./]+)?$/,` ${n}$1`);let a=(t.get(i)?.version??0)+1;return t.set(i,{bytes:n,version:a}),{path:i,version:String(a)}},pick:({accept:e})=>({path:[...t.keys()].find(t=>s.test(t)&&Z(e,t))??null}),pickLinks:e=>{T.push(e);let n=w.shift();return(n?typeof n==`function`?n(e):n:[...t.keys()].filter(t=>t!==i&&s.test(t)&&Z(e.accept,t))).filter(e=>t.has(e)).map(e=>({path:e,version:String(t.get(e).version)}))},openAgent:()=>{r.textContent=`the editor asked for the agent`},changed:e=>{a.push(e),r.textContent=`${i}: revision ${e.revision}${e.dirty?`, unsaved`:``}`},notify:e=>{r.textContent=`${e.level}: ${e.title}`},shortcut:e=>{r.textContent=`host shortcut ${e.key}`},customize:({personal:e})=>{localStorage.setItem(D,JSON.stringify(e.hide))},action:e=>{O.push(e),r.textContent=`host button ${e.id}`},schema:e=>{d.push(e)},...l?{presence:e=>void u.push(e)}:{},...y?{generate:e=>V(e)}:{},...S?{open:e=>H(e),openUrl:e=>U(e)}:{}},...e.kitFiles?{files:{storage:Y(t,()=>E.includes(`/`)?E.slice(0,E.lastIndexOf(`/`)):``,m),kit:`dev-kit`,principal:`dev-person`,manifest:e.kitFiles,pick:async e=>{let t=h.shift();return typeof t==`function`?t(e):t??[]},print:async({bytes:e,title:t})=>(v.push({title:t,size:e.byteLength}),window.devHost.printAnswer),log:e=>void g.push(e),trace:(e,t)=>void _.push({method:e,params:t})}}:{}}),l&&p.length&&c.peersChanged(p),r.textContent=`${i} open in ${c.kit.id} ${c.kit.version}`}catch(e){r.textContent=`could not open ${i}: ${e instanceof Error?e.message:String(e)}`}}async function V(e){b.push(e),r.textContent=`the editor asked to generate for ${e.purpose}`;let t=x.shift()??{refuse:`unavailable`},n=typeof t==`function`?await t(e):t;if(`refuse`in n)throw new f(-32e3,`the development host refused: ${n.refuse}`,{reason:n.refuse});return n}async function H(e){C.push({method:`host/open`,params:e}),r.textContent=`the editor asked to open ${JSON.stringify(e.link)}`;let n=te(e.link,E,t);if(!n)throw new f(-32e3,`the link is not in the workspace`,{reason:`not-found`});if(!n.exists){if(!e.create)throw new f(-32e3,`${n.path} is not in the workspace`,{reason:`not-found`});t.set(n.path,{bytes:new ArrayBuffer(0),version:1})}return{opened:window.devHost.openAnswer}}async function U(e){return C.push({method:`host/openUrl`,params:e}),r.textContent=`the editor asked to open ${e.url}`,{opened:window.devHost.openAnswer}}function W(e){p=e,l&&c?.peersChanged(e)}window.devHost={files:t,connection:()=>c,open:B,changes:a,configure:R,actions:O,setScheme:z,presences:u,setPeers:W,schemas:d,folders:m,scriptPick:(...e)=>void h.push(...e),grants:g,fileRequests:_,prints:v,printAnswer:!0,checkNoPaths:()=>G(_),generated:b,scriptGenerate:(...e)=>void x.push(...e),opens:C,openAnswer:!0,scriptLinkPick:(...e)=>void w.push(...e),linkPicks:T},i?.addEventListener(`change`,async()=>{let e=i.files?.[0];e&&await B(e.name,await e.arrayBuffer())}),(async()=>{for(let[n,r]of Object.entries(e.files??{})){let e=await fetch(r).catch(()=>null);e?.ok&&t.set(n,{bytes:await e.arrayBuffer(),version:1})}if(!e.sample){r.textContent=`choose a file`;return}let n=await fetch(e.sample).catch(()=>null);if(!n?.ok){r.textContent=`choose a file`;return}let i=decodeURIComponent(e.sample.split(`/`).pop()??`Sample`);await B(e.lend?.folder?`${e.lend.folder}/${i}`:i,await n.arrayBuffer())})()}re({sample:`./sample/Sample.ktable`});