@blinkk/root-cms 3.0.6 → 3.1.2
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.
- package/README.md +77 -0
- package/dist/app.js +6 -4
- package/dist/browser-client/browser-client.d.ts +148 -0
- package/dist/browser-client/embed-window.d.ts +66 -0
- package/dist/browser-client/emitter.d.ts +11 -0
- package/dist/browser-client.js +377 -0
- package/dist/{chunk-RXWDB3K4.js → chunk-4VZTYUQ7.js} +1 -1
- package/dist/{chunk-N4K6ICFR.js → chunk-AFBSITEO.js} +4 -6
- package/dist/{chunk-PNLLZXVY.js → chunk-AJDMNTZQ.js} +2 -2
- package/dist/chunk-J72JK4KR.js +8 -0
- package/dist/{chunk-7L5OI5ES.js → chunk-X5CNR4CK.js} +8 -4
- package/dist/cli.js +2 -1
- package/dist/client.js +2 -1
- package/dist/core/client.d.ts +5 -0
- package/dist/core/plugin.d.ts +1 -1
- package/dist/core/translations.d.ts +19 -4
- package/dist/core.js +4 -2
- package/dist/functions.js +4 -3
- package/dist/plugin.js +38 -7
- package/dist/shared/embed-protocol.d.ts +72 -0
- package/dist/shared/translation-languages.d.ts +67 -0
- package/dist/ui/AIPage-2N5UYBRX.js +1 -0
- package/dist/ui/AssetsPage-KLGNE6D6.js +1 -0
- package/dist/ui/CollectionPage-D7IG6526.js +1 -0
- package/dist/ui/ComparePage-726NIJW5.js +1 -0
- package/dist/ui/DataPage-YMSQCIVK.js +1 -0
- package/dist/ui/DataSourcePage-7VPFUG3K.js +1 -0
- package/dist/ui/DocTranslationsPage-FO7O76VK.js +1 -0
- package/dist/ui/DocumentPage-M7SJ4ITQ.js +1 -0
- package/dist/ui/EditDataSourcePage-Y7YK6IWT.js +1 -0
- package/dist/ui/EditReleasePage-XZ4RHHRT.js +1 -0
- package/dist/ui/EmbeddedAIPage-RJOUIPF2.js +1 -0
- package/dist/ui/EmbeddedDocumentPage-4TLMCDSO.js +1 -0
- package/dist/ui/{ImageEditorDialog-QEULJAT2.js → ImageEditorDialog-GGS4VFEA.js} +2 -2
- package/dist/ui/LogsPage-IGDDZGEI.js +1 -0
- package/dist/ui/NewDataSourcePage-YUPRHL7F.js +1 -0
- package/dist/ui/NewReleasePage-6HHLYOQP.js +1 -0
- package/dist/ui/NotFoundPage-A6OCYREA.js +1 -0
- package/dist/ui/ProjectPage-UHRXNN7O.js +1 -0
- package/dist/ui/ReleasePage-V2JMPWX7.js +1 -0
- package/dist/ui/ReleasesPage-SCR4SVKN.js +1 -0
- package/dist/ui/SettingsPage-5XKHPG6K.js +1 -0
- package/dist/ui/SidebarToolsPage-VXVRZ2C3.js +1 -0
- package/dist/ui/TaskPage-LDPRN3G6.js +1 -0
- package/dist/ui/TasksPage-DIXUWYXM.js +1 -0
- package/dist/ui/TranslationsArbPage-QPD3ZBT4.js +2 -0
- package/dist/ui/TranslationsEditPage-475Z7UPC.js +1 -0
- package/dist/ui/{TranslationsPage-OBN6CQZZ.js → TranslationsPage-674JU6L4.js} +32 -32
- package/dist/ui/{chunk-N4DFAIC5.js → chunk-2EPQJUGM.js} +1 -1
- package/dist/ui/{chunk-WKOX3VFN.js → chunk-2RAVKX2Z.js} +2 -2
- package/dist/ui/chunk-2S5HMST6.js +1 -0
- package/dist/ui/{chunk-V7RAXP2W.js → chunk-3E6CASIN.js} +1 -1
- package/dist/ui/chunk-4ALFT4ES.js +141 -0
- package/dist/ui/{chunk-KYKFNAX4.js → chunk-4FGASIIX.js} +1 -1
- package/dist/ui/chunk-4ISFTE2G.js +5 -0
- package/dist/ui/{chunk-SKEP5WYH.js → chunk-7SK47HHZ.js} +3 -3
- package/dist/ui/chunk-AAHM6RYJ.js +1 -0
- package/dist/ui/chunk-AGFPVTBA.js +1 -0
- package/dist/ui/chunk-BUNR5EU3.js +1 -0
- package/dist/ui/{chunk-N5Y5OWTV.js → chunk-BW2MKGNP.js} +1 -1
- package/dist/ui/{chunk-2225WAJ2.js → chunk-CAY5NM4Z.js} +1 -1
- package/dist/ui/{chunk-4KE2SZKH.js → chunk-D3UIZHRK.js} +1 -1
- package/dist/ui/{chunk-HYARD7BK.js → chunk-ENQKSLGJ.js} +1 -1
- package/dist/ui/chunk-FBSBL476.js +1 -0
- package/dist/ui/{chunk-NQB37NMX.js → chunk-FJLNXXE3.js} +1 -1
- package/dist/ui/chunk-GT5EQSEX.js +1 -0
- package/dist/ui/{chunk-KPJ53X55.js → chunk-HARRKJFZ.js} +1 -1
- package/dist/ui/{chunk-6E7PGMZX.js → chunk-HO3W4RVG.js} +1 -1
- package/dist/ui/{chunk-CVGYBXVH.js → chunk-J5E457OI.js} +1 -1
- package/dist/ui/{chunk-SEUH7LN2.js → chunk-JBHRZ4EX.js} +1 -1
- package/dist/ui/{chunk-W3HIZQ4Z.js → chunk-JS6TK4OP.js} +1 -1
- package/dist/ui/{chunk-BEDUTYQP.js → chunk-JTIQBW33.js} +1 -1
- package/dist/ui/{chunk-ORXEMIQC.js → chunk-KRNQ6L35.js} +1 -1
- package/dist/ui/chunk-LROR6N3B.js +7 -0
- package/dist/ui/{chunk-4CUWZQXT.js.LEGAL.txt → chunk-LROR6N3B.js.LEGAL.txt} +6 -1
- package/dist/ui/{chunk-6GPTGBA7.js → chunk-MSYTAJBV.js} +1 -1
- package/dist/ui/{chunk-RQKL4KXY.js → chunk-N3JSLTMV.js} +1 -1
- package/dist/ui/{chunk-NMBXHKIJ.js → chunk-NJMNOITA.js} +1 -1
- package/dist/ui/{chunk-D37DCENS.js → chunk-NSOTG64N.js} +1 -1
- package/dist/ui/chunk-NWHGT476.js +1 -0
- package/dist/ui/chunk-P2Z66DHV.js +1 -0
- package/dist/ui/{chunk-4IXGYXA2.js → chunk-PTPYMVFW.js} +1 -1
- package/dist/ui/{chunk-OVRTVMO5.js → chunk-Q7IU4QCY.js} +1 -1
- package/dist/ui/{chunk-XYBHH5L4.js → chunk-QF3GPZTI.js} +1 -1
- package/dist/ui/{chunk-AXETBZ6T.js → chunk-QHJOTXYB.js} +1 -1
- package/dist/ui/{chunk-UHWNLNP4.js → chunk-RHAJNURN.js} +1 -1
- package/dist/ui/chunk-SENZVSVZ.js +1 -0
- package/dist/ui/chunk-SKQECSUR.js +1 -0
- package/dist/ui/chunk-TOGLZDK3.js +1 -0
- package/dist/ui/chunk-TPJCPCRR.js +1 -0
- package/dist/ui/{chunk-EMYXSVTD.js → chunk-TVYAZN2Q.js} +1 -1
- package/dist/ui/{chunk-GDSSFO5R.js → chunk-UUVAD4U4.js} +1 -1
- package/dist/ui/{chunk-EGEB6N4J.js → chunk-VD6G5NV4.js} +11 -11
- package/dist/ui/{chunk-DXKEDMEI.js → chunk-VJUMFJIX.js} +1 -1
- package/dist/ui/chunk-W5DOO6ID.js +1 -0
- package/dist/ui/{chunk-6MOPIV5T.js → chunk-W6LP22IK.js} +1 -1
- package/dist/ui/{chunk-3XYCOR6Z.js → chunk-WFQU7V3W.js} +1 -1
- package/dist/ui/chunk-WMICEDOT.js +1 -0
- package/dist/ui/chunk-XMESZUC5.js +1 -0
- package/dist/ui/{chunk-T47V6AGW.js → chunk-XWX2622O.js} +1 -1
- package/dist/ui/chunk-YMBBWVBB.js +3 -0
- package/dist/ui/chunk-YXSXWFLZ.js +1 -0
- package/dist/ui/chunk-ZMS6NIGG.js +1 -0
- package/dist/ui/gcs-ECSDFCIU.js +1 -0
- package/dist/ui/ui.css +1 -1
- package/dist/ui/ui.js +1 -1
- package/package.json +7 -3
- package/dist/ui/AIPage-JPZ4QUB4.js +0 -1
- package/dist/ui/AssetsPage-GDJMKS3M.js +0 -1
- package/dist/ui/CollectionPage-5DVXJEET.js +0 -1
- package/dist/ui/ComparePage-LIXA6G66.js +0 -1
- package/dist/ui/DataPage-AP4Z5JPS.js +0 -1
- package/dist/ui/DataSourcePage-WO3ZKMFI.js +0 -1
- package/dist/ui/DocTranslationsPage-QKYFIVHP.js +0 -1
- package/dist/ui/DocumentPage-ON43I5KM.js +0 -1
- package/dist/ui/EditDataSourcePage-XVMEV2LJ.js +0 -1
- package/dist/ui/EditReleasePage-A2NB5TFG.js +0 -1
- package/dist/ui/LogsPage-4LZJX3O4.js +0 -1
- package/dist/ui/NewDataSourcePage-4YWX7IOG.js +0 -1
- package/dist/ui/NewReleasePage-HWLVTEXX.js +0 -1
- package/dist/ui/NotFoundPage-72AXQAYX.js +0 -1
- package/dist/ui/ProjectPage-L4GYDIA5.js +0 -1
- package/dist/ui/ReleasePage-43BSWL5B.js +0 -1
- package/dist/ui/ReleasesPage-CJXAZBP6.js +0 -1
- package/dist/ui/SettingsPage-SYXAMKSF.js +0 -1
- package/dist/ui/SidebarToolsPage-OFF5BOXP.js +0 -1
- package/dist/ui/TaskPage-HBDLHFI5.js +0 -1
- package/dist/ui/TasksPage-OLCDTQNB.js +0 -1
- package/dist/ui/TranslationsArbPage-E3NCMAMS.js +0 -2
- package/dist/ui/TranslationsEditPage-IWOI7Y5G.js +0 -1
- package/dist/ui/chunk-32LRQ5MJ.js +0 -1
- package/dist/ui/chunk-3HVDIPSS.js +0 -1
- package/dist/ui/chunk-3IDOZ4MG.js +0 -1
- package/dist/ui/chunk-4CUWZQXT.js +0 -7
- package/dist/ui/chunk-AOCBDKLV.js +0 -1
- package/dist/ui/chunk-DUJYIOLE.js +0 -5
- package/dist/ui/chunk-IDYKCAAL.js +0 -1
- package/dist/ui/chunk-IKED2IGU.js +0 -1
- package/dist/ui/chunk-J3EGGI57.js +0 -1
- package/dist/ui/chunk-MZP6RIG2.js +0 -1
- package/dist/ui/chunk-NQ5ARARP.js +0 -1
- package/dist/ui/chunk-RI2JWWU3.js +0 -141
- package/dist/ui/chunk-RPOP6MVJ.js +0 -1
- package/dist/ui/chunk-TDKVKTW4.js +0 -1
- package/dist/ui/chunk-TZEZEMRQ.js +0 -1
- package/dist/ui/chunk-UA7UCTX5.js +0 -1
- package/dist/ui/chunk-UFQSZ6J2.js +0 -3
- package/dist/ui/gcs-L33FIRZU.js +0 -1
- /package/dist/ui/{ImageEditorDialog-QEULJAT2.js.LEGAL.txt → ImageEditorDialog-GGS4VFEA.js.LEGAL.txt} +0 -0
- /package/dist/ui/{chunk-RI2JWWU3.js.LEGAL.txt → chunk-4ALFT4ES.js.LEGAL.txt} +0 -0
- /package/dist/ui/{chunk-SKEP5WYH.js.LEGAL.txt → chunk-7SK47HHZ.js.LEGAL.txt} +0 -0
- /package/dist/ui/{chunk-NMBXHKIJ.js.LEGAL.txt → chunk-NJMNOITA.js.LEGAL.txt} +0 -0
- /package/dist/ui/{chunk-EGEB6N4J.js.LEGAL.txt → chunk-VD6G5NV4.js.LEGAL.txt} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as C}from"./chunk-
|
|
1
|
+
import{a as C}from"./chunk-FJLNXXE3.js";import{e as p}from"./chunk-BUNR5EU3.js";import{Fb as u,Ga as o,U as _,g,j as b}from"./chunk-LROR6N3B.js";b();function m(s){let e={},t=[],r={};if(Object.entries(s).forEach(([n,i])=>{e[n]={id:n,name:i.name||n,description:i.description,isGroup:!1,collection:i,children:[]}}),Object.entries(s).forEach(([n,i])=>{let c=e[n],d=i.group||"Content";d?(r[d]||(r[d]={id:`group:${d}`,name:d,isGroup:!0,children:[]}),r[d].children.push(c)):t.push(c)}),Object.keys(r).length>0&&t.length>0){let n={id:"group:Content",name:"Content",isGroup:!0,children:t},i=Object.values(r).sort((c,d)=>c.name.localeCompare(d.name));return[n,...i]}Object.values(r).forEach(n=>{t.push(n)});let l=n=>{n.sort((i,c)=>i.name.localeCompare(c.name)),n.forEach(i=>{i.children.length>0&&l(i.children)})};return l(t),t}function O(s){let{collections:e,activeCollectionId:t,projectId:r}=s,[a,l]=C(`root-cms::${r}::closed_groups`,[]),n=g(()=>m(e),[]),i=(c,d)=>{d?l(a.filter(v=>v!==c)):a.includes(c)||l([...a,c])};return o("div",{className:p(s.className,"CollectionTree"),children:[n.map(c=>o(h,{node:c,depth:0,activeCollectionId:t,closedGroups:a,onAccordionChange:i},c.id)),n.length===0&&o("div",{className:"CollectionTree__collections__empty",children:"No collections match your query."})]})}function h(s){let{node:e,depth:t,activeCollectionId:r,closedGroups:a,onAccordionChange:l}=s,n=e.children.length>0;return e.isGroup?n?o(f,{node:e,depth:t,activeCollectionId:r,closedGroups:a,onAccordionChange:l,label:o("div",{className:"CollectionTree__group__label",children:o("span",{children:e.name})})}):o("div",{className:"CollectionTree__group-empty",style:{paddingLeft:`${t*16}px`},children:[o(u,{size:20,strokeWidth:"1.75"}),o("span",{children:e.name})]}):n?o(f,{node:e,depth:t,activeCollectionId:r,closedGroups:a,onAccordionChange:l,label:o("div",{className:"CollectionTree__collection__label",children:o("a",{className:p("CollectionTree__collection-link",e.id===r&&"active"),href:`/cms/content/${e.id}`,onClick:i=>i.stopPropagation(),children:e.name})})}):o("a",{className:p("CollectionTree__collection",e.id===r&&"active"),href:`/cms/content/${e.id}`,children:[o("div",{className:"CollectionTree__collection__icon",children:o(u,{size:20,strokeWidth:"1.75"})}),o("div",{className:"CollectionTree__collection__content",children:[o("div",{className:"CollectionTree__collection__name",children:e.name}),e.description&&o("div",{className:"CollectionTree__collection__desc",children:e.description})]})]})}function f(s){let{node:e,depth:t,label:r,activeCollectionId:a,closedGroups:l,onAccordionChange:n}=s,i=!l.includes(e.id);return o("div",{className:"CollectionTree__accordion",children:o(_,{iconPosition:"left",initialItem:i?0:-1,offsetIcon:!1,onChange:()=>n(e.id,!i),children:o(_.Item,{label:r,children:o("div",{className:"CollectionTree__accordion__children",children:e.children.map(c=>o(h,{node:c,depth:t+1,activeCollectionId:a,closedGroups:l,onAccordionChange:n},c.id))})})})})}export{O as a};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{f as c}from"./chunk-KRNQ6L35.js";import{a as p,b,c as g,g as E,i as C,n as x,p as _,q as A,s as w,t as h,v as u,w as D}from"./chunk-VD6G5NV4.js";var q="tasks",H=20;function K(){let t=window.firebase.db,e=window.__ROOT_CTX.rootConfig.projectId;return g(t,"Projects",e)}function T(t){let e=window.firebase.db,n=window.__ROOT_CTX.rootConfig.projectId;return g(e,"Projects",n,"Tasks",t)}function N(){let t=window.firebase.db,e=window.__ROOT_CTX.rootConfig.projectId;return g(t,"Projects",e,"Counters",q)}function v(){let t=window.firebase.db,e=window.__ROOT_CTX.rootConfig.projectId;return b(t,"Projects",e,"Tasks")}function O(t){let e=window.firebase.db,n=window.__ROOT_CTX.rootConfig.projectId;return b(e,"Projects",n,"Tasks",t,"Comments")}function P(t,e){let n=window.firebase.db,s=window.__ROOT_CTX.rootConfig.projectId;return g(n,"Projects",s,"Tasks",t,"Comments",e)}function R(t){let e=window.firebase.db,n=window.__ROOT_CTX.rootConfig.projectId;return b(e,"Projects",n,"Tasks",t,"Events")}function G(t){return g(R(t))}async function J(){let t=await x(K());return t.exists()&&(t.data()||{}).settings?.defaultAssignee||null}async function st(t){if(!t.title)throw new Error("missing task title");let e=window.firebase.db,n=t.assignee??await J(),s=t.priority||"normal",a="new",i=L(t.targetLaunchDate),d=await h(e,async r=>{let o=N(),l=(await r.get(o)).data()||{},f=typeof l.lastTaskId=="number"?l.lastTaskId:0,k=Math.floor(f)+1;for(let B=0;B<H;B++){let j=T(String(k));if(!(await r.get(j)).exists())return r.set(o,{lastTaskId:k,updatedAt:u()},{merge:!0}),r.set(j,{id:String(k),title:t.title,description:t.description||"",assignee:n??null,priority:s,status:a,targetLaunchDate:i,createdAt:u(),createdBy:window.firebase.user.email||"",updatedAt:u(),updatedBy:window.firebase.user.email||""}),String(k);k+=1}throw new Error("unable to allocate a task id")});return c("tasks.create",{metadata:{taskId:d}}),d}function L(t){return t instanceof Date?p.fromDate(t):t??null}function Q(t){let e=W(t);return!["closed","complete","completed","done","resolved"].includes(e)}function W(t){let e=(t||"new").trim().toLowerCase();return e==="open"?"new":e==="blocked"?"in-progress":["done","complete","completed","resolved"].includes(e)?"closed":e}function Y(t){return t.sort((e,n)=>{let s=e.createdAt?.toMillis?.()||0;return(n.createdAt?.toMillis?.()||0)-s})}function M(t){return Y(t.docs.map(e=>({...e.data(),id:e.id})))}function at(t,e){return w(v(),n=>{t(M(n))},e)}function it(t,e){return w(v(),n=>{t(M(n).filter(s=>Q(s.status)))},e)}function rt(t,e,n){return w(T(t),s=>{if(!s.exists()){e(null);return}e({...s.data(),id:s.id})},n)}function ot(t,e,n){return w(E(O(t),C("createdAt","asc")),s=>{e(s.docs.map(a=>({...a.data(),id:a.id})))},n)}function dt(t,e,n){return w(E(R(t),C("createdAt","asc")),s=>{e(s.docs.map(a=>({...a.data(),id:a.id})))},n)}async function ct(t,e){if(!t)throw new Error("missing task id");let n=e?.trim()||null;await y(t,"assignee",n)&&c("tasks.updateAssignee",{metadata:{taskId:t,assignee:n}})}async function ut(t,e){if(!t)throw new Error("missing task id");let n=e.trim();if(!n)throw new Error("missing title");await y(t,"title",n)&&c("tasks.updateTitle",{metadata:{taskId:t}})}async function mt(t,e){if(!t)throw new Error("missing task id");if(!e)throw new Error("missing status");let n=e.trim();await y(t,"status",n)&&c("tasks.updateStatus",{metadata:{taskId:t,status:e}})}async function lt(t,e){if(!t)throw new Error("missing task id");await y(t,"priority",e)&&c("tasks.updatePriority",{metadata:{taskId:t,priority:e}})}async function ft(t,e){if(!t)throw new Error("missing task id");let n=L(e);await y(t,"targetLaunchDate",n)&&c("tasks.updateTargetLaunchDate",{metadata:{taskId:t}})}async function pt(t,e){if(!t)throw new Error("missing task id");await A(T(t),{description:e,updatedAt:u(),updatedBy:window.firebase.user.email||""}),c("tasks.updateDescription",{metadata:{taskId:t}})}async function gt(t,e){if(!t)throw new Error("missing task id");if(!e?.src)throw new Error("missing attachment file");let n=window.firebase.db,s=T(t),a=window.firebase.user.email||"",i={...e,id:g(R(t)).id,attachedAt:p.now(),attachedBy:a};return await h(n,async d=>{let r=await d.get(s);if(!r.exists())throw new Error("task not found");let o=r.data(),m=S(o.attachments);d.update(s,{attachments:[...m,i],updatedAt:u(),updatedBy:a})}),c("tasks.attachment.add",{metadata:{taskId:t,attachmentId:i.id,filename:i.filename||i.src}}),i}async function wt(t,e){if(!t||!e)throw new Error("missing task or attachment id");let n=window.firebase.db,s=T(t),a=window.firebase.user.email||"",i;await h(n,async r=>{let o=await r.get(s);if(!o.exists())throw new Error("task not found");let m=o.data(),l=S(m.attachments);return i=l.find(f=>f.id===e),i?(r.update(s,{attachments:l.filter(f=>f.id!==e),updatedAt:u(),updatedBy:a}),!0):!1})&&c("tasks.attachment.remove",{metadata:{taskId:t,attachmentId:e,filename:i?.filename||i?.src||""}})}async function y(t,e,n){let s=window.firebase.db,a=T(t),i=G(t),d=window.firebase.user.email||"";return h(s,async r=>{let o=await r.get(a);if(!o.exists())throw new Error("task not found");let m=o.data(),l=U(m[e]),f=U(n);return Z(l,f)?!1:(r.update(a,{[e]:f,updatedAt:u(),updatedBy:d}),r.set(i,{id:i.id,taskId:t,type:"metadata",field:e,oldValue:l,newValue:f,createdAt:u(),createdBy:d}),!0)})}function U(t){return t instanceof p||typeof t=="string"?t:null}function Z(t,e){return t instanceof p&&e instanceof p?t.toMillis()===e.toMillis():t===e}function S(t){return Array.isArray(t)?t.filter(e=>!!(e?.id&&e?.src)):[]}async function Tt(t,e,n,s){if(!t)throw new Error("missing task id");if(!e)throw new Error("missing comment content");let a=z(e),i=typeof e=="string"?e:F(e);if(!i.trim()&&!a)throw new Error("missing comment content");let d=g(O(t)),r=d.id,o=(s?.mentions||[]).map(m=>m.toLowerCase());return await _(d,{id:r,taskId:t,parentId:n||null,content:i,body:a,mentions:o,createdAt:u(),createdBy:window.firebase.user.email||"",history:[]}),c("tasks.comment.add",{metadata:{taskId:t,commentId:r,parentId:n||null,mentions:o}}),r}async function kt(t,e,n,s){if(!t||!e)throw new Error("missing task or comment id");if(!n)throw new Error("missing comment content");let a=z(n),i=typeof n=="string"?n:F(n);if(!i.trim()&&!a)throw new Error("missing comment content");let d=P(t,e),r=await x(d);if(!r.exists())throw new Error("comment not found");let o=r.data(),m=(s?.mentions||[]).map(l=>l.toLowerCase());await A(d,{content:i,body:a,mentions:m,updatedAt:u(),updatedBy:window.firebase.user.email||"",isDeleted:!1,history:D({action:"edit",content:o.content,body:o.body||null,changedAt:p.now(),changedBy:window.firebase.user.email||""})}),c("tasks.comment.edit",{metadata:{taskId:t,commentId:e,mentions:m}})}function z(t){return typeof t=="string"?null:t}function F(t){return t?.blocks?.length?t.blocks.map(e=>$(e)).filter(Boolean).join(`
|
|
2
|
+
`).trim():""}function $(t){switch(t.type){case"paragraph":case"heading":case"quote":return V(t.data?.text||"");case"orderedList":case"unorderedList":return(t.data?.items||[]).map(e=>X(e)).filter(Boolean).join(`
|
|
3
|
+
`);case"image":return t.data?.file?.alt||t.data?.file?.url||"";default:return""}}function X(t){let e=[V(t.content||"")];return t.items?.length&&e.push(t.items.map(n=>X(n)).filter(Boolean).join(`
|
|
4
|
+
`)),e.filter(Boolean).join(`
|
|
5
|
+
`)}function V(t){return t.replace(/<[^>]+>/g,"")}async function ht(t,e){if(!t||!e)throw new Error("missing task or comment id");let n=P(t,e),s=await x(n);if(!s.exists())throw new Error("comment not found");let a=s.data();await A(n,{content:"",isDeleted:!0,deletedAt:u(),deletedBy:window.firebase.user.email||"",history:D({action:"delete",content:a.content,changedAt:p.now(),changedBy:window.firebase.user.email||""})}),c("tasks.comment.delete",{metadata:{taskId:t,commentId:e}})}export{st as a,Q as b,W as c,at as d,it as e,rt as f,ot as g,dt as h,ct as i,ut as j,mt as k,lt as l,ft as m,pt as n,gt as o,wt as p,Tt as q,kt as r,ht as s};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{B as
|
|
2
|
-
${this.customData.serverResponse}`:this.message=this._baseMessage}},p;(function(t){t.UNKNOWN="unknown",t.OBJECT_NOT_FOUND="object-not-found",t.BUCKET_NOT_FOUND="bucket-not-found",t.PROJECT_NOT_FOUND="project-not-found",t.QUOTA_EXCEEDED="quota-exceeded",t.UNAUTHENTICATED="unauthenticated",t.UNAUTHORIZED="unauthorized",t.UNAUTHORIZED_APP="unauthorized-app",t.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",t.INVALID_CHECKSUM="invalid-checksum",t.CANCELED="canceled",t.INVALID_EVENT_NAME="invalid-event-name",t.INVALID_URL="invalid-url",t.INVALID_DEFAULT_BUCKET="invalid-default-bucket",t.NO_DEFAULT_BUCKET="no-default-bucket",t.CANNOT_SLICE_BLOB="cannot-slice-blob",t.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",t.NO_DOWNLOAD_URL="no-download-url",t.INVALID_ARGUMENT="invalid-argument",t.INVALID_ARGUMENT_COUNT="invalid-argument-count",t.APP_DELETED="app-deleted",t.INVALID_ROOT_OPERATION="invalid-root-operation",t.INVALID_FORMAT="invalid-format",t.INTERNAL_ERROR="internal-error",t.UNSUPPORTED_ENVIRONMENT="unsupported-environment"})(p||(p={}));function ee(t){return"storage/"+t}function le(){let t="An unknown error occurred, please check the error payload for server response.";return new g(p.UNKNOWN,t)}function it(t){return new g(p.OBJECT_NOT_FOUND,"Object '"+t+"' does not exist.")}function at(t){return new g(p.QUOTA_EXCEEDED,"Quota for bucket '"+t+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function ut(){let t="User is not authenticated, please authenticate using Firebase Authentication and try again.";return new g(p.UNAUTHENTICATED,t)}function lt(){return new g(p.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}function ct(t){return new g(p.UNAUTHORIZED,"User does not have permission to access '"+t+"'.")}function Fe(){return new g(p.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function Be(){return new g(p.CANCELED,"User canceled the upload/download.")}function ht(t){return new g(p.INVALID_URL,"Invalid URL '"+t+"'.")}function dt(t){return new g(p.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+t+"'.")}function ft(){return new g(p.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+Le+"' property when initializing the app?")}function Me(){return new g(p.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function pt(){return new g(p.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function _t(t){return new g(p.UNSUPPORTED_ENVIRONMENT,`${t} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}function ne(t){return new g(p.INVALID_ARGUMENT,t)}function qe(){return new g(p.APP_DELETED,"The Firebase app was deleted.")}function gt(t){return new g(p.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function $(t,e){return new g(p.INVALID_FORMAT,"String does not match format '"+t+"': "+e)}function q(t){throw new g(p.INTERNAL_ERROR,"Internal error: "+t)}var k=class t{constructor(e,n){this.bucket=e,this.path_=n}get path(){return this.path_}get isRoot(){return this.path.length===0}fullServerUrl(){let e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,n){let s;try{s=t.makeFromUrl(e,n)}catch{return new t(e,"")}if(s.path==="")return s;throw dt(e)}static makeFromUrl(e,n){let s=null,r="([A-Za-z0-9.\\-_]+)";function o(b){b.path.charAt(b.path.length-1)==="/"&&(b.path_=b.path_.slice(0,-1))}let i="(/(.*))?$",u=new RegExp("^gs://"+r+i,"i"),a={bucket:1,path:3};function l(b){b.path_=decodeURIComponent(b.path)}let c="v[A-Za-z0-9_]+",d=n.replace(/[.]/g,"\\."),f="(/([^?#]*).*)?$",_=new RegExp(`^https?://${d}/${c}/b/${r}/o${f}`,"i"),h={bucket:1,path:3},T=n===De?"(?:storage.googleapis.com|storage.cloud.google.com)":n,m="([^?#]*)",U=new RegExp(`^https?://${T}/${r}/${m}`,"i"),R=[{regex:u,indices:a,postModify:o},{regex:_,indices:h,postModify:l},{regex:U,indices:{bucket:1,path:2},postModify:l}];for(let b=0;b<R.length;b++){let C=R[b],v=C.regex.exec(e);if(v){let Y=v[C.indices.bucket],M=v[C.indices.path];M||(M=""),s=new t(Y,M),C.postModify(s);break}}if(s==null)throw ht(e);return s}},se=class{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}};function mt(t,e,n){let s=1,r=null,o=null,i=!1,u=0;function a(){return u===2}let l=!1;function c(...m){l||(l=!0,e.apply(null,m))}function d(m){r=setTimeout(()=>{r=null,t(_,a())},m)}function f(){o&&clearTimeout(o)}function _(m,...U){if(l){f();return}if(m){f(),c.call(null,m,...U);return}if(a()||i){f(),c.call(null,m,...U);return}s<64&&(s*=2);let R;u===1?(u=2,R=0):R=(s+Math.random())*1e3,d(R)}let h=!1;function T(m){h||(h=!0,f(),!l&&(r!==null?(m||(u=2),clearTimeout(r),d(0)):m||(u=1)))}return d(0),o=setTimeout(()=>{i=!0,T(!0)},n),T}function bt(t){t(!1)}function wt(t){return t!==void 0}function Rt(t){return typeof t=="function"}function Tt(t){return typeof t=="object"&&!Array.isArray(t)}function ce(t){return typeof t=="string"||t instanceof String}function Ae(t){return he()&&t instanceof Blob}function he(){return typeof Blob<"u"}function Oe(t,e,n,s){if(s<e)throw ne(`Invalid value for '${t}'. Expected ${e} or greater.`);if(s>n)throw ne(`Invalid value for '${t}'. Expected ${n} or less.`)}function z(t,e,n){let s=e;return n==null&&(s=`https://${e}`),`${n}://${s}/v0${t}`}function yt(t){let e=encodeURIComponent,n="?";for(let s in t)if(t.hasOwnProperty(s)){let r=e(s)+"="+e(t[s]);n=n+r+"&"}return n=n.slice(0,-1),n}var P;(function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"})(P||(P={}));function $e(t,e){let n=t>=500&&t<600,r=[408,429].indexOf(t)!==-1,o=e.indexOf(t)!==-1;return n||r||o}var re=class{constructor(e,n,s,r,o,i,u,a,l,c,d,f=!0,_=!1){this.url_=e,this.method_=n,this.headers_=s,this.body_=r,this.successCodes_=o,this.additionalRetryCodes_=i,this.callback_=u,this.errorCallback_=a,this.timeout_=l,this.progressCallback_=c,this.connectionFactory_=d,this.retry=f,this.isUsingEmulator=_,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((h,T)=>{this.resolve_=h,this.reject_=T,this.start_()})}start_(){let e=(s,r)=>{if(r){s(!1,new D(!1,null,!0));return}let o=this.connectionFactory_();this.pendingConnection_=o;let i=u=>{let a=u.loaded,l=u.lengthComputable?u.total:-1;this.progressCallback_!==null&&this.progressCallback_(a,l)};this.progressCallback_!==null&&o.addUploadProgressListener(i),o.send(this.url_,this.method_,this.isUsingEmulator,this.body_,this.headers_).then(()=>{this.progressCallback_!==null&&o.removeUploadProgressListener(i),this.pendingConnection_=null;let u=o.getErrorCode()===P.NO_ERROR,a=o.getStatus();if(!u||$e(a,this.additionalRetryCodes_)&&this.retry){let c=o.getErrorCode()===P.ABORT;s(!1,new D(!1,null,c));return}let l=this.successCodes_.indexOf(a)!==-1;s(!0,new D(l,o))})},n=(s,r)=>{let o=this.resolve_,i=this.reject_,u=r.connection;if(r.wasSuccessCode)try{let a=this.callback_(u,u.getResponse());wt(a)?o(a):o()}catch(a){i(a)}else if(u!==null){let a=le();a.serverResponse=u.getErrorText(),this.errorCallback_?i(this.errorCallback_(u,a)):i(a)}else if(r.canceled){let a=this.appDelete_?qe():Be();i(a)}else{let a=Fe();i(a)}};this.canceled_?n(!1,new D(!1,null,!0)):this.backoffId_=mt(e,n,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,this.backoffId_!==null&&bt(this.backoffId_),this.pendingConnection_!==null&&this.pendingConnection_.abort()}},D=class{constructor(e,n,s){this.wasSuccessCode=e,this.connection=n,this.canceled=!!s}};function kt(t,e){e!==null&&e.length>0&&(t.Authorization="Firebase "+e)}function Et(t,e){t["X-Firebase-Storage-Version"]="webjs/"+(e??"AppManager")}function Ut(t,e){e&&(t["X-Firebase-GMPID"]=e)}function It(t,e){e!==null&&(t["X-Firebase-AppCheck"]=e)}function xt(t,e,n,s,r,o,i=!0,u=!1){let a=yt(t.urlParams),l=t.url+a,c=Object.assign({},t.headers);return Ut(c,e),kt(c,n),Et(c,o),It(c,s),new re(l,t.method,c,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,r,i,u)}function At(){return typeof BlobBuilder<"u"?BlobBuilder:typeof WebKitBlobBuilder<"u"?WebKitBlobBuilder:void 0}function Ot(...t){let e=At();if(e!==void 0){let n=new e;for(let s=0;s<t.length;s++)n.append(t[s]);return n.getBlob()}else{if(he())return new Blob(t);throw new g(p.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}}function St(t,e,n){return t.webkitSlice?t.webkitSlice(e,n):t.mozSlice?t.mozSlice(e,n):t.slice?t.slice(e,n):null}function Pt(t){if(typeof atob>"u")throw _t("base-64");return atob(t)}var E={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"},H=class{constructor(e,n){this.data=e,this.contentType=n||null}};function Ct(t,e){switch(t){case E.RAW:return new H(He(e));case E.BASE64:case E.BASE64URL:return new H(je(t,e));case E.DATA_URL:return new H(Nt(e),Dt(e))}throw le()}function He(t){let e=[];for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);if(s<=127)e.push(s);else if(s<=2047)e.push(192|s>>6,128|s&63);else if((s&64512)===55296)if(!(n<t.length-1&&(t.charCodeAt(n+1)&64512)===56320))e.push(239,191,189);else{let o=s,i=t.charCodeAt(++n);s=65536|(o&1023)<<10|i&1023,e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63)}else(s&64512)===56320?e.push(239,191,189):e.push(224|s>>12,128|s>>6&63,128|s&63)}return new Uint8Array(e)}function vt(t){let e;try{e=decodeURIComponent(t)}catch{throw $(E.DATA_URL,"Malformed data URL.")}return He(e)}function je(t,e){switch(t){case E.BASE64:{let r=e.indexOf("-")!==-1,o=e.indexOf("_")!==-1;if(r||o)throw $(t,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?");break}case E.BASE64URL:{let r=e.indexOf("+")!==-1,o=e.indexOf("/")!==-1;if(r||o)throw $(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/");break}}let n;try{n=Pt(e)}catch(r){throw r.message.includes("polyfill")?r:$(t,"Invalid character found")}let s=new Uint8Array(n.length);for(let r=0;r<n.length;r++)s[r]=n.charCodeAt(r);return s}var V=class{constructor(e){this.base64=!1,this.contentType=null;let n=e.match(/^data:([^,]+)?,/);if(n===null)throw $(E.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");let s=n[1]||null;s!=null&&(this.base64=Lt(s,";base64"),this.contentType=this.base64?s.substring(0,s.length-7):s),this.rest=e.substring(e.indexOf(",")+1)}};function Nt(t){let e=new V(t);return e.base64?je(E.BASE64,e.rest):vt(e.rest)}function Dt(t){return new V(t).contentType}function Lt(t,e){return t.length>=e.length?t.substring(t.length-e.length)===e:!1}var X=class t{constructor(e,n){let s=0,r="";Ae(e)?(this.data_=e,s=e.size,r=e.type):e instanceof ArrayBuffer?(n?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),s=this.data_.length):e instanceof Uint8Array&&(n?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),s=e.length),this.size_=s,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,n){if(Ae(this.data_)){let s=this.data_,r=St(s,e,n);return r===null?null:new t(r)}else{let s=new Uint8Array(this.data_.buffer,e,n-e);return new t(s,!0)}}static getBlob(...e){if(he()){let n=e.map(s=>s instanceof t?s.data_:s);return new t(Ot.apply(null,n))}else{let n=e.map(i=>ce(i)?Ct(E.RAW,i).data:i.data_),s=0;n.forEach(i=>{s+=i.byteLength});let r=new Uint8Array(s),o=0;return n.forEach(i=>{for(let u=0;u<i.length;u++)r[o++]=i[u]}),new t(r,!0)}}uploadData(){return this.data_}};function Ft(t){let e;try{e=JSON.parse(t)}catch{return null}return Tt(e)?e:null}function Bt(t){if(t.length===0)return null;let e=t.lastIndexOf("/");return e===-1?"":t.slice(0,e)}function Mt(t,e){let n=e.split("/").filter(s=>s.length>0).join("/");return t.length===0?n:t+"/"+n}function ze(t){let e=t.lastIndexOf("/",t.length-2);return e===-1?t:t.slice(e+1)}function qt(t,e){return e}var w=class{constructor(e,n,s,r){this.server=e,this.local=n||e,this.writable=!!s,this.xform=r||qt}},W=null;function $t(t){return!ce(t)||t.length<2?t:ze(t)}function de(){if(W)return W;let t=[];t.push(new w("bucket")),t.push(new w("generation")),t.push(new w("metageneration")),t.push(new w("name","fullPath",!0));function e(o,i){return $t(i)}let n=new w("name");n.xform=e,t.push(n);function s(o,i){return i!==void 0?Number(i):i}let r=new w("size");return r.xform=s,t.push(r),t.push(new w("timeCreated")),t.push(new w("updated")),t.push(new w("md5Hash",null,!0)),t.push(new w("cacheControl",null,!0)),t.push(new w("contentDisposition",null,!0)),t.push(new w("contentEncoding",null,!0)),t.push(new w("contentLanguage",null,!0)),t.push(new w("contentType",null,!0)),t.push(new w("metadata","customMetadata",!0)),W=t,W}function Ht(t,e){function n(){let s=t.bucket,r=t.fullPath,o=new k(s,r);return e._makeStorageReference(o)}Object.defineProperty(t,"ref",{get:n})}function jt(t,e,n){let s={};s.type="file";let r=n.length;for(let o=0;o<r;o++){let i=n[o];s[i.local]=i.xform(s,e[i.server])}return Ht(s,t),s}function zt(t,e,n){let s=Ft(e);return s===null?null:jt(t,s,n)}function fe(t,e){let n={},s=e.length;for(let r=0;r<s;r++){let o=e[r];o.writable&&(n[o.server]=t[o.local])}return JSON.stringify(n)}var x=class{constructor(e,n,s,r){this.url=e,this.method=n,this.handler=s,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}};function O(t){if(!t)throw le()}function K(t,e){function n(s,r){let o=zt(t,r,e);return O(o!==null),o}return n}function G(t){function e(n,s){let r;return n.getStatus()===401?n.getErrorText().includes("Firebase App Check token is invalid")?r=lt():r=ut():n.getStatus()===402?r=at(t.bucket):n.getStatus()===403?r=ct(t.path):r=s,r.status=n.getStatus(),r.serverResponse=s.serverResponse,r}return e}function pe(t){let e=G(t);function n(s,r){let o=e(s,r);return s.getStatus()===404&&(o=it(t.path)),o.serverResponse=r.serverResponse,o}return n}function Ge(t,e,n){let s=e.fullServerUrl(),r=z(s,t.host,t._protocol),o="GET",i=t.maxOperationRetryTime,u=new x(r,o,K(t,n),i);return u.errorHandler=pe(e),u}function Gt(t,e,n,s){let r=e.fullServerUrl(),o=z(r,t.host,t._protocol),i="PATCH",u=fe(n,s),a={"Content-Type":"application/json; charset=utf-8"},l=t.maxOperationRetryTime,c=new x(o,i,K(t,s),l);return c.headers=a,c.body=u,c.errorHandler=pe(e),c}function Wt(t,e){let n=e.fullServerUrl(),s=z(n,t.host,t._protocol),r="DELETE",o=t.maxOperationRetryTime;function i(a,l){}let u=new x(s,r,i,o);return u.successCodes=[200,204],u.errorHandler=pe(e),u}function Vt(t,e){return t&&t.contentType||e&&e.type()||"application/octet-stream"}function We(t,e,n){let s=Object.assign({},n);return s.fullPath=t.path,s.size=e.size(),s.contentType||(s.contentType=Vt(null,e)),s}function Xt(t,e,n,s,r){let o=e.bucketOnlyServerUrl(),i={"X-Goog-Upload-Protocol":"multipart"};function u(){let R="";for(let b=0;b<2;b++)R=R+Math.random().toString().slice(2);return R}let a=u();i["Content-Type"]="multipart/related; boundary="+a;let l=We(e,s,r),c=fe(l,n),d="--"+a+`\r
|
|
1
|
+
import{B as Ue,C as Ie,D as xe,E as Ae,G as Oe,H as ee,c as we,e as Q,f as Te,g as Re,h as ye,p as ke,x as S,y as Ee}from"./chunk-DTMZLUNY.js";var Fe="firebasestorage.googleapis.com",Be="storageBucket",ot=120*1e3,it=600*1e3,at=1e3;var g=class t extends ke{constructor(e,n,s=0){super(te(e),`Firebase Storage: ${n} (${te(e)})`),this.status_=s,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,t.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return te(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}
|
|
2
|
+
${this.customData.serverResponse}`:this.message=this._baseMessage}},p;(function(t){t.UNKNOWN="unknown",t.OBJECT_NOT_FOUND="object-not-found",t.BUCKET_NOT_FOUND="bucket-not-found",t.PROJECT_NOT_FOUND="project-not-found",t.QUOTA_EXCEEDED="quota-exceeded",t.UNAUTHENTICATED="unauthenticated",t.UNAUTHORIZED="unauthorized",t.UNAUTHORIZED_APP="unauthorized-app",t.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",t.INVALID_CHECKSUM="invalid-checksum",t.CANCELED="canceled",t.INVALID_EVENT_NAME="invalid-event-name",t.INVALID_URL="invalid-url",t.INVALID_DEFAULT_BUCKET="invalid-default-bucket",t.NO_DEFAULT_BUCKET="no-default-bucket",t.CANNOT_SLICE_BLOB="cannot-slice-blob",t.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",t.NO_DOWNLOAD_URL="no-download-url",t.INVALID_ARGUMENT="invalid-argument",t.INVALID_ARGUMENT_COUNT="invalid-argument-count",t.APP_DELETED="app-deleted",t.INVALID_ROOT_OPERATION="invalid-root-operation",t.INVALID_FORMAT="invalid-format",t.INTERNAL_ERROR="internal-error",t.UNSUPPORTED_ENVIRONMENT="unsupported-environment"})(p||(p={}));function te(t){return"storage/"+t}function ce(){let t="An unknown error occurred, please check the error payload for server response.";return new g(p.UNKNOWN,t)}function ut(t){return new g(p.OBJECT_NOT_FOUND,"Object '"+t+"' does not exist.")}function lt(t){return new g(p.QUOTA_EXCEEDED,"Quota for bucket '"+t+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function ct(){let t="User is not authenticated, please authenticate using Firebase Authentication and try again.";return new g(p.UNAUTHENTICATED,t)}function ht(){return new g(p.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project.")}function dt(t){return new g(p.UNAUTHORIZED,"User does not have permission to access '"+t+"'.")}function Me(){return new g(p.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function qe(){return new g(p.CANCELED,"User canceled the upload/download.")}function ft(t){return new g(p.INVALID_URL,"Invalid URL '"+t+"'.")}function pt(t){return new g(p.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+t+"'.")}function _t(){return new g(p.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+Be+"' property when initializing the app?")}function $e(){return new g(p.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function gt(){return new g(p.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function mt(t){return new g(p.UNSUPPORTED_ENVIRONMENT,`${t} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`)}function se(t){return new g(p.INVALID_ARGUMENT,t)}function He(){return new g(p.APP_DELETED,"The Firebase app was deleted.")}function bt(t){return new g(p.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function $(t,e){return new g(p.INVALID_FORMAT,"String does not match format '"+t+"': "+e)}function q(t){throw new g(p.INTERNAL_ERROR,"Internal error: "+t)}var k=class t{constructor(e,n){this.bucket=e,this.path_=n}get path(){return this.path_}get isRoot(){return this.path.length===0}fullServerUrl(){let e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){return"/b/"+encodeURIComponent(this.bucket)+"/o"}static makeFromBucketSpec(e,n){let s;try{s=t.makeFromUrl(e,n)}catch{return new t(e,"")}if(s.path==="")return s;throw pt(e)}static makeFromUrl(e,n){let s=null,r="([A-Za-z0-9.\\-_]+)";function o(b){b.path.charAt(b.path.length-1)==="/"&&(b.path_=b.path_.slice(0,-1))}let i="(/(.*))?$",u=new RegExp("^gs://"+r+i,"i"),a={bucket:1,path:3};function l(b){b.path_=decodeURIComponent(b.path)}let c="v[A-Za-z0-9_]+",d=n.replace(/[.]/g,"\\."),f="(/([^?#]*).*)?$",_=new RegExp(`^https?://${d}/${c}/b/${r}/o${f}`,"i"),h={bucket:1,path:3},R=n===Fe?"(?:storage.googleapis.com|storage.cloud.google.com)":n,m="([^?#]*)",U=new RegExp(`^https?://${R}/${r}/${m}`,"i"),T=[{regex:u,indices:a,postModify:o},{regex:_,indices:h,postModify:l},{regex:U,indices:{bucket:1,path:2},postModify:l}];for(let b=0;b<T.length;b++){let C=T[b],v=C.regex.exec(e);if(v){let Z=v[C.indices.bucket],M=v[C.indices.path];M||(M=""),s=new t(Z,M),C.postModify(s);break}}if(s==null)throw ft(e);return s}},re=class{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}};function wt(t,e,n){let s=1,r=null,o=null,i=!1,u=0;function a(){return u===2}let l=!1;function c(...m){l||(l=!0,e.apply(null,m))}function d(m){r=setTimeout(()=>{r=null,t(_,a())},m)}function f(){o&&clearTimeout(o)}function _(m,...U){if(l){f();return}if(m){f(),c.call(null,m,...U);return}if(a()||i){f(),c.call(null,m,...U);return}s<64&&(s*=2);let T;u===1?(u=2,T=0):T=(s+Math.random())*1e3,d(T)}let h=!1;function R(m){h||(h=!0,f(),!l&&(r!==null?(m||(u=2),clearTimeout(r),d(0)):m||(u=1)))}return d(0),o=setTimeout(()=>{i=!0,R(!0)},n),R}function Tt(t){t(!1)}function Rt(t){return t!==void 0}function yt(t){return typeof t=="function"}function kt(t){return typeof t=="object"&&!Array.isArray(t)}function he(t){return typeof t=="string"||t instanceof String}function Se(t){return de()&&t instanceof Blob}function de(){return typeof Blob<"u"}function Pe(t,e,n,s){if(s<e)throw se(`Invalid value for '${t}'. Expected ${e} or greater.`);if(s>n)throw se(`Invalid value for '${t}'. Expected ${n} or less.`)}function G(t,e,n){let s=e;return n==null&&(s=`https://${e}`),`${n}://${s}/v0${t}`}function Et(t){let e=encodeURIComponent,n="?";for(let s in t)if(t.hasOwnProperty(s)){let r=e(s)+"="+e(t[s]);n=n+r+"&"}return n=n.slice(0,-1),n}var P;(function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"})(P||(P={}));function je(t,e){let n=t>=500&&t<600,r=[408,429].indexOf(t)!==-1,o=e.indexOf(t)!==-1;return n||r||o}var oe=class{constructor(e,n,s,r,o,i,u,a,l,c,d,f=!0,_=!1){this.url_=e,this.method_=n,this.headers_=s,this.body_=r,this.successCodes_=o,this.additionalRetryCodes_=i,this.callback_=u,this.errorCallback_=a,this.timeout_=l,this.progressCallback_=c,this.connectionFactory_=d,this.retry=f,this.isUsingEmulator=_,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((h,R)=>{this.resolve_=h,this.reject_=R,this.start_()})}start_(){let e=(s,r)=>{if(r){s(!1,new D(!1,null,!0));return}let o=this.connectionFactory_();this.pendingConnection_=o;let i=u=>{let a=u.loaded,l=u.lengthComputable?u.total:-1;this.progressCallback_!==null&&this.progressCallback_(a,l)};this.progressCallback_!==null&&o.addUploadProgressListener(i),o.send(this.url_,this.method_,this.isUsingEmulator,this.body_,this.headers_).then(()=>{this.progressCallback_!==null&&o.removeUploadProgressListener(i),this.pendingConnection_=null;let u=o.getErrorCode()===P.NO_ERROR,a=o.getStatus();if(!u||je(a,this.additionalRetryCodes_)&&this.retry){let c=o.getErrorCode()===P.ABORT;s(!1,new D(!1,null,c));return}let l=this.successCodes_.indexOf(a)!==-1;s(!0,new D(l,o))})},n=(s,r)=>{let o=this.resolve_,i=this.reject_,u=r.connection;if(r.wasSuccessCode)try{let a=this.callback_(u,u.getResponse());Rt(a)?o(a):o()}catch(a){i(a)}else if(u!==null){let a=ce();a.serverResponse=u.getErrorText(),this.errorCallback_?i(this.errorCallback_(u,a)):i(a)}else if(r.canceled){let a=this.appDelete_?He():qe();i(a)}else{let a=Me();i(a)}};this.canceled_?n(!1,new D(!1,null,!0)):this.backoffId_=wt(e,n,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,this.backoffId_!==null&&Tt(this.backoffId_),this.pendingConnection_!==null&&this.pendingConnection_.abort()}},D=class{constructor(e,n,s){this.wasSuccessCode=e,this.connection=n,this.canceled=!!s}};function Ut(t,e){e!==null&&e.length>0&&(t.Authorization="Firebase "+e)}function It(t,e){t["X-Firebase-Storage-Version"]="webjs/"+(e??"AppManager")}function xt(t,e){e&&(t["X-Firebase-GMPID"]=e)}function At(t,e){e!==null&&(t["X-Firebase-AppCheck"]=e)}function Ot(t,e,n,s,r,o,i=!0,u=!1){let a=Et(t.urlParams),l=t.url+a,c=Object.assign({},t.headers);return xt(c,e),Ut(c,n),It(c,o),At(c,s),new oe(l,t.method,c,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,r,i,u)}function St(){return typeof BlobBuilder<"u"?BlobBuilder:typeof WebKitBlobBuilder<"u"?WebKitBlobBuilder:void 0}function Pt(...t){let e=St();if(e!==void 0){let n=new e;for(let s=0;s<t.length;s++)n.append(t[s]);return n.getBlob()}else{if(de())return new Blob(t);throw new g(p.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}}function Ct(t,e,n){return t.webkitSlice?t.webkitSlice(e,n):t.mozSlice?t.mozSlice(e,n):t.slice?t.slice(e,n):null}function vt(t){if(typeof atob>"u")throw mt("base-64");return atob(t)}var E={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"},H=class{constructor(e,n){this.data=e,this.contentType=n||null}};function Nt(t,e){switch(t){case E.RAW:return new H(Ge(e));case E.BASE64:case E.BASE64URL:return new H(ze(t,e));case E.DATA_URL:return new H(Lt(e),Ft(e))}throw ce()}function Ge(t){let e=[];for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);if(s<=127)e.push(s);else if(s<=2047)e.push(192|s>>6,128|s&63);else if((s&64512)===55296)if(!(n<t.length-1&&(t.charCodeAt(n+1)&64512)===56320))e.push(239,191,189);else{let o=s,i=t.charCodeAt(++n);s=65536|(o&1023)<<10|i&1023,e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63)}else(s&64512)===56320?e.push(239,191,189):e.push(224|s>>12,128|s>>6&63,128|s&63)}return new Uint8Array(e)}function Dt(t){let e;try{e=decodeURIComponent(t)}catch{throw $(E.DATA_URL,"Malformed data URL.")}return Ge(e)}function ze(t,e){switch(t){case E.BASE64:{let r=e.indexOf("-")!==-1,o=e.indexOf("_")!==-1;if(r||o)throw $(t,"Invalid character '"+(r?"-":"_")+"' found: is it base64url encoded?");break}case E.BASE64URL:{let r=e.indexOf("+")!==-1,o=e.indexOf("/")!==-1;if(r||o)throw $(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/");break}}let n;try{n=vt(e)}catch(r){throw r.message.includes("polyfill")?r:$(t,"Invalid character found")}let s=new Uint8Array(n.length);for(let r=0;r<n.length;r++)s[r]=n.charCodeAt(r);return s}var X=class{constructor(e){this.base64=!1,this.contentType=null;let n=e.match(/^data:([^,]+)?,/);if(n===null)throw $(E.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");let s=n[1]||null;s!=null&&(this.base64=Bt(s,";base64"),this.contentType=this.base64?s.substring(0,s.length-7):s),this.rest=e.substring(e.indexOf(",")+1)}};function Lt(t){let e=new X(t);return e.base64?ze(E.BASE64,e.rest):Dt(e.rest)}function Ft(t){return new X(t).contentType}function Bt(t,e){return t.length>=e.length?t.substring(t.length-e.length)===e:!1}var V=class t{constructor(e,n){let s=0,r="";Se(e)?(this.data_=e,s=e.size,r=e.type):e instanceof ArrayBuffer?(n?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),s=this.data_.length):e instanceof Uint8Array&&(n?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),s=e.length),this.size_=s,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,n){if(Se(this.data_)){let s=this.data_,r=Ct(s,e,n);return r===null?null:new t(r)}else{let s=new Uint8Array(this.data_.buffer,e,n-e);return new t(s,!0)}}static getBlob(...e){if(de()){let n=e.map(s=>s instanceof t?s.data_:s);return new t(Pt.apply(null,n))}else{let n=e.map(i=>he(i)?Nt(E.RAW,i).data:i.data_),s=0;n.forEach(i=>{s+=i.byteLength});let r=new Uint8Array(s),o=0;return n.forEach(i=>{for(let u=0;u<i.length;u++)r[o++]=i[u]}),new t(r,!0)}}uploadData(){return this.data_}};function Mt(t){let e;try{e=JSON.parse(t)}catch{return null}return kt(e)?e:null}function qt(t){if(t.length===0)return null;let e=t.lastIndexOf("/");return e===-1?"":t.slice(0,e)}function $t(t,e){let n=e.split("/").filter(s=>s.length>0).join("/");return t.length===0?n:t+"/"+n}function We(t){let e=t.lastIndexOf("/",t.length-2);return e===-1?t:t.slice(e+1)}function Ht(t,e){return e}var w=class{constructor(e,n,s,r){this.server=e,this.local=n||e,this.writable=!!s,this.xform=r||Ht}},W=null;function jt(t){return!he(t)||t.length<2?t:We(t)}function fe(){if(W)return W;let t=[];t.push(new w("bucket")),t.push(new w("generation")),t.push(new w("metageneration")),t.push(new w("name","fullPath",!0));function e(o,i){return jt(i)}let n=new w("name");n.xform=e,t.push(n);function s(o,i){return i!==void 0?Number(i):i}let r=new w("size");return r.xform=s,t.push(r),t.push(new w("timeCreated")),t.push(new w("updated")),t.push(new w("md5Hash",null,!0)),t.push(new w("cacheControl",null,!0)),t.push(new w("contentDisposition",null,!0)),t.push(new w("contentEncoding",null,!0)),t.push(new w("contentLanguage",null,!0)),t.push(new w("contentType",null,!0)),t.push(new w("metadata","customMetadata",!0)),W=t,W}function Gt(t,e){function n(){let s=t.bucket,r=t.fullPath,o=new k(s,r);return e._makeStorageReference(o)}Object.defineProperty(t,"ref",{get:n})}function zt(t,e,n){let s={};s.type="file";let r=n.length;for(let o=0;o<r;o++){let i=n[o];s[i.local]=i.xform(s,e[i.server])}return Gt(s,t),s}function Wt(t,e,n){let s=Mt(e);return s===null?null:zt(t,s,n)}function pe(t,e){let n={},s=e.length;for(let r=0;r<s;r++){let o=e[r];o.writable&&(n[o.server]=t[o.local])}return JSON.stringify(n)}var x=class{constructor(e,n,s,r){this.url=e,this.method=n,this.handler=s,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}};function O(t){if(!t)throw ce()}function K(t,e){function n(s,r){let o=Wt(t,r,e);return O(o!==null),o}return n}function z(t){function e(n,s){let r;return n.getStatus()===401?n.getErrorText().includes("Firebase App Check token is invalid")?r=ht():r=ct():n.getStatus()===402?r=lt(t.bucket):n.getStatus()===403?r=dt(t.path):r=s,r.status=n.getStatus(),r.serverResponse=s.serverResponse,r}return e}function _e(t){let e=z(t);function n(s,r){let o=e(s,r);return s.getStatus()===404&&(o=ut(t.path)),o.serverResponse=r.serverResponse,o}return n}function Xe(t,e,n){let s=e.fullServerUrl(),r=G(s,t.host,t._protocol),o="GET",i=t.maxOperationRetryTime,u=new x(r,o,K(t,n),i);return u.errorHandler=_e(e),u}function Xt(t,e,n,s){let r=e.fullServerUrl(),o=G(r,t.host,t._protocol),i="PATCH",u=pe(n,s),a={"Content-Type":"application/json; charset=utf-8"},l=t.maxOperationRetryTime,c=new x(o,i,K(t,s),l);return c.headers=a,c.body=u,c.errorHandler=_e(e),c}function Vt(t,e){let n=e.fullServerUrl(),s=G(n,t.host,t._protocol),r="DELETE",o=t.maxOperationRetryTime;function i(a,l){}let u=new x(s,r,i,o);return u.successCodes=[200,204],u.errorHandler=_e(e),u}function Kt(t,e){return t&&t.contentType||e&&e.type()||"application/octet-stream"}function Ve(t,e,n){let s=Object.assign({},n);return s.fullPath=t.path,s.size=e.size(),s.contentType||(s.contentType=Kt(null,e)),s}function Yt(t,e,n,s,r){let o=e.bucketOnlyServerUrl(),i={"X-Goog-Upload-Protocol":"multipart"};function u(){let T="";for(let b=0;b<2;b++)T=T+Math.random().toString().slice(2);return T}let a=u();i["Content-Type"]="multipart/related; boundary="+a;let l=Ve(e,s,r),c=pe(l,n),d="--"+a+`\r
|
|
3
3
|
Content-Type: application/json; charset=utf-8\r
|
|
4
4
|
\r
|
|
5
5
|
`+c+`\r
|
|
@@ -7,4 +7,4 @@ Content-Type: application/json; charset=utf-8\r
|
|
|
7
7
|
Content-Type: `+l.contentType+`\r
|
|
8
8
|
\r
|
|
9
9
|
`,f=`\r
|
|
10
|
-
--`+a+"--",_=X.getBlob(d,s,f);if(_===null)throw Me();let h={name:l.fullPath},T=z(o,t.host,t._protocol),m="POST",U=t.maxUploadRetryTime,I=new x(T,m,K(t,n),U);return I.urlParams=h,I.headers=i,I.body=_.uploadData(),I.errorHandler=G(e),I}var L=class{constructor(e,n,s,r){this.current=e,this.total=n,this.finalized=!!s,this.metadata=r||null}};function _e(t,e){let n=null;try{n=t.getResponseHeader("X-Goog-Upload-Status")}catch{O(!1)}return O(!!n&&(e||["active"]).indexOf(n)!==-1),n}function Kt(t,e,n,s,r){let o=e.bucketOnlyServerUrl(),i=We(e,s,r),u={name:i.fullPath},a=z(o,t.host,t._protocol),l="POST",c={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${s.size()}`,"X-Goog-Upload-Header-Content-Type":i.contentType,"Content-Type":"application/json; charset=utf-8"},d=fe(i,n),f=t.maxUploadRetryTime;function _(T){_e(T);let m;try{m=T.getResponseHeader("X-Goog-Upload-URL")}catch{O(!1)}return O(ce(m)),m}let h=new x(a,l,_,f);return h.urlParams=u,h.headers=c,h.body=d,h.errorHandler=G(e),h}function Yt(t,e,n,s){let r={"X-Goog-Upload-Command":"query"};function o(l){let c=_e(l,["active","final"]),d=null;try{d=l.getResponseHeader("X-Goog-Upload-Size-Received")}catch{O(!1)}d||O(!1);let f=Number(d);return O(!isNaN(f)),new L(f,s.size(),c==="final")}let i="POST",u=t.maxUploadRetryTime,a=new x(n,i,o,u);return a.headers=r,a.errorHandler=G(e),a}var Se=256*1024;function Zt(t,e,n,s,r,o,i,u){let a=new L(0,0);if(i?(a.current=i.current,a.total=i.total):(a.current=0,a.total=s.size()),s.size()!==a.total)throw pt();let l=a.total-a.current,c=l;r>0&&(c=Math.min(c,r));let d=a.current,f=d+c,_="";c===0?_="finalize":l===c?_="upload, finalize":_="upload";let h={"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":`${a.current}`},T=s.slice(d,f);if(T===null)throw Me();function m(b,C){let v=_e(b,["active","final"]),Y=a.current+c,M=s.size(),Z;return v==="final"?Z=K(e,o)(b,C):Z=null,new L(Y,M,v==="final",Z)}let U="POST",I=e.maxUploadRetryTime,R=new x(n,U,m,I);return R.headers=h,R.body=T.uploadData(),R.progressCallback=u||null,R.errorHandler=G(t),R}var y={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function te(t){switch(t){case"running":case"pausing":case"canceling":return y.RUNNING;case"paused":return y.PAUSED;case"success":return y.SUCCESS;case"canceled":return y.CANCELED;case"error":return y.ERROR;default:return y.ERROR}}var oe=class{constructor(e,n,s){if(Rt(e)||n!=null||s!=null)this.next=e,this.error=n??void 0,this.complete=s??void 0;else{let o=e;this.next=o.next,this.error=o.error,this.complete=o.complete}}};function N(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}var Pe=null,ie=class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=P.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=P.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=P.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,n,s,r,o){if(this.sent_)throw q("cannot .send() more than once");if(J(e)&&s&&(this.xhr_.withCredentials=!0),this.sent_=!0,this.xhr_.open(n,e,!0),o!==void 0)for(let i in o)o.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,o[i].toString());return r!==void 0?this.xhr_.send(r):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw q("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw q("cannot .getStatus() before sending");try{return this.xhr_.status}catch{return-1}}getResponse(){if(!this.sent_)throw q("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw q("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){this.xhr_.upload!=null&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){this.xhr_.upload!=null&&this.xhr_.upload.removeEventListener("progress",e)}},ae=class extends ie{initXhr(){this.xhr_.responseType="text"}};function A(){return Pe?Pe():new ae}var ue=class{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}constructor(e,n,s=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=n,this._metadata=s,this._mappings=de(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=r=>{if(this._request=void 0,this._chunkMultiplier=1,r._codeEquals(p.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{let o=this.isExponentialBackoffExpired();if($e(r.status,[]))if(o)r=Fe();else{this.sleepTime=Math.max(this.sleepTime*2,ot),this._needToFetchStatus=!0,this.completeTransitions_();return}this._error=r,this._transition("error")}},this._metadataErrorHandler=r=>{this._request=void 0,r._codeEquals(p.CANCELED)?this.completeTransitions_():(this._error=r,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((r,o)=>{this._resolve=r,this._reject=o,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){let e=this._transferred;return n=>this._updateProgress(e+n)}_shouldDoResumable(e){return e.size()>256*1024}_start(){this._state==="running"&&this._request===void 0&&(this._resumable?this._uploadUrl===void 0?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([n,s])=>{switch(this._state){case"running":e(n,s);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused");break}})}_createResumable(){this._resolveToken((e,n)=>{let s=Kt(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(s,A,e,n);this._request=r,r.getPromise().then(o=>{this._request=void 0,this._uploadUrl=o,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let e=this._uploadUrl;this._resolveToken((n,s)=>{let r=Yt(this._ref.storage,this._ref._location,e,this._blob),o=this._ref.storage._makeRequest(r,A,n,s);this._request=o,o.getPromise().then(i=>{i=i,this._request=void 0,this._updateProgress(i.current),this._needToFetchStatus=!1,i.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let e=Se*this._chunkMultiplier,n=new L(this._transferred,this._blob.size()),s=this._uploadUrl;this._resolveToken((r,o)=>{let i;try{i=Zt(this._ref._location,this._ref.storage,s,this._blob,e,this._mappings,n,this._makeProgressCallback())}catch(a){this._error=a,this._transition("error");return}let u=this._ref.storage._makeRequest(i,A,r,o,!1);this._request=u,u.getPromise().then(a=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(a.current),a.finalized?(this._metadata=a.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){Se*this._chunkMultiplier*2<32*1024*1024&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,n)=>{let s=Ge(this._ref.storage,this._ref._location,this._mappings),r=this._ref.storage._makeRequest(s,A,e,n);this._request=r,r.getPromise().then(o=>{this._request=void 0,this._metadata=o,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,n)=>{let s=Xt(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(s,A,e,n);this._request=r,r.getPromise().then(o=>{this._request=void 0,this._metadata=o,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){let n=this._transferred;this._transferred=e,this._transferred!==n&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,this._request!==void 0?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":let n=this._state==="paused";this._state=e,n&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=Be(),this._state=e,this._notifyObservers();break;case"error":this._state=e,this._notifyObservers();break;case"success":this._state=e,this._notifyObservers();break}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start();break}}get snapshot(){let e=te(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,n,s,r){let o=new oe(n||void 0,s||void 0,r||void 0);return this._addObserver(o),()=>{this._removeObserver(o)}}then(e,n){return this._promise.then(e,n)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){let n=this._observers.indexOf(e);n!==-1&&this._observers.splice(n,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(n=>{this._notifyObserver(n)})}_finishPromise(){if(this._resolve!==void 0){let e=!0;switch(te(this._state)){case y.SUCCESS:N(this._resolve.bind(null,this.snapshot))();break;case y.CANCELED:case y.ERROR:let n=this._reject;N(n.bind(null,this._error))();break;default:e=!1;break}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(te(this._state)){case y.RUNNING:case y.PAUSED:e.next&&N(e.next.bind(e,this.snapshot))();break;case y.SUCCESS:e.complete&&N(e.complete.bind(e))();break;case y.CANCELED:case y.ERROR:e.error&&N(e.error.bind(e,this._error))();break;default:e.error&&N(e.error.bind(e,this._error))()}}resume(){let e=this._state==="paused"||this._state==="pausing";return e&&this._transition("running"),e}pause(){let e=this._state==="running";return e&&this._transition("pausing"),e}cancel(){let e=this._state==="running"||this._state==="pausing";return e&&this._transition("canceling"),e}};var F=class t{constructor(e,n){this._service=e,n instanceof k?this._location=n:this._location=k.makeFromUrl(n,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,n){return new t(e,n)}get root(){let e=new k(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return ze(this._location.path)}get storage(){return this._service}get parent(){let e=Bt(this._location.path);if(e===null)return null;let n=new k(this._location.bucket,e);return new t(this._service,n)}_throwIfRoot(e){if(this._location.path==="")throw gt(e)}};function Jt(t,e,n){return t._throwIfRoot("uploadBytesResumable"),new ue(t,new X(e),n)}function Qt(t){t._throwIfRoot("getMetadata");let e=Ge(t.storage,t._location,de());return t.storage.makeRequestWithTokens(e,A)}function en(t,e){t._throwIfRoot("updateMetadata");let n=Gt(t.storage,t._location,e,de());return t.storage.makeRequestWithTokens(n,A)}function tn(t){t._throwIfRoot("deleteObject");let e=Wt(t.storage,t._location);return t.storage.makeRequestWithTokens(e,A)}function nn(t,e){let n=Mt(t._location.path,e),s=new k(t._location.bucket,n);return new F(t.storage,s)}function sn(t){return/^[A-Za-z]+:\/\//.test(t)}function rn(t,e){return new F(t,e)}function Ve(t,e){if(t instanceof j){let n=t;if(n._bucket==null)throw ft();let s=new F(n,n._bucket);return e!=null?Ve(s,e):s}else return e!==void 0?nn(t,e):t}function on(t,e){if(e&&sn(e)){if(t instanceof j)return rn(t,e);throw ne("To use ref(service, url), the first argument must be a Storage instance.")}else return Ve(t,e)}function Ce(t,e){let n=e?.[Le];return n==null?null:k.makeFromBucketSpec(n,t)}function an(t,e,n,s={}){t.host=`${e}:${n}`;let r=J(e);r&&(be(`https://${t.host}/b`),Re("Storage",!0)),t._isUsingEmulator=!0,t._protocol=r?"https":"http";let{mockUserToken:o}=s;o&&(t._overrideAuthToken=typeof o=="string"?o:we(o,t.app.options.projectId))}var j=class{constructor(e,n,s,r,o,i=!1){this.app=e,this._authProvider=n,this._appCheckProvider=s,this._url=r,this._firebaseVersion=o,this._isUsingEmulator=i,this._bucket=null,this._host=De,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=st,this._maxUploadRetryTime=rt,this._requests=new Set,r!=null?this._bucket=k.makeFromBucketSpec(r,this._host):this._bucket=Ce(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,this._url!=null?this._bucket=k.makeFromBucketSpec(this._url,e):this._bucket=Ce(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){Oe("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){Oe("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;let e=this._authProvider.getImmediate({optional:!0});if(e){let n=await e.getToken();if(n!==null)return n.accessToken}return null}async _getAppCheckToken(){if(Ue(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new F(this,e)}_makeRequest(e,n,s,r,o=!0){if(this._deleted)return new se(qe());{let i=xt(e,this._appId,s,r,n,this._firebaseVersion,o,this._isUsingEmulator);return this._requests.add(i),i.getPromise().then(()=>this._requests.delete(i),()=>this._requests.delete(i)),i}}async makeRequestWithTokens(e,n){let[s,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,n,s,r).getPromise()}},ve="@firebase/storage",Ne="0.14.0";var Xe="storage";function Ke(t,e,n){return t=S(t),Jt(t,e,n)}function Ye(t){return t=S(t),Qt(t)}function Ze(t,e){return t=S(t),en(t,e)}function Je(t){return t=S(t),tn(t)}function B(t,e){return t=S(t),on(t,e)}function Un(t=xe(),e){t=S(t);let s=Ee(t,Xe).getImmediate({identifier:e}),r=me("storage");return r&&un(s,...r),s}function un(t,e,n,s={}){an(t,e,n,s)}function ln(t,{instanceIdentifier:e}){let n=t.getProvider("app").getImmediate(),s=t.getProvider("auth-internal"),r=t.getProvider("app-check-internal");return new j(n,s,r,e,Ie)}function cn(){ke(new ye(Xe,ln,"PUBLIC").setMultipleInstances(!0)),Q(ve,Ne,""),Q(ve,Ne,"esm2020")}cn();var Qe=["bmp","gif","ico","jpeg","jpg","png","tiff","webp"],et=[...Qe,"svg"],tt=["mp4","webm"],hn="https://lh3.googleusercontent.com/";async function Sn(t,e){let n=window.__ROOT_CTX.rootConfig.projectId,s=await wn(t),r=ge(t.name),o=dn(t,s,r,e),i=`${n}/uploads/${o}`,u=B(window.firebase.storage,i);if(e?.checkExists&&await fn(i))throw new Error(`File already exists: ${i}`);let a=Ke(u,t),l=-1,c=Date.now();return await new Promise((d,f)=>{let _=setInterval(()=>{Date.now()-c>1e4&&(clearInterval(_),f(new Error("Upload stalled: no progress for 10 seconds")))},1e3);a.on("state_changed",h=>{h.bytesTransferred>0&&clearInterval(_),console.log(`uploading ${t.name}: ${h.bytesTransferred} / ${h.totalBytes} bytes`),h.bytesTransferred!==l&&(l=h.bytesTransferred,c=Date.now())},h=>{clearInterval(_),f(h)},()=>{console.log(`uploaded ${i}`),clearInterval(_),d(a.snapshot)})}),pn(u,t,r,e)}async function Pn(t){let e=window.firebase.storage,n;t.startsWith("/")?n=B(e,`gs://${t.substring(1)}`):t.startsWith("http")?n=B(e,t):n=B(e,t),await Je(n),console.log(`deleted ${t}`)}function dn(t,e,n,s){return s?.namingMode==="clean"?t.name:s?.namingMode==="hash-path"||s?.preserveFilename?`${e}/${t.name}`:`${e}.${n}`}async function fn(t){let e=B(window.firebase.storage,t);try{return await Ye(e),!0}catch(n){if(n.code==="storage/object-not-found")return!1;throw n}}async function pn(t,e,n,s){let r={};r.filename=e.name,r.uploadedBy=window.firebase.user.email||"unknown",r.uploadedAt=String(Math.floor(new Date().getTime()));let o=`/${t.bucket}/${t.fullPath}`,i=`https://storage.googleapis.com${o}`;if(et.includes(n)){let a=await mn(e);if(r.width=a.width,r.height=a.height,!s?.disableGci&&Qe.includes(n)){let l=await gn(o);l&&(r.gcsPath=o,i=l)}r.canvasBgColor=await Tn(e)?"dark":"light"}else if(tt.includes(n)){let a=await bn(i);r.width=a.width,r.height=a.height,console.log("video dimensions:",a)}let u=s?.cacheControl||"public, max-age=31536000";return await Ze(t,{cacheControl:u,customMetadata:Rn(r)}),console.log("updated meta data: ",r),{...r,src:i}}function ge(t){return _n(t.split(".").at(-1)||"")}function _n(t){let e=String(t).toLowerCase();return e==="jpeg"&&(e="jpg"),e}async function gn(t){let e=window.__ROOT_CTX.rootConfig.gci;if(!e)return"";let n=new URLSearchParams({gcs:t}),s=`${e}/_/serving_url?${n.toString()}`,r=await window.fetch(s);if(r.status!==200){let i=await r.text();throw console.error(`failed to get gci url: ${s}`),console.error(i),new Error("failed to get gci url")}return(await r.json()).servingUrl}async function mn(t){return new Promise((e,n)=>{let s=new FileReader;s.onload=()=>{let r=new Image;r.onload=()=>{e({width:r.width,height:r.height})},r.onerror=n,r.src=String(s.result)},s.onerror=n,s.readAsDataURL(t)})}async function bn(t){return new Promise((e,n)=>{let s=document.createElement("video");s.addEventListener("loadedmetadata",()=>{let r={width:s.videoWidth,height:s.videoHeight};e(r),document.body.removeChild(s)},!1),s.addEventListener("error",()=>{n(new Error("Failed to load video metadata")),document.body.removeChild(s)},!1),s.className="sr-only",s.src=t,s.preload="metadata",document.body.appendChild(s)})}async function wn(t){let e=await t.arrayBuffer(),n=await crypto.subtle.digest("SHA-1",e);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}function Rn(t){let e={};return Object.entries(t).forEach(([n,s])=>{t[n]=String(s).trim()}),e}function Cn(t){if(!t)return!1;if(nt(t)||t.startsWith("data:image/")||t.startsWith("blob:"))return!0;let e=ge(t);return et.includes(e)}function nt(t){return t?t.startsWith(hn):!1}function vn(t){if(!t)return!1;let e=ge(t);return tt.includes(e)}function Nn(t){return nt(t)?t.split("=")[0]+"=s0-d":t}function Tn(t){return new Promise((e,n)=>{let s=new Image,r=new FileReader;r.onload=()=>{s.src=r.result},s.onload=()=>{let o=document.createElement("canvas"),i=o.getContext("2d");o.width=s.width,o.height=s.height,i.drawImage(s,0,0,o.width,o.height);let{data:u}=i.getImageData(0,0,o.width,o.height),a=0,l=0,c=0,d=0,f=Math.floor(u.length/4e4)*4;f<4&&(f=4);for(let h=0;h<u.length;h+=f)u[h+3]<128||(a+=u[h],l+=u[h+1],c+=u[h+2],d++);if(d===0){e(!1);return}let _=.299*(a/d)+.587*(l/d)+.114*(c/d);e(_>128)},s.onerror=n,r.onerror=n,r.readAsDataURL(t)})}export{Un as a,Qe as b,et as c,tt as d,hn as e,Sn as f,Pn as g,fn as h,ge as i,Cn as j,nt as k,vn as l,Nn as m,Tn as n};
|
|
10
|
+
--`+a+"--",_=V.getBlob(d,s,f);if(_===null)throw $e();let h={name:l.fullPath},R=G(o,t.host,t._protocol),m="POST",U=t.maxUploadRetryTime,I=new x(R,m,K(t,n),U);return I.urlParams=h,I.headers=i,I.body=_.uploadData(),I.errorHandler=z(e),I}var L=class{constructor(e,n,s,r){this.current=e,this.total=n,this.finalized=!!s,this.metadata=r||null}};function ge(t,e){let n=null;try{n=t.getResponseHeader("X-Goog-Upload-Status")}catch{O(!1)}return O(!!n&&(e||["active"]).indexOf(n)!==-1),n}function Zt(t,e,n,s,r){let o=e.bucketOnlyServerUrl(),i=Ve(e,s,r),u={name:i.fullPath},a=G(o,t.host,t._protocol),l="POST",c={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${s.size()}`,"X-Goog-Upload-Header-Content-Type":i.contentType,"Content-Type":"application/json; charset=utf-8"},d=pe(i,n),f=t.maxUploadRetryTime;function _(R){ge(R);let m;try{m=R.getResponseHeader("X-Goog-Upload-URL")}catch{O(!1)}return O(he(m)),m}let h=new x(a,l,_,f);return h.urlParams=u,h.headers=c,h.body=d,h.errorHandler=z(e),h}function Jt(t,e,n,s){let r={"X-Goog-Upload-Command":"query"};function o(l){let c=ge(l,["active","final"]),d=null;try{d=l.getResponseHeader("X-Goog-Upload-Size-Received")}catch{O(!1)}d||O(!1);let f=Number(d);return O(!isNaN(f)),new L(f,s.size(),c==="final")}let i="POST",u=t.maxUploadRetryTime,a=new x(n,i,o,u);return a.headers=r,a.errorHandler=z(e),a}var Ce=256*1024;function Qt(t,e,n,s,r,o,i,u){let a=new L(0,0);if(i?(a.current=i.current,a.total=i.total):(a.current=0,a.total=s.size()),s.size()!==a.total)throw gt();let l=a.total-a.current,c=l;r>0&&(c=Math.min(c,r));let d=a.current,f=d+c,_="";c===0?_="finalize":l===c?_="upload, finalize":_="upload";let h={"X-Goog-Upload-Command":_,"X-Goog-Upload-Offset":`${a.current}`},R=s.slice(d,f);if(R===null)throw $e();function m(b,C){let v=ge(b,["active","final"]),Z=a.current+c,M=s.size(),J;return v==="final"?J=K(e,o)(b,C):J=null,new L(Z,M,v==="final",J)}let U="POST",I=e.maxUploadRetryTime,T=new x(n,U,m,I);return T.headers=h,T.body=R.uploadData(),T.progressCallback=u||null,T.errorHandler=z(t),T}var y={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function ne(t){switch(t){case"running":case"pausing":case"canceling":return y.RUNNING;case"paused":return y.PAUSED;case"success":return y.SUCCESS;case"canceled":return y.CANCELED;case"error":return y.ERROR;default:return y.ERROR}}var ie=class{constructor(e,n,s){if(yt(e)||n!=null||s!=null)this.next=e,this.error=n??void 0,this.complete=s??void 0;else{let o=e;this.next=o.next,this.error=o.error,this.complete=o.complete}}};function N(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}var ve=null,ae=class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=P.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=P.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=P.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,n,s,r,o){if(this.sent_)throw q("cannot .send() more than once");if(Q(e)&&s&&(this.xhr_.withCredentials=!0),this.sent_=!0,this.xhr_.open(n,e,!0),o!==void 0)for(let i in o)o.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,o[i].toString());return r!==void 0?this.xhr_.send(r):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw q("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw q("cannot .getStatus() before sending");try{return this.xhr_.status}catch{return-1}}getResponse(){if(!this.sent_)throw q("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw q("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){this.xhr_.upload!=null&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){this.xhr_.upload!=null&&this.xhr_.upload.removeEventListener("progress",e)}},ue=class extends ae{initXhr(){this.xhr_.responseType="text"}};function A(){return ve?ve():new ue}var le=class{isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}constructor(e,n,s=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=n,this._metadata=s,this._mappings=fe(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=r=>{if(this._request=void 0,this._chunkMultiplier=1,r._codeEquals(p.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{let o=this.isExponentialBackoffExpired();if(je(r.status,[]))if(o)r=Me();else{this.sleepTime=Math.max(this.sleepTime*2,at),this._needToFetchStatus=!0,this.completeTransitions_();return}this._error=r,this._transition("error")}},this._metadataErrorHandler=r=>{this._request=void 0,r._codeEquals(p.CANCELED)?this.completeTransitions_():(this._error=r,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((r,o)=>{this._resolve=r,this._reject=o,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){let e=this._transferred;return n=>this._updateProgress(e+n)}_shouldDoResumable(e){return e.size()>256*1024}_start(){this._state==="running"&&this._request===void 0&&(this._resumable?this._uploadUrl===void 0?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([n,s])=>{switch(this._state){case"running":e(n,s);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused");break}})}_createResumable(){this._resolveToken((e,n)=>{let s=Zt(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(s,A,e,n);this._request=r,r.getPromise().then(o=>{this._request=void 0,this._uploadUrl=o,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let e=this._uploadUrl;this._resolveToken((n,s)=>{let r=Jt(this._ref.storage,this._ref._location,e,this._blob),o=this._ref.storage._makeRequest(r,A,n,s);this._request=o,o.getPromise().then(i=>{i=i,this._request=void 0,this._updateProgress(i.current),this._needToFetchStatus=!1,i.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let e=Ce*this._chunkMultiplier,n=new L(this._transferred,this._blob.size()),s=this._uploadUrl;this._resolveToken((r,o)=>{let i;try{i=Qt(this._ref._location,this._ref.storage,s,this._blob,e,this._mappings,n,this._makeProgressCallback())}catch(a){this._error=a,this._transition("error");return}let u=this._ref.storage._makeRequest(i,A,r,o,!1);this._request=u,u.getPromise().then(a=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(a.current),a.finalized?(this._metadata=a.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){Ce*this._chunkMultiplier*2<32*1024*1024&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,n)=>{let s=Xe(this._ref.storage,this._ref._location,this._mappings),r=this._ref.storage._makeRequest(s,A,e,n);this._request=r,r.getPromise().then(o=>{this._request=void 0,this._metadata=o,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,n)=>{let s=Yt(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),r=this._ref.storage._makeRequest(s,A,e,n);this._request=r,r.getPromise().then(o=>{this._request=void 0,this._metadata=o,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){let n=this._transferred;this._transferred=e,this._transferred!==n&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,this._request!==void 0?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":let n=this._state==="paused";this._state=e,n&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=qe(),this._state=e,this._notifyObservers();break;case"error":this._state=e,this._notifyObservers();break;case"success":this._state=e,this._notifyObservers();break}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start();break}}get snapshot(){let e=ne(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,n,s,r){let o=new ie(n||void 0,s||void 0,r||void 0);return this._addObserver(o),()=>{this._removeObserver(o)}}then(e,n){return this._promise.then(e,n)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){let n=this._observers.indexOf(e);n!==-1&&this._observers.splice(n,1)}_notifyObservers(){this._finishPromise(),this._observers.slice().forEach(n=>{this._notifyObserver(n)})}_finishPromise(){if(this._resolve!==void 0){let e=!0;switch(ne(this._state)){case y.SUCCESS:N(this._resolve.bind(null,this.snapshot))();break;case y.CANCELED:case y.ERROR:let n=this._reject;N(n.bind(null,this._error))();break;default:e=!1;break}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(ne(this._state)){case y.RUNNING:case y.PAUSED:e.next&&N(e.next.bind(e,this.snapshot))();break;case y.SUCCESS:e.complete&&N(e.complete.bind(e))();break;case y.CANCELED:case y.ERROR:e.error&&N(e.error.bind(e,this._error))();break;default:e.error&&N(e.error.bind(e,this._error))()}}resume(){let e=this._state==="paused"||this._state==="pausing";return e&&this._transition("running"),e}pause(){let e=this._state==="running";return e&&this._transition("pausing"),e}cancel(){let e=this._state==="running"||this._state==="pausing";return e&&this._transition("canceling"),e}};var F=class t{constructor(e,n){this._service=e,n instanceof k?this._location=n:this._location=k.makeFromUrl(n,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,n){return new t(e,n)}get root(){let e=new k(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return We(this._location.path)}get storage(){return this._service}get parent(){let e=qt(this._location.path);if(e===null)return null;let n=new k(this._location.bucket,e);return new t(this._service,n)}_throwIfRoot(e){if(this._location.path==="")throw bt(e)}};function en(t,e,n){return t._throwIfRoot("uploadBytesResumable"),new le(t,new V(e),n)}function tn(t){t._throwIfRoot("getMetadata");let e=Xe(t.storage,t._location,fe());return t.storage.makeRequestWithTokens(e,A)}function nn(t,e){t._throwIfRoot("updateMetadata");let n=Xt(t.storage,t._location,e,fe());return t.storage.makeRequestWithTokens(n,A)}function sn(t){t._throwIfRoot("deleteObject");let e=Vt(t.storage,t._location);return t.storage.makeRequestWithTokens(e,A)}function rn(t,e){let n=$t(t._location.path,e),s=new k(t._location.bucket,n);return new F(t.storage,s)}function on(t){return/^[A-Za-z]+:\/\//.test(t)}function an(t,e){return new F(t,e)}function Ke(t,e){if(t instanceof j){let n=t;if(n._bucket==null)throw _t();let s=new F(n,n._bucket);return e!=null?Ke(s,e):s}else return e!==void 0?rn(t,e):t}function un(t,e){if(e&&on(e)){if(t instanceof j)return an(t,e);throw se("To use ref(service, url), the first argument must be a Storage instance.")}else return Ke(t,e)}function Ne(t,e){let n=e?.[Be];return n==null?null:k.makeFromBucketSpec(n,t)}function ln(t,e,n,s={}){t.host=`${e}:${n}`;let r=Q(e);r&&(Te(`https://${t.host}/b`),ye("Storage",!0)),t._isUsingEmulator=!0,t._protocol=r?"https":"http";let{mockUserToken:o}=s;o&&(t._overrideAuthToken=typeof o=="string"?o:Re(o,t.app.options.projectId))}var j=class{constructor(e,n,s,r,o,i=!1){this.app=e,this._authProvider=n,this._appCheckProvider=s,this._url=r,this._firebaseVersion=o,this._isUsingEmulator=i,this._bucket=null,this._host=Fe,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=ot,this._maxUploadRetryTime=it,this._requests=new Set,r!=null?this._bucket=k.makeFromBucketSpec(r,this._host):this._bucket=Ne(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,this._url!=null?this._bucket=k.makeFromBucketSpec(this._url,e):this._bucket=Ne(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){Pe("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){Pe("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;let e=this._authProvider.getImmediate({optional:!0});if(e){let n=await e.getToken();if(n!==null)return n.accessToken}return null}async _getAppCheckToken(){if(xe(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new F(this,e)}_makeRequest(e,n,s,r,o=!0){if(this._deleted)return new re(He());{let i=Ot(e,this._appId,s,r,n,this._firebaseVersion,o,this._isUsingEmulator);return this._requests.add(i),i.getPromise().then(()=>this._requests.delete(i),()=>this._requests.delete(i)),i}}async makeRequestWithTokens(e,n){let[s,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,n,s,r).getPromise()}},De="@firebase/storage",Le="0.14.0";var Ye="storage";function Ze(t,e,n){return t=S(t),en(t,e,n)}function Je(t){return t=S(t),tn(t)}function Qe(t,e){return t=S(t),nn(t,e)}function et(t){return t=S(t),sn(t)}function B(t,e){return t=S(t),un(t,e)}function xn(t=Oe(),e){t=S(t);let s=Ie(t,Ye).getImmediate({identifier:e}),r=we("storage");return r&&cn(s,...r),s}function cn(t,e,n,s={}){ln(t,e,n,s)}function hn(t,{instanceIdentifier:e}){let n=t.getProvider("app").getImmediate(),s=t.getProvider("auth-internal"),r=t.getProvider("app-check-internal");return new j(n,s,r,e,Ae)}function dn(){Ue(new Ee(Ye,hn,"PUBLIC").setMultipleInstances(!0)),ee(De,Le,""),ee(De,Le,"esm2020")}dn();var tt=["bmp","gif","ico","jpeg","jpg","png","tiff","webp"],nt=[...tt,"svg"],fn=["avif"],st=[...nt,...fn],be=["mp4","webm"],pn="https://lh3.googleusercontent.com/";async function Cn(t,e){let n=window.__ROOT_CTX.rootConfig.projectId,s=await Rn(t),r=Y(t.name),o=_n(t,s,r,e),i=`${n}/uploads/${o}`,u=B(window.firebase.storage,i);if(e?.checkExists&&await gn(i))throw new Error(`File already exists: ${i}`);let a=Ze(u,t),l=-1,c=Date.now();return await new Promise((d,f)=>{let _=setInterval(()=>{Date.now()-c>1e4&&(clearInterval(_),f(new Error("Upload stalled: no progress for 10 seconds")))},1e3);a.on("state_changed",h=>{h.bytesTransferred>0&&clearInterval(_),console.log(`uploading ${t.name}: ${h.bytesTransferred} / ${h.totalBytes} bytes`),h.bytesTransferred!==l&&(l=h.bytesTransferred,c=Date.now())},h=>{clearInterval(_),f(h)},()=>{console.log(`uploaded ${i}`),clearInterval(_),d(a.snapshot)})}),mn(u,t,r,e)}async function vn(t){let e=window.firebase.storage,n;t.startsWith("/")?n=B(e,`gs://${t.substring(1)}`):t.startsWith("http")?n=B(e,t):n=B(e,t),await et(n),console.log(`deleted ${t}`)}function _n(t,e,n,s){return s?.namingMode==="clean"?t.name:s?.namingMode==="hash-path"||s?.preserveFilename?`${e}/${t.name}`:`${e}.${n}`}async function gn(t){let e=B(window.firebase.storage,t);try{return await Je(e),!0}catch(n){if(n.code==="storage/object-not-found")return!1;throw n}}async function mn(t,e,n,s){let r={};r.filename=e.name,r.uploadedBy=window.firebase.user.email||"unknown",r.uploadedAt=String(Math.floor(new Date().getTime()));let o=`/${t.bucket}/${t.fullPath}`,i=`https://storage.googleapis.com${o}`;if(st.includes(n)){let a=await wn(e);if(r.width=a.width,r.height=a.height,!s?.disableGci&&tt.includes(n)){let l=await bn(o);l&&(r.gcsPath=o,i=l)}r.canvasBgColor=await kn(e)?"dark":"light"}else if(be.includes(n)){let a=await Tn(i);r.width=a.width,r.height=a.height,console.log("video dimensions:",a)}let u=s?.cacheControl||"public, max-age=31536000";return await Qe(t,{cacheControl:u,customMetadata:yn(r)}),console.log("updated meta data: ",r),{...r,src:i}}function Y(t){return me(t.split(".").at(-1)||"")}function me(t){let e=String(t).toLowerCase();return e==="jpeg"&&(e="jpg"),e}async function bn(t){let e=window.__ROOT_CTX.rootConfig.gci;if(!e)return"";let n=new URLSearchParams({gcs:t}),s=`${e}/_/serving_url?${n.toString()}`,r=await window.fetch(s);if(r.status!==200){let i=await r.text();throw console.error(`failed to get gci url: ${s}`),console.error(i),new Error("failed to get gci url")}return(await r.json()).servingUrl}async function wn(t){return new Promise((e,n)=>{let s=new FileReader;s.onload=()=>{let r=new Image;r.onload=()=>{e({width:r.width,height:r.height})},r.onerror=n,r.src=String(s.result)},s.onerror=n,s.readAsDataURL(t)})}async function Tn(t){return new Promise((e,n)=>{let s=document.createElement("video");s.addEventListener("loadedmetadata",()=>{let r={width:s.videoWidth,height:s.videoHeight};e(r),document.body.removeChild(s)},!1),s.addEventListener("error",()=>{n(new Error("Failed to load video metadata")),document.body.removeChild(s)},!1),s.className="sr-only",s.src=t,s.preload="metadata",document.body.appendChild(s)})}async function Rn(t){let e=await t.arrayBuffer(),n=await crypto.subtle.digest("SHA-1",e);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}function yn(t){let e={};return Object.entries(t).forEach(([n,s])=>{t[n]=String(s).trim()}),e}function Nn(t){if(!t)return!1;if(rt(t)||t.startsWith("data:image/")||t.startsWith("blob:"))return!0;let e=Y(t);return st.includes(e)}function rt(t){return t?t.startsWith(pn):!1}function Dn(t){if(!t)return!1;let e=Y(t);return be.includes(e)}function Ln(t,e){if(!e||e.length===0)return!0;let n=Y(t);return e.some(s=>{let r=String(s).toLowerCase().trim();if(r==="*"||r==="*/*"||r===`*/${n}`)return!0;if(r.endsWith("/*")){let o=r.split("/")[0];return o==="image"?nt.includes(n):o==="video"?be.includes(n):!1}return r.includes("/")?me(r.split("/")[1].split("+")[0])===n:me(r.replace(/^\./,""))===n})}function Fn(t){return rt(t)?t.split("=")[0]+"=s0-d":t}function kn(t){return new Promise((e,n)=>{let s=new Image,r=new FileReader;r.onload=()=>{s.src=r.result},s.onload=()=>{let o=document.createElement("canvas"),i=o.getContext("2d");o.width=s.width,o.height=s.height,i.drawImage(s,0,0,o.width,o.height);let{data:u}=i.getImageData(0,0,o.width,o.height),a=0,l=0,c=0,d=0,f=Math.floor(u.length/4e4)*4;f<4&&(f=4);for(let h=0;h<u.length;h+=f)u[h+3]<128||(a+=u[h],l+=u[h+1],c+=u[h+2],d++);if(d===0){e(!1);return}let _=.299*(a/d)+.587*(l/d)+.114*(c/d);e(_>128)},s.onerror=n,r.onerror=n,r.readAsDataURL(t)})}export{xn as a,tt as b,nt as c,fn as d,st as e,be as f,pn as g,Cn as h,vn as i,gn as j,Y as k,Nn as l,rt as m,Dn as n,Ln as o,Fn as p,kn as q};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(){return!!(window.__ROOT_CTX.ai||window.__ROOT_CTX.experiments?.ai)}function n(){return!!(window.__ROOT_CTX.ai?.imageGenerationEnabled||window.__ROOT_CTX.experiments?.ai)}export{e as a,n as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as te,f as se,g as U,h as oe,i as ne,l as ie}from"./chunk-YMBBWVBB.js";import{f as p}from"./chunk-KRNQ6L35.js";import{a as k,b as I,c as l,f as J,g as x,h as D,i as O,j as F,l as Y,n as B,o as j,p as M,q as w,r as Z,t as $,u as R,v as m,w as ee,x as T}from"./chunk-VD6G5NV4.js";import{k as N}from"./chunk-7SK47HHZ.js";function re(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null}function ce(e){return re(e)&&Array.isArray(e.blocks)&&e.blocks.length>0}var X=new Map;function Re(e){return X.get(e)||null}async function We(e){let t=Re(e);if(t)return t;let s=b(e),o=(await B(s)).data();return De(e,o),o}function De(e,t){X.set(e,t)}function q(e){X.delete(e)}function L(e){for(let t of e)q(t)}function ae(e){e||(e=6);let t=[],s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=s.length;for(let o=0;o<e;o++)t.push(s.charAt(Math.floor(Math.random()*n)));return t.join("")}var v=class extends Error{},le=200,Ce=/[/\\\u0000-\u001f]/;function C(){let e=window.__ROOT_CTX.rootConfig.projectId,t=window.firebase.db;return I(t,"Projects",e,"Assets")}var Te="root-cms:assetPicker:lastFolder";function ue(){let e=window.__ROOT_CTX.rootConfig.projectId;return`${Te}:${e}`}function rt(){try{return localStorage.getItem(ue())||""}catch{return""}}function ct(e){try{localStorage.setItem(ue(),e||"")}catch{}}function H(e){let t=(e||"").trim();if(!t)throw new v("Name is required.");if(t.length>le)throw new v(`Name is too long (max ${le} chars).`);if(Ce.test(t))throw new v("Name cannot contain slashes.");if(t==="."||t==="..")throw new v("Invalid name.");return t}function _(e,t){return e?`${e}/${t}`:t}function at(e){return e?e.split("/").filter(Boolean):[]}function E(e){return`folder-${encodeURIComponent(e)}`}function me(e){return e.sort((t,s)=>t.type!==s.type?t.type==="folder"?-1:1:(t.name||"").localeCompare(s.name||"",void 0,{numeric:!0,sensitivity:"base"}))}function pe(e){return!!e&&typeof e.name=="string"&&(e.type==="file"||e.type==="folder")}async function Be(e){let t=C(),s=x(t,D("parent","==",e||"")),n=await j(s),o=[];return n.forEach(i=>{let r=i.data();pe(r)&&o.push(r)}),me(o)}var de=1e3;async function lt(e){let t=C(),s;e?s=x(t,D("parent",">=",e),D("parent","<=",`${e}\uF8FF`),F(de)):s=x(t,F(de));let n=await j(s),o=[];return n.forEach(i=>{let r=i.data();pe(r)&&(!e||Q(r.parent,e))&&o.push(r)}),me(o)}function dt(e,t){return t?e===t?"":e.startsWith(`${t}/`)?e.slice(t.length+1):e:e}async function P(e){let t=l(C(),e),s=await B(t);return s.exists()?s.data():null}async function ft(e,t){let s=H(t),n=_(e,s),o=E(n),i=l(C(),o),r={id:o,type:"folder",parent:e||"",name:s,createdAt:m(),createdBy:window.firebase.user.email,modifiedAt:m(),modifiedBy:window.firebase.user.email};return await M(i,r,{merge:!0}),p("asset.folder_create",{metadata:{folder:n}}),await P(o)}async function ut(e){let t=W(e.file),s=H(e.name||t.filename||Fe(t.src)),n=ae(12),o=l(C(),n);return await M(o,{id:n,type:"file",parent:e.parent||"",name:s,file:t,createdAt:m(),createdBy:window.firebase.user.email,modifiedAt:m(),modifiedBy:window.firebase.user.email}),p("asset.upload",{metadata:{assetId:n,name:s}}),await P(n)}async function mt(e,t){let s=H(t);if(s===e.name)return;if(e.type==="folder"){let o=_(e.parent,e.name),i=_(e.parent,s);await ge(e,i,s,e.parent),p("asset.rename",{metadata:{from:o,to:i}});return}let n=l(C(),e.id);await w(n,{name:s,modifiedAt:m(),modifiedBy:window.firebase.user.email}),p("asset.rename",{metadata:{assetId:e.id,from:e.name,to:s}})}async function pt(e,t){let s=t||"";if(s===e.parent)return;if(e.type==="folder"){let o=_(e.parent,e.name),i=_(s,e.name);if(i===o||Q(i,o))throw new Error("Cannot move a folder into itself.");await ge(e,i,e.name,s),p("asset.move",{metadata:{from:o,to:i}});return}let n=l(C(),e.id);await w(n,{parent:s,modifiedAt:m(),modifiedBy:window.firebase.user.email}),p("asset.move",{metadata:{assetId:e.id,from:e.parent,to:s}})}function Q(e,t){return e===t||e.startsWith(`${t}/`)}async function ge(e,t,s,n){let o=_(e.parent,e.name),i=C(),r=window.firebase.db,c=x(i,D("parent",">=",o),D("parent","<=",`${o}\uF8FF`)),a=await j(c),f=[];a.forEach(h=>{let A=h.data();Q(A.parent,o)&&f.push(A)});let d=T(r),g=0,y=async()=>{g+=1,g>=400&&(await d.commit(),d=T(r),g=0)},u=E(t);d.set(l(i,u),{id:u,type:"folder",parent:n,name:s,createdAt:e.createdAt??m(),createdBy:e.createdBy??window.firebase.user.email,modifiedAt:m(),modifiedBy:window.firebase.user.email}),await y();for(let h of f){let A=t+h.parent.slice(o.length);if(h.type==="folder"){let S=_(A,h.name);d.set(l(i,E(S)),{...h,id:E(S),parent:A,modifiedAt:m(),modifiedBy:window.firebase.user.email}),await y(),d.delete(l(i,h.id)),await y()}else d.update(l(i,h.id),{parent:A,modifiedAt:m(),modifiedBy:window.firebase.user.email}),await y()}u!==e.id&&(d.delete(l(i,e.id)),g+=1),g>0&&await d.commit()}async function gt(e){if(e.type==="folder"){let t=_(e.parent,e.name);if((await Be(t)).length>0)throw new Error("Folder is not empty.")}await Z(l(C(),e.id)),p("asset.delete",{metadata:{assetId:e.id,name:e.name}})}async function yt(e,t){let s=W(t);!s.alt&&e.file?.alt&&(s.alt=e.file.alt),e.file?.altDisabled&&(s.altDisabled=!0);let n=l(C(),e.id),o={file:s,modifiedAt:m(),modifiedBy:window.firebase.user.email},i=N(s.filename||s.src||""),r=je(e.name,i);return r!==e.name&&(o.name=r),await w(n,o),p("asset.replace",{metadata:{assetId:e.id,name:e.name}}),await P(e.id)}function je(e,t){let s=(e||"").lastIndexOf(".");return!t||s<=0||N(e)===t?e:`${e.slice(0,s)}.${t}`}async function ht(e,t){let s=l(C(),e.id);return await w(s,{"file.alt":t||"",modifiedAt:m(),modifiedBy:window.firebase.user.email}),await P(e.id)}async function wt(e,t){let s=l(C(),e.id);return await w(s,{"file.altDisabled":t?!0:R(),modifiedAt:m(),modifiedBy:window.firebase.user.email}),p("asset.alt_disabled",{metadata:{assetId:e.id,name:e.name,disabled:t}}),await P(e.id)}function _e(e){let t={...W(e.file),assetId:e.id};return t.altDisabled&&(t.alt=""),t}function K(e){let t=new Set;return G(e,t),Array.from(t).sort()}function G(e,t){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)G(s,t);return}if(typeof e.toMillis!="function"){if(z(e)){t.add(e.assetId);return}for(let s of Object.keys(e))G(e[s],t)}}}function z(e){return typeof e?.assetId=="string"&&typeof e?.src=="string"}function fe(e){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let t of e)if(fe(t))return!0;return!1}if(typeof e.toMillis=="function")return!1;if(z(e))return!0;for(let t of Object.keys(e))if(fe(e[t]))return!0;return!1}async function ke(e){let t=window.__ROOT_CTX.rootConfig.projectId,s=window.firebase.db,n=Object.keys(window.__ROOT_CTX.collections||{});return(await Promise.all(n.map(async r=>{let c=I(s,"Projects",t,"Collections",r,"Drafts"),a=x(c,D("sys.assets","array-contains",e)),f=await j(a),d=[];return f.forEach(g=>{d.push(g.data())}),d}))).flat().sort((r,c)=>r.id.localeCompare(c.id))}async function bt(e,t={}){let s=window.__ROOT_CTX.rootConfig.projectId,n=window.firebase.db,o=t.docs??await ke(e.id),i=[],r=[];for(let c of o){let a=[];if(ye(c.fields,e.id,"fields",a),a.length===0)continue;let f={};for(let u of a)f[u.path]=Ie(e,u.value,t.previousFile);f["sys.modifiedAt"]=m(),f["sys.modifiedBy"]=window.firebase.user.email;let[d,g]=c.id.split("/"),y=l(n,"Projects",s,"Collections",d,"Drafts",g);try{await w(y,f),i.push(c.id)}catch(u){console.error(`failed to sync asset ${e.id} to ${c.id}:`,u),r.push(c.id)}}return i.length>0&&(L(i),p("asset.sync",{metadata:{assetId:e.id,name:e.name,docIds:i}})),{updatedDocIds:i,failedDocIds:r}}function ye(e,t,s,n){if(!(!e||typeof e!="object")&&!Array.isArray(e)&&typeof e.toMillis!="function"){if(z(e)){e.assetId===t&&n.push({path:s,value:e});return}for(let o of Object.keys(e))ye(e[o],t,`${s}.${o}`,n)}}function Ie(e,t,s){let n=_e(e);if(!e.file?.altDisabled){let i=s?.alt??e.file?.alt??"",r=t?.alt||"";r&&r!==i&&(n.alt=r)}let o=s?.canvasBgColor??e.file?.canvasBgColor;return t?.canvasBgColor&&t.canvasBgColor!==o&&(n.canvasBgColor=t.canvasBgColor),n}function W(e){let t={};return Object.entries(e||{}).forEach(([s,n])=>{n!==void 0&&(t[s]=n)}),t}function Fe(e){return(e||"").split("?")[0].split("/").pop()||"untitled"}async function Ft(e){let t=window.__ROOT_CTX.rootConfig.projectId,s=window.firebase.db,[n,o]=e.split("/"),i=l(s,"Projects",t,"Collections",n,"Drafts",o),r=l(s,"Projects",t,"Collections",n,"Published",o),c=l(s,"Projects",t,"Collections",n,"Scheduled",o),a=T(s);a.delete(i),a.delete(r),a.delete(c),await a.commit(),console.log(`deleted doc: ${e}`),p("doc.delete",{metadata:{docId:e}})}async function vt(e,t){await ve([e],t)}async function ve(e,t){if(e.length===0){console.log("no docs to publish");return}let s=window.firebase.db;if(e.length>100)throw new Error("publish docs exceeds limit of 100 docs. break up your request into multiple calls.");let n=await Ve(e),o=t?.batch||T(s),i=["published"];t?.releaseId&&i.push(`release:${t.releaseId}`),e.forEach(r=>{let c=n[r];if(!c)throw new Error(`doc does not exist: ${r}`);Me(o,r,c,i,t?.publishMessage)}),await o.commit(),e.length===1?console.log(`published ${e[0]}`):console.log(`published ${e.length} docs: ${e.join(", ")}`);for(let r of e){let c={docId:r};t?.publishMessage&&(c.publishMessage=t.publishMessage),p("doc.publish",{metadata:c})}L(e)}function Me(e,t,s,n,o){if(Se(s))throw new Error(`publishing is locked for doc: ${s.id}`);if(Pe(s))throw new Error(`cannot publish archived doc: ${s.id}`);let i=window.__ROOT_CTX.rootConfig.projectId,r=window.firebase.db,[c,a]=t.split("/"),f=l(r,"Projects",i,"Collections",c,"Drafts",a),d=l(r,"Projects",i,"Collections",c,"Scheduled",a),g=l(r,"Projects",i,"Collections",c,"Published",a),y={...s},u=y.sys??{};u.modifiedAt=m(),u.modifiedBy=window.firebase.user.email,u.publishedAt=m(),u.publishedBy=window.firebase.user.email,u.firstPublishedAt??=m(),u.firstPublishedBy??=window.firebase.user.email,delete u.scheduledAt,delete u.scheduledBy,e.update(f,{sys:u}),e.set(g,{...y,sys:u}),e.delete(d);let h=l(r,"Projects",i,"Collections",c,"Drafts",a,"Versions",String(Date.now())),A={id:t,collection:c,slug:a,fields:y.fields||{},sys:u};n?.length&&(A.tags=n),o&&(A.publishMessage=o),e.set(h,A)}async function Mt(e,t,s){let n=window.__ROOT_CTX.rootConfig.projectId,o=window.firebase.db,[i,r]=e.split("/"),c=l(o,"Projects",n,"Collections",i,"Drafts",r),a=l(o,"Projects",n,"Collections",i,"Scheduled",r);await $(o,async d=>{let g=await d.get(c);if(!g.exists())throw new Error(`${c.id} does not exist`);let y={...g.data()},u=y.sys??{};u.modifiedAt=m(),u.modifiedBy=window.firebase.user.email,u.scheduledAt=k.fromMillis(t),u.scheduledBy=window.firebase.user.email,d.update(c,{sys:u});let h={...y,sys:u};s?.publishMessage&&(h.scheduledPublishMessage=s.publishMessage),d.set(a,h)}),console.log(`saved ${a.id}`);let f={docId:e,scheduledAt:t};s?.publishMessage&&(f.publishMessage=s.publishMessage),p("doc.schedule",{metadata:f})}async function Pt(e){let t=window.__ROOT_CTX.rootConfig.projectId,s=window.firebase.db,[n,o]=e.split("/"),i=l(s,"Projects",t,"Collections",n,"Drafts",o),r=l(s,"Projects",t,"Collections",n,"Scheduled",o),c=l(s,"Projects",t,"Collections",n,"Published",o),a=T(s);a.update(i,{"sys.modifiedAt":m(),"sys.modifiedBy":window.firebase.user.email,"sys.publishedAt":R(),"sys.publishedBy":R(),"sys.firstPublishedAt":R(),"sys.firstPublishedBy":R()}),a.delete(r),a.delete(c),await a.commit(),console.log(`unpublished ${e}`),p("doc.unpublish",{metadata:{docId:e}}),q(e)}async function St(e){let t=window.__ROOT_CTX.rootConfig.projectId,s=window.firebase.db,[n,o]=e.split("/"),i=l(s,"Projects",t,"Collections",n,"Drafts",o),r=l(s,"Projects",t,"Collections",n,"Published",o);await $(s,async c=>{let a=await c.get(r);if(!a.exists())throw new Error(`${r.id} does not exist`);let f=a.data();c.set(i,f)}),console.log(`reverted draft ${e}`),p("doc.revert",{metadata:{docId:e}})}async function Ot(e){let t=window.__ROOT_CTX.rootConfig.projectId,s=window.firebase.db,[n,o]=e.split("/"),i=l(s,"Projects",t,"Collections",n,"Drafts",o),r=l(s,"Projects",t,"Collections",n,"Scheduled",o),c=T(s);c.update(i,{"sys.modifiedAt":m(),"sys.modifiedBy":window.firebase.user.email,"sys.scheduledAt":R(),"sys.scheduledBy":R()}),c.delete(r),await c.commit(),console.log(`unscheduled ${e}`),p("doc.unschedule",{metadata:{docId:e}})}async function Lt(e,t){let s={lockedAt:m(),lockedBy:window.firebase.user.email,reason:t.reason||`Locked by ${window.firebase.user.email}.`};t.until&&(s.until=k.fromMillis(t.until));let n=b(e);await w(n,{"sys.publishingLocked":s});let i={docId:e,reason:t.reason};t.until&&(i.until=t.until),p("doc.lock_publishing",{metadata:i})}async function Et(e){let t=b(e),s={"sys.publishingLocked":R()};await w(t,s),p("doc.unlock_publishing",{metadata:{docId:e}})}async function Vt(e){let t=b(e);await w(t,{"sys.archivedAt":m(),"sys.archivedBy":window.firebase.user.email}),p("doc.archive",{metadata:{docId:e}})}async function $t(e){let t=b(e);await w(t,{"sys.archivedAt":R(),"sys.archivedBy":R()}),p("doc.unarchive",{metadata:{docId:e}})}function Pe(e){return!!e?.sys?.archivedAt}function Nt(e){let t=k.now().toMillis();return(e?.sys?.scheduledAt?.toMillis()||0)>t}function Se(e){if(e?.sys?.publishingLocked){if(e.sys.publishingLocked.until){let t=k.now().toMillis(),s=e.sys.publishingLocked.until.toMillis();return t<s}return!0}return!1}async function Ut(e,t,s){let n=b(e),o=await B(n);if(!o.exists())throw new Error(`doc ${e} does not exist`);let i=o.data(),r=i.fields??{},c=i.sys?.locales;await Oe(t,{fields:r,locales:c,overwrite:s?.overwrite})}async function Oe(e,t){let[s,n]=e.split("/"),o=b(e),i=await B(o);if(i.exists()&&!t?.overwrite)throw new Error(`${e} already exists`);let r=t?.fields??{},c={id:e,collection:s,slug:n,sys:{createdAt:m(),createdBy:window.firebase.user.email,modifiedAt:m(),modifiedBy:window.firebase.user.email,locales:t?.locales??["en"]},fields:r};if(i.exists()&&t?.overwrite){let f=i.data();c.sys={...f.sys,locales:t?.locales??f.sys.locales,modifiedAt:m(),modifiedBy:window.firebase.user.email}}let a=K(r);a.length>0?c.sys.assets=a:delete c.sys.assets,await M(o,c),p("doc.create",{metadata:{docId:e}})}async function Xt(e,t,s){let n={};for(let d of t){if(!d.source)continue;let g={source:U(d.source)},y={},u={};Object.entries(d).forEach(([A,S])=>{if(A==="source")return;let Ae=ne(A);for(let V of ie(A)){if(oe(V))continue;let xe=V===Ae?u:y;xe[V]=U(S||"")}}),Object.assign(g,y,u);let h=await se(g.source);n[h]=g}let i=[e.split("/")[0],e];s?.tags&&i.push(...s.tags);let r=te(),c=window.firebase.db,a=T(c),f=0;for(let d in n){let g=n[d],y=l(r,d);a.set(y,{...g,tags:ee(...i)},{merge:!0}),f+=1,f>=500&&(await a.commit(),a=T(c),console.log(`saved ${f} strings`),f=0)}return f>0&&(await a.commit(),console.log(`saved ${f} strings`)),p("doc.import_translations",{metadata:{docId:e,...s?.actionMetadata},links:s?.actionLinks}),n}function b(e){let t=window.__ROOT_CTX.rootConfig.projectId,s=window.firebase.db,[n,o]=e.split("/");return l(s,"Projects",t,"Collections",n,"Drafts",o)}function Le(e){let t=window.__ROOT_CTX.rootConfig.projectId,s=window.firebase.db,[n,o]=e.split("/");return l(s,"Projects",t,"Collections",n,"Published",o)}function Ee(e,t){let s=window.__ROOT_CTX.rootConfig.projectId,n=window.firebase.db,[o,i]=e.split("/");return l(n,"Projects",s,"Collections",o,"Drafts",i,"Versions",t)}async function Ve(e){let t=window.__ROOT_CTX.rootConfig.projectId,s=window.firebase.db,n={};e.forEach(i=>{let[r,c]=i.split("/");r in n?n[r].push(c):n[r]=[c]});let o={};return await Promise.all(Object.entries(n).map(async([i,r])=>{let c=I(s,"Projects",t,"Collections",i,"Drafts"),a=x(c,D(J(),"in",r));(await j(a)).forEach(d=>{let g=`${i}/${d.id}`;o[g]=d.data()})})),o}async function qt(e,t){let s=window.firebase.db,n=b(e),o=I(s,n.path,"Versions"),i=t?.limit??50,r=x(o,O("sys.modifiedAt","desc"),F(i));t?.tags&&(r=x(r,D("tags","array-contains-any",t.tags))),t?.cursor&&(r=x(r,Y(t.cursor)));let c=await j(r),a=[],f=null;return c.forEach(d=>{let g={...d.data(),_versionId:d.id};a.push(g),f=d}),{versions:a,lastDoc:f,hasMore:c.size===i}}async function Gt(e,t){let s=b(e),n={"sys.modifiedAt":m(),"sys.modifiedBy":window.firebase.user.email,"sys.assets":K(t.fields||{}),fields:t.fields||{}};await w(s,n),p("doc.restore_version",{metadata:{docId:e,versionModifiedAt:t.sys?.modifiedAt,versionModifiedBy:t.sys?.modifiedBy}})}var $e=/^(before|after):(\d+)$/,Ne=10*1e3;async function Ue(e,t){let s=String(t).match($e);if(s)return await Xe(e,s[1],parseInt(s[2]));let n;t==="draft"?n=b(e):t==="published"?n=Le(e):n=Ee(e,t);let o=await B(n);return o.exists()?o.data():null}async function Xe(e,t,s){let n=window.firebase.db,o=b(e),i=I(n,o.path,"Versions"),r=k.fromMillis(s-Ne),c;t==="before"?c=x(i,D("sys.modifiedAt","<",r),O("sys.modifiedAt","desc"),F(1)):c=x(i,D("sys.modifiedAt",">=",r),O("sys.modifiedAt","asc"),F(1));let a=await j(c);return a.empty?t==="after"?await Ue(e,"draft"):null:a.docs[0].data()}async function Ht(e,t){if(!t?.spreadsheetId)throw new Error("no spreadsheet id");let s=b(e),n={"sys.l10nSheet":{spreadsheetId:t.spreadsheetId,gid:t.gid||0,linkedAt:m(),linkedBy:window.firebase.user.email}};await w(s,n),p("doc.link_sheet",{metadata:{docId:e,sheetId:t}})}async function Qt(e){let t=b(e),s={"sys.l10nSheet":R()};await w(t,s),p("doc.unlink_sheet",{metadata:{docId:e}})}async function Kt(e){let t=b(e),o=(await B(t)).data()?.sys?.l10nSheet||{};return o?.spreadsheetId?{spreadsheetId:o.spreadsheetId,gid:o.gid||0}:null}function he(e,t){let s={};for(let n in e){let o=e[n];if(be(o))if(o.toMillis)s[n]=o.toMillis();else if(Object.hasOwn(o,"_array")&&Array.isArray(o._array)){let i=o._array.map(r=>{let c={...he(o[r]||{},t),_arrayKey:r};return t?.removeArrayKey&&delete c._arrayKey,c});s[n]=i}else s[n]=he(o,t);else s[n]=o}return s}async function zt(e,t){let s=await window.fetch("/cms/api/ai.diff",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({docId:e,beforeVersion:t?.beforeVersion||"published",afterVersion:t?.afterVersion||"draft"})}),n=await s.text(),o=null;try{o=JSON.parse(n)}catch{}if(!s.ok||o?.success===!1){let i=o&&(o.error||o.message)||n;throw new Error(i||"Failed to fetch AI summary")}return typeof o?.summary=="string"?o.summary:typeof o?.data?.summary=="string"?o.data.summary:!o&&n?n:""}function be(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null}function Wt(e){let[t,s]=e.split("/");return{id:e,collection:t,slug:s}}function we(e){if(qe(e))return k.fromMillis(e.seconds*1e3);if(ce(e))return e.time=Date.now(),e;if(Array.isArray(e))return e.map(t=>we(t));if(be(e)){let t={};return Object.keys(e).forEach(s=>{t[s]=we(e[s])}),t}return e}function qe(e){return e?.type==="firestore/timestamp/1.0"}export{ce as a,We as b,De as c,ae as d,rt as e,ct as f,_ as g,at as h,Be as i,lt as j,dt as k,P as l,ft as m,ut as n,mt as o,pt as p,gt as q,yt as r,je as s,ht as t,wt as u,_e as v,K as w,fe as x,ke as y,bt as z,Ft as A,vt as B,ve as C,Mt as D,Pt as E,St as F,Ot as G,Lt as H,Et as I,Vt as J,$t as K,Pe as L,Nt as M,Se as N,Ut as O,Oe as P,Xt as Q,Ve as R,qt as S,Gt as T,Ue as U,Ht as V,Qt as W,Kt as X,he as Y,zt as Z,Wt as _,we as $};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as j,d as B,e as a,g as O,i as U,j as q}from"./chunk-LROR6N3B.js";import{a as g,b as p,f as K,i as k,j as D,k as M}from"./chunk-KUCVLANF.js";M();q();var d,R;function Z(e){return!R||(typeof R=="string"?e.startsWith(R):R.test(e))}function N(e,t){let n="";if(d=void 0,t&&t.type==="click"){if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||t.button!==0)return e;let r=t.composedPath().find(c=>c.nodeName=="A"&&c.href),o=r&&r.getAttribute("href");if(!r||r.origin!=location.origin||/^#/.test(o)||!/^(_?self)?$/i.test(r.target)||!Z(o)||r.download)return e;d=!0,t.preventDefault(),n=r.href.replace(location.origin,"")}else t&&t.url?(d=!t.replace,n=t.url):n=location.pathname+location.search;return d===!0?history.pushState(null,"",n):d===!1&&history.replaceState(null,"",n),n}var V=(e,t,n={})=>{e=e.split("/").filter(Boolean),t=(t||"").split("/").filter(Boolean),n.params||(n.params={});for(let r=0,o,c;r<Math.max(e.length,t.length);r++){let[,s,f,l]=(t[r]||"").match(/^(:?)(.*?)([+*?]?)$/);if(o=e[r],!(!s&&f==o)){if(!s&&o&&l=="*"){n.rest="/"+e.slice(r).map(decodeURIComponent).join("/");break}if(!s||!o&&l!="?"&&l!="*")return;if(c=l=="+"||l=="*",c?o=e.slice(r).map(decodeURIComponent).join("/")||void 0:o&&(o=decodeURIComponent(o)),n.params[f]=o,f in n||(n[f]=o),c)break}}return n};function E(e){let[t,n]=j(N,e.url||location.pathname+location.search);e.scope&&(R=e.scope);let r=d===!0,o=O(()=>{let c=new URL(t,location.origin),s=c.pathname.replace(/\/+$/g,"")||"/";return{url:t,path:s,query:Object.fromEntries(c.searchParams),route:(f,l)=>n({url:f,replace:l}),wasPush:r}},[t]);return B(()=>(addEventListener("click",n),addEventListener("popstate",n),()=>{removeEventListener("click",n),removeEventListener("popstate",n)}),[]),p(E.ctx.Provider,{value:o},e.children)}var ee=Promise.resolve();function $(e){let[t,n]=j(u=>u+1,0),{url:r,query:o,wasPush:c,path:s}=T();if(!r)throw new Error("preact-iso's <Router> must be used within a <LocationProvider>, see: https://github.com/preactjs/preact-iso#locationprovider");let{rest:f=s,params:l={}}=U(H),S=a(!1),z=a(s),C=a(0),i=a(),_=a(),h=a(),b=a(!1),P=a();P.current=!1;let A,I,m;K(e.children).some(u=>{if(V(f,u.props.path,m={...u.props,path:f,query:o,params:Object.assign({},l),rest:""}))return A=k(u,m);u.props.default&&(I=k(u,m))});let v=A||I,Y=i.current&&i.current.__u&x&&i.current.__u&L,F=i.current&&i.current.__h,G=O(()=>{_.current=i.current,i.current=p(H.Provider,{value:m},v);let u=_.current&&_.current.props.children;return!u||!v||v.type!==u.type||v.props.component!==u.props.component?(this.__v&&this.__v.__k&&this.__v.__k.reverse(),C.current++,!0):!1},[r,JSON.stringify(m)]);Y?(i.current.__u|=x,i.current.__u|=L):F&&(i.current.__h=!0);let Q=_.current;return _.current=null,this.__c=(u,y)=>{P.current=!0,_.current=Q,e.onLoadStart&&e.onLoadStart(r),S.current=!0;let X=C.current;u.then(()=>{X===C.current&&(_.current=null,i.current&&(y.__h&&(i.current.__h=y.__h),y.__u&L&&(i.current.__u|=L),y.__u&x&&(i.current.__u|=x)),ee.then(n))})},B(()=>{let u=this.__v&&this.__v.__e;if(P.current){!b.current&&!h.current&&(h.current=u);return}!b.current&&h.current&&(h.current!==u&&h.current.remove(),h.current=null),b.current=!0,z.current!==s&&(c&&scrollTo(0,0),e.onRouteChange&&e.onRouteChange(r),z.current=s),e.onLoadEnd&&S.current&&e.onLoadEnd(r),S.current=!1},[s,c,t]),G?[p(w,{r:i}),p(w,{r:_})]:p(w,{r:i})}var x=32,L=128,w=({r:e})=>e.current;$.Provider=E;E.ctx=D({});var H=D({}),te=e=>p(e.component,e),T=()=>U(E.ctx);M();q();var J=g.__b;g.__b=e=>{e.type&&e.type._forwarded&&e.ref&&(e.props.ref=e.ref,e.ref=null),J&&J(e)};var W=g.__e;g.__e=(e,t,n)=>{if(e&&e.then){let r=t;for(;r=r.__;)if(r.__c&&r.__c.__c)return t.__e==null&&(t.__c.__z=[n.__e],t.__e=n.__e,t.__k=n.__k),t.__k||(t.__k=[]),r.__c.__c(e,t)}W&&W(e,t,n)};M();function ve(...e){return e.filter(t=>!!t).join(" ")||void 0}export{E as a,$ as b,te as c,T as d,ve as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{e as r}from"./chunk-BUNR5EU3.js";import{Ga as i}from"./chunk-LROR6N3B.js";function f(n){let{className:a,as:l,size:t,weight:e,color:o,children:s,...x}=n;return i(l||"div",{...x,className:r(a,"text",t&&`size:${t}`,e&&`weight:${e}`,o&&`color:${o}`),children:s})}export{f as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as x,n as y}from"./chunk-
|
|
1
|
+
import{c as x,n as y}from"./chunk-VD6G5NV4.js";import{a as d,c as g,j as R}from"./chunk-LROR6N3B.js";var v=3600*1e3,p=new Map,P=new Map,h=new Set;function A(e){return e.trim().toLowerCase()}function E(e){let r=p.get(e);if(r){if(Date.now()-r.fetchedAt>v){p.delete(e);return}return r}}function M(){h.forEach(e=>e())}function T(e){let r=window.firebase.db,s=window.__ROOT_CTX.rootConfig.projectId;return x(r,"Projects",s,"UserProfiles",e)}function a(e){if(!e)return null;let r=E(A(e));return r?r.value:void 0}async function U(e){if(!e)return null;let r=A(e),s=E(r);if(s)return s.value;let n=P.get(r);if(n)return n;let i=(async()=>{try{let t=await y(T(r)),l=t.exists()?t.data():null;return p.set(r,{value:l,fetchedAt:Date.now()}),M(),l}catch(t){return console.error("failed to fetch user profile:",e,t),p.set(r,{value:null,fetchedAt:Date.now()}),null}finally{P.delete(r)}})();return P.set(r,i),i}function b(e){return h.add(e),()=>{h.delete(e)}}function O(e,r){if(!(r||e||"").trim())return"?";if(r){let t=r.trim().split(/\s+/).map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).filter(Boolean);if(t.length>=2)return(t[0][0]+t[1][0]).toUpperCase();if(t.length===1&&t[0].length>0)return t[0].slice(0,2).toUpperCase()}let i=(e.split("@")[0]||e).replace(/[^a-zA-Z0-9]/g,"");return i.length===0?"?":i.slice(0,2).toUpperCase()}function S(e){let r=e.trim();if(!r)return"?";let[s,n=""]=r.split("@"),t=(_(r)?n:s||r).replace(/[^a-zA-Z0-9]/g,"");return t.length===0?"?":t[0].toUpperCase()}function _(e){return e.trim().startsWith("*@")}function z(e){let r=["#1f6feb","#0e7490","#0f766e","#15803d","#9333ea","#c026d3","#db2777","#dc2626","#ea580c","#b45309"],s=0;for(let n=0;n<e.length;n++)s=s*31+e.charCodeAt(n)>>>0;return r[s%r.length]}R();function H(e){let r=e?a(e):null,[s,n]=d(r??null),[i,t]=d(!!e&&r===void 0);return g(()=>{if(!e){n(null),t(!1);return}let l=!1,o=a(e);o!==void 0?(n(o),t(!1)):(t(!0),U(e).then(f=>{l||(n(f),t(!1))}));let c=b(()=>{if(l||!e)return;let f=a(e);f!==void 0&&n(f)});return()=>{l=!0,c()}},[e]),{profile:s,loading:i}}function W(e){let r=e.filter(o=>!!o).map(o=>o.toLowerCase()),s=r.slice().sort().join(","),[n,i]=d(()=>{let o=new Map;return r.forEach(c=>{let f=a(c);f!==void 0&&o.set(c,f)}),o}),[t,l]=d(r.length>0);return g(()=>{if(r.length===0){i(new Map),l(!1);return}let o=!1;function c(){let u=new Map,w=!1;r.forEach(C=>{let m=a(C);m===void 0?w=!0:u.set(C,m)}),i(u),l(w)}c(),Promise.all(r.filter(u=>a(u)===void 0).map(u=>U(u))).then(()=>{o||c()});let f=b(()=>{o||c()});return()=>{o=!0,f()}},[s]),{profiles:n,loading:t}}export{O as a,S as b,_ as c,z as d,H as e,W as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as _,c as P}from"./chunk-
|
|
1
|
+
import{a as _,c as P}from"./chunk-JS6TK4OP.js";import{f as u}from"./chunk-KRNQ6L35.js";import{a as w,b as j,c as n,g as T,n as b,o as R,p as I,q as m,u as h,v as l,x as f}from"./chunk-VD6G5NV4.js";async function F(t,a){if(!t)throw new Error("missing data source id");let o=window.__ROOT_CTX.rootConfig.projectId,e=window.firebase.db,s=n(e,"Projects",o,"DataSources",t);await I(s,{...a,id:t,createdAt:l(),createdBy:window.firebase.user.email}),u("datasource.create",{metadata:{datasourceId:t}})}async function G(){let t=window.__ROOT_CTX.rootConfig.projectId,a=window.firebase.db,o=j(a,"Projects",t,"DataSources"),e=T(o),s=await R(e),r=[];return s.forEach(c=>{r.push(c.data())}),r}async function S(t){let a=window.__ROOT_CTX.rootConfig.projectId,o=window.firebase.db,e=n(o,"Projects",a,"DataSources",t),s=await b(e);return s.exists()?s.data():null}async function O(t,a){let o=a?.mode||"draft",e=window.__ROOT_CTX.rootConfig.projectId,s=window.firebase.db,r=n(s,"Projects",e,"DataSources",t,"Data",o),c=await b(r);return c.exists()?c.data():null}async function U(t,a){let o=window.__ROOT_CTX.rootConfig.projectId,e=window.firebase.db,s=n(e,"Projects",o,"DataSources",t);await m(s,a),u("datasource.save",{metadata:{datasourceId:t}})}async function q(t){let a=window.__ROOT_CTX.rootConfig.projectId,o=window.firebase.db,e=n(o,"Projects",a,"DataSources",t);await m(e,{archivedAt:l(),archivedBy:window.firebase.user.email}),u("datasource.archive",{metadata:{datasourceId:t}})}async function H(t){let a=window.__ROOT_CTX.rootConfig.projectId,o=window.firebase.db,e=n(o,"Projects",a,"DataSources",t);await m(e,{archivedAt:h(),archivedBy:h()}),u("datasource.unarchive",{metadata:{datasourceId:t}})}async function W(t){let a=await S(t);if(!a)throw new Error(`data source not found: ${t}`);if(a.archivedAt)throw new Error(`data source is archived: ${t}`);if(a.type==="http"&&a.url&&!C(a.url)){let o=await fetch("/cms/api/data.sync",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({id:a.id})});if(o.status!==200){let e=await o.text();throw new Error(`sync failed: ${e}`)}}else{let{data:o,headers:e}=await x(a),s=window.__ROOT_CTX.rootConfig.projectId,r=window.firebase.db,c=n(r,"Projects",s,"DataSources",t),d=n(r,"Projects",s,"DataSources",t,"Data","draft"),p={...a,syncedAt:w.now(),syncedBy:window.firebase.user.email},i=f(r);i.set(d,{dataSource:p,data:o,...e?{headers:e}:{}}),i.update(c,{syncedAt:w.now(),syncedBy:window.firebase.user.email}),await i.commit()}console.log(`synced data source: ${t}`),u("datasource.sync",{metadata:{datasourceId:t}})}async function M(t){let a=await S(t);if(!a)throw new Error(`data source not found: ${t}`);if(a.archivedAt)throw new Error(`data source is archived: ${t}`);let o=window.__ROOT_CTX.rootConfig.projectId,e=window.firebase.db,s=n(e,"Projects",o,"DataSources",t),r=n(e,"Projects",o,"DataSources",t,"Data","draft"),c=n(e,"Projects",o,"DataSources",t,"Data","published"),d=await O(t,{mode:"draft"}),p={...a,publishedAt:w.now(),publishedBy:window.firebase.user.email},i=f(e);i.set(c,{dataSource:p,data:d?.data||null,...d?.headers?{headers:d.headers}:{}}),i.update(r,{dataSource:p}),i.update(s,{publishedAt:w.now(),publishedBy:window.firebase.user.email}),await i.commit(),console.log(`published data ${t}`),u("datasource.publish",{metadata:{datasourceId:t}})}async function k(t){if(!await S(t))throw new Error(`data source not found: ${t}`);let o=window.__ROOT_CTX.rootConfig.projectId,e=window.firebase.db,s=n(e,"Projects",o,"DataSources",t),r=n(e,"Projects",o,"DataSources",t,"Data","draft"),c=n(e,"Projects",o,"DataSources",t,"Data","published"),d=f(e);d.update(s,{publishedAt:h(),publishedBy:h()}),(await b(r)).exists()&&d.update(r,{"dataSource.publishedAt":h(),"dataSource.publishedBy":h()}),d.delete(c),await d.commit(),console.log(`unpublished data source: ${t}`),u("datasource.unpublish",{metadata:{datasourceId:t}})}async function J(t,a){if(t.length===0)return;let o=window.firebase.db,e=window.__ROOT_CTX.rootConfig.projectId,s=a?.batch||f(o);for(let r of t){let c=await S(r);if(!c)throw new Error(`data source not found: ${r}`);if(c.archivedAt)throw new Error(`data source is archived: ${r}`);let d=await O(r,{mode:"draft"}),p=n(o,"Projects",e,"DataSources",r),i=n(o,"Projects",e,"DataSources",r,"Data","draft"),y=n(o,"Projects",e,"DataSources",r,"Data","published"),D={...c,publishedAt:l(),publishedBy:window.firebase.user.email};s.set(y,{dataSource:D,data:d?.data||null,...d?.headers?{headers:d.headers}:{}}),s.update(i,{dataSource:D}),s.update(p,{publishedAt:l(),publishedBy:window.firebase.user.email}),u("datasource.publish",{metadata:{datasourceId:r}})}(!a?.batch||a?.commitBatch)&&await s.commit()}async function N(t){let a=window.__ROOT_CTX.rootConfig.projectId,o=window.firebase.db,e=n(o,"Projects",a,"DataSources",t),s=n(o,"Projects",a,"DataSources",t,"Data","draft"),r=n(o,"Projects",a,"DataSources",t,"Data","published"),c=f(o);c.delete(s),c.delete(r),c.delete(e),await c.commit(),console.log(`deleted data source ${t}`),u("datasource.delete",{metadata:{datasourceId:t}})}async function x(t){if(t.type==="http")return{data:await B(t)};if(t.type==="gsheet")return await v(t);throw new Error(`unsupported data source: ${t.type}`)}async function v(t){let a=P(t.url);if(!a?.spreadsheetId)throw new Error(`failed to parse google sheet url: ${t.url}`);let e=await new _(a.spreadsheetId).getSheet(a.gid??0);if(!e)throw new Error(`could not find sheet: ${t.url}`);let s=t.dataFormat||"map",[r,c]=await e.getValues();return s==="array"?{data:[r,c],headers:r}:{data:c.map(p=>{let i={};return p.forEach((y,D)=>{let g=r[D];g&&(i[g]=String(y||""))}),i}),headers:r}}async function B(t){if(!C(t.url))throw new Error(`unsupported url: ${t.url}`);let a=await fetch(t.url,{method:t.httpOptions?.method||"GET",headers:t.httpOptions?.headers||[],body:t.httpOptions?.body||void 0});if(a.status!==200){let e=await a.text();throw new Error(`req failed: ${e}`)}return String(a.headers.get("content-type")).includes("application/json")?await a.json():a.text()}function C(t){return t&&t.startsWith("/")}export{F as a,G as b,S as c,O as d,U as e,q as f,H as g,W as h,M as i,k as j,J as k,N as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as p,d as U,e as g}from"./chunk-
|
|
1
|
+
import{a as p,d as U,e as g}from"./chunk-CAY5NM4Z.js";import{e as u}from"./chunk-BUNR5EU3.js";import{Fa as d,Ga as t,a as f,aa as v,j as x}from"./chunk-LROR6N3B.js";import{d as c}from"./chunk-KUCVLANF.js";x();function A(e){let a=e.size||30,l=e.withTooltip!==!1,{profile:_}=g(e.profile===void 0?e.email:null),s=e.profile!==void 0?e.profile:_,r=s?.email||e.email||"",i=s?.displayName||"",o=s?.photoURL||"",[n,h]=f(!1),m=t(v,{className:u("UserAvatar",e.inactive&&"UserAvatar--inactive",e.className),src:!n&&o?o:void 0,alt:i||r,size:a,radius:"xl",style:!o||n?{backgroundColor:U(r||i||"?"),color:"#fff",fontWeight:600,fontSize:Math.max(10,Math.round(a*.4))}:void 0,imageProps:{onError:()=>h(!0)},children:!o||n?p(r,i):null});return l?t(A.Tooltip,{email:r,displayName:i,children:m}):m}A.Tooltip=function(a){if(!a.email&&!a.displayName)return t(c,{children:a.children});let l=t("div",{className:"UserAvatar__tooltip",children:[a.displayName&&t("div",{className:"UserAvatar__tooltip__name",children:a.displayName}),a.email&&t("div",{className:"UserAvatar__tooltip__email",children:a.email})]});return t(d,{label:l,position:"bottom",withArrow:!0,transition:"pop",children:a.children})};export{A as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function i(){return window.__ROOT_CTX.allowedIframeOrigins||[]}function a(e){return e?e===window.location.origin?!0:i().includes(e):!1}function s(){if(!document.referrer)return"";try{return new URL(document.referrer).origin}catch{return""}}function d(e){let o=window.parent!==window?window.parent:window.opener;if(!o)return;let t={root:e},n=i();if(n.length===0){let r=s();r&&o.postMessage(t,r);return}n.forEach(r=>{o.postMessage(t,r)})}export{a,d as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,h as n,j as s}from"./chunk-
|
|
1
|
+
import{a,h as n,j as s}from"./chunk-LROR6N3B.js";s();s();function T(e,r){let[c,i]=a(()=>{try{let t=window.localStorage.getItem(e);return t?JSON.parse(t):r}catch(t){return console.error(t),r}}),u=n(t=>{i(l=>{let o=typeof t=="function"?t(l):t;return window.localStorage.setItem(e,JSON.stringify(o)),o})},[e]);return[c,u]}export{T as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as t}from"./chunk-BUNR5EU3.js";import{Fa as l,Ga as i}from"./chunk-LROR6N3B.js";import{d as n}from"./chunk-KUCVLANF.js";function c(o){return o.condition?i(l,{label:o.label,children:i("div",{className:t(o.className,"ConditionalTooltip"),style:o.style,children:i("div",{className:"ConditionalTooltip__content",children:o.children})})}):i(n,{children:o.children})}export{c as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as D,K as x,R as A,b as k,da as L,fa as B,i as I,ra as F,v as d,y as M}from"./chunk-
|
|
1
|
+
import{A as D,K as x,R as A,b as k,da as L,fa as B,i as I,ra as F,v as d,y as M}from"./chunk-LROR6N3B.js";import{j as R}from"./chunk-KUCVLANF.js";M();M();var h=R(null);h.displayName="@mantine/modals/ModalsContext";function j(){let o=I(h);if(!o)throw new Error("[@mantine/modals] useModals hook was called outside of context, wrap your app with ModalsProvider component");return o}M();M();var W=Object.defineProperty,X=Object.defineProperties,Y=Object.getOwnPropertyDescriptors,T=Object.getOwnPropertySymbols,Z=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable,V=(o,r,e)=>r in o?W(o,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[r]=e,S=(o,r)=>{for(var e in r||(r={}))Z.call(r,e)&&V(o,e,r[e]);if(T)for(var e of T(r))$.call(r,e)&&V(o,e,r[e]);return o},G=(o,r)=>X(o,Y(r));function q({id:o,cancelProps:r,confirmProps:e,labels:c={cancel:"",confirm:""},closeOnConfirm:n=!0,closeOnCancel:s=!0,groupProps:m,onCancel:u,onConfirm:f,children:v}){let{cancel:_,confirm:y}=c,P=j(),w=l=>{typeof r?.onClick=="function"&&r?.onClick(l),typeof u=="function"&&u(),s&&P.closeModal(o)},b=l=>{typeof e?.onClick=="function"&&e?.onClick(l),typeof f=="function"&&f(),n&&P.closeModal(o)};return d.createElement(d.Fragment,null,v&&d.createElement(A,{mb:"md"},v),d.createElement(B,S({position:"right"},m),d.createElement(L,G(S({variant:"default"},r),{onClick:w}),r?.children||_),d.createElement(L,G(S({},e),{onClick:b}),e?.children||y)))}function z(o,r){switch(r.type){case"OPEN":return{current:r.payload,modals:[...o.modals,r.payload]};case"CLOSE":return{current:o.modals[o.modals.length-2]||null,modals:o.modals.filter(e=>e.id!==r.payload)};case"CLOSE_ALL":return{current:o.current,modals:[]};default:return o}}var oo=Object.defineProperty,ro=Object.defineProperties,eo=Object.getOwnPropertyDescriptors,g=Object.getOwnPropertySymbols,K=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable,H=(o,r,e)=>r in o?oo(o,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[r]=e,E=(o,r)=>{for(var e in r||(r={}))K.call(r,e)&&H(o,e,r[e]);if(g)for(var e of g(r))Q.call(r,e)&&H(o,e,r[e]);return o},J=(o,r)=>ro(o,eo(r)),N=(o,r)=>{var e={};for(var c in o)K.call(o,c)&&r.indexOf(c)<0&&(e[c]=o[c]);if(o!=null&&g)for(var c of g(o))r.indexOf(c)<0&&Q.call(o,c)&&(e[c]=o[c]);return e};function to(o){if(!o)return{confirmProps:{},modalProps:{}};let r=o,{id:e,children:c,onCancel:n,onConfirm:s,closeOnConfirm:m,closeOnCancel:u,cancelProps:f,confirmProps:v,groupProps:_,labels:y}=r,P=N(r,["id","children","onCancel","onConfirm","closeOnConfirm","closeOnCancel","cancelProps","confirmProps","groupProps","labels"]);return{confirmProps:{id:e,children:c,onCancel:n,onConfirm:s,closeOnConfirm:m,closeOnCancel:u,cancelProps:f,confirmProps:v,groupProps:_,labels:y},modalProps:E({id:e},P)}}function no({children:o,modalProps:r,labels:e,modals:c}){let[n,s]=k(z,{modals:[],current:null}),m=l=>{n.modals.forEach(t=>{var a,p,i,O;t.type==="confirm"&&l&&((p=(a=t.props)==null?void 0:a.onCancel)==null||p.call(a)),(O=(i=t.props)==null?void 0:i.onClose)==null||O.call(i)}),s({type:"CLOSE_ALL"})},u=l=>{let t=l.id||x();return s({type:"OPEN",payload:{id:t,type:"content",props:l}}),t},f=l=>{let t=l.id||x();return s({type:"OPEN",payload:{id:t,type:"confirm",props:l}}),t},v=(l,t)=>{let a=t.id||x();return s({type:"OPEN",payload:{id:a,type:"context",props:t,ctx:l}}),a},_=(l,t)=>{var a,p,i,O;if(n.modals.length<=1){m(t);return}let C=n.modals.find(U=>U.id===l);C?.type==="confirm"&&t&&((p=(a=C.props)==null?void 0:a.onCancel)==null||p.call(a)),(O=(i=C?.props)==null?void 0:i.onClose)==null||O.call(i),s({type:"CLOSE",payload:C.id})},y={modals:n.modals,openModal:u,openConfirmModal:f,openContextModal:v,closeModal:_,closeAll:m},P=()=>{var l;switch((l=n.current)==null?void 0:l.type){case"context":{let t=n.current.props,{innerProps:a}=t,p=N(t,["innerProps"]),i=c[n.current.ctx];return{modalProps:p,content:d.createElement(i,{innerProps:a,context:y,id:n.current.id})}}case"confirm":{let{modalProps:t,confirmProps:a}=to(n.current.props);return{modalProps:t,content:d.createElement(q,J(E({},a),{id:n.current.id,labels:n.current.props.labels||e}))}}case"content":{let t=n.current.props,{children:a}=t;return{modalProps:N(t,["children"]),content:d.createElement(d.Fragment,null,a)}}default:return{modalProps:{},content:null}}},{modalProps:w,content:b}=P();return d.createElement(h.Provider,{value:y},d.createElement(F,J(E(E({},r),w),{opened:n.modals.length>0,onClose:()=>_(n.current.id)}),b),o)}function bo(){let o=D();return{overlayColor:o.colorScheme==="dark"?o.colors.dark[9]:o.colors.gray[2],overlayOpacity:.55,overlayBlur:3}}export{j as a,no as b,bo as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as Q,e as z,f as N,g as Z}from"./chunk-344GZOGG.js";import{a as ee}from"./chunk-YDO2EDVY.js";import{a as G,c as K,n as g,p as P,q as B,u as b}from"./chunk-EGEB6N4J.js";import{c as V,e as O,h as S,k as L,y as j}from"./chunk-4CUWZQXT.js";import{b as ie,d as ne}from"./chunk-PVAE643M.js";var re=ie((ke,te)=>{"use strict";function fe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let r,o=0;return function(...a){clearTimeout(r);let n=Date.now(),c=n-o,d=t-c;d<=0?(o=n,e.apply(this,a)):r=setTimeout(()=>{o=Date.now(),e.apply(this,a)},d)}}te.exports=fe});j();var se=ne(re(),1);j();j();var oe=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},i=(e,t,r)=>(oe(e,t,"read from private field"),r?r.call(e):t.get(e)),p=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},C=(e,t,r,o)=>(oe(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r);function me(e,t){return t!=null?(0,se.default)(e,t):e}var y,U,W,$,k,R,A,J,X,Ie=class{constructor(e=[]){p(this,y,void 0),p(this,U,"ready"),p(this,W,void 0),p(this,$,new Set),p(this,k,new Set),p(this,R,new Set),this.pushMessage=t=>{C(this,y,i(this,y).concat(t)),i(this,A).call(this)},this.popMessage=()=>{C(this,y,i(this,y).slice(0,-1)),i(this,A).call(this)},this.replaceMessage=(t,r)=>{C(this,y,[...i(this,y).slice(0,t),this.snapshot(r),...i(this,y).slice(t+1)]),i(this,A).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,r)=>{let o=r?me(t,r):t;return i(this,$).add(o),()=>{i(this,$).delete(o)}},this["~registerStatusCallback"]=t=>(i(this,k).add(t),()=>{i(this,k).delete(t)}),this["~registerErrorCallback"]=t=>(i(this,R).add(t),()=>{i(this,R).delete(t)}),p(this,A,()=>{i(this,$).forEach(t=>t())}),p(this,J,()=>{i(this,k).forEach(t=>t())}),p(this,X,()=>{i(this,R).forEach(t=>t())}),C(this,y,e)}get status(){return i(this,U)}set status(e){C(this,U,e),i(this,J).call(this)}get error(){return i(this,W)}set error(e){C(this,W,e),i(this,X).call(this)}get messages(){return i(this,y)}set messages(e){C(this,y,[...e]),i(this,A).call(this)}};y=new WeakMap;U=new WeakMap;W=new WeakMap;$=new WeakMap;k=new WeakMap;R=new WeakMap;A=new WeakMap;J=new WeakMap;X=new WeakMap;var x,ae=class extends Q{constructor({messages:e,...t}){let r=new Ie(e);super({...t,state:r}),p(this,x,void 0),this["~registerMessagesCallback"]=(o,s)=>i(this,x)["~registerMessagesCallback"](o,s),this["~registerStatusCallback"]=o=>i(this,x)["~registerStatusCallback"](o),this["~registerErrorCallback"]=o=>i(this,x)["~registerErrorCallback"](o),C(this,x,r)}};x=new WeakMap;function Le({experimental_throttle:e,resume:t=!1,...r}={}){let o=O("chat"in r?{}:{onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen});"chat"in r||(o.current={onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen});let s={...r,onToolCall:u=>{var h,m;return(m=(h=o.current).onToolCall)==null?void 0:m.call(h,u)},onData:u=>{var h,m;return(m=(h=o.current).onData)==null?void 0:m.call(h,u)},onFinish:u=>{var h,m;return(m=(h=o.current).onFinish)==null?void 0:m.call(h,u)},onError:u=>{var h,m;return(m=(h=o.current).onError)==null?void 0:m.call(h,u)},sendAutomaticallyWhen:u=>{var h,m,H;return(H=(m=(h=o.current).sendAutomaticallyWhen)==null?void 0:m.call(h,u))!=null?H:!1}},a=O("chat"in r?r.chat:new ae(s));("chat"in r&&r.chat!==a.current||"id"in r&&a.current.id!==r.id)&&(a.current="chat"in r?r.chat:new ae(s));let c=S(u=>a.current["~registerMessagesCallback"](u,e),[e,a.current.id]),d=L(c,()=>a.current.messages,()=>a.current.messages),f=L(a.current["~registerStatusCallback"],()=>a.current.status,()=>a.current.status),l=L(a.current["~registerErrorCallback"],()=>a.current.error,()=>a.current.error),I=S(u=>{typeof u=="function"&&(u=u(a.current.messages)),a.current.messages=u},[a]);return V(()=>{t&&a.current.resumeStream()},[t,a]),{id:a.current.id,messages:d,setMessages:I,sendMessage:a.current.sendMessage,regenerate:a.current.regenerate,clearError:a.current.clearError,stop:a.current.stop,error:l,resumeStream:a.current.resumeStream,status:f,addToolResult:a.current.addToolOutput,addToolOutput:a.current.addToolOutput,addToolApprovalResponse:a.current.addToolApprovalResponse}}var Y=null;function _(){return Y||(Y=import("./ai-tools-4DWMFQS6.js")),Y}var ge=["doc_set","doc_create","doc_updateField","doc_edit","doc_duplicate"];function ye(e){return ge.includes(e)}function E(){let e=window;return{rootConfig:e.__ROOT_CTX.rootConfig,firebase:e.firebase}}function ve(e){let{collection:t,slug:r}=D(e);return`/cms/content/${encodeURIComponent(t)}/${encodeURIComponent(r)}`}function D(e){let t=e.indexOf("/");if(t<=0||t===e.length-1)throw new Error(`invalid docId: "${e}" (expected "Collection/slug")`);return{collection:e.slice(0,t),slug:e.slice(t+1).replace(/\//g,"--")}}function w(e){let{collection:t,slug:r}=D(e),{firebase:o,rootConfig:s}=E();return K(o.db,"Projects",s.projectId,"Collections",t,"Drafts",r)}function M(e){return Z(e,{isTimestamp:t=>t instanceof G,timestampToValue:t=>t.toMillis()})}function we(e){return JSON.parse(JSON.stringify(e??null))}function q(e){if(typeof e!="string")return e;let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function ce(e){return Array.isArray(e)?e.map(t=>{let r={op:t?.op,path:t?.path};return t&&"value"in t&&(r.value=q(t.value)),t&&t.index!==void 0&&t.index!==null&&(r.index=t.index),r}):[]}function de(e){switch(e.op){case"set":return`Set ${e.path}`;case"insert_item":return e.index===void 0?`Insert into ${e.path} (append)`:`Insert into ${e.path} at ${e.index}`;case"remove_item":return`Remove ${e.path}[${e.index}]`;default:return`${e.op} ${e.path}`}}function De(e,t,r){let o=t.split("."),s=e;for(let c=0;c<o.length-1;c++){let d=o[c],f=Array.isArray(s)?Number(d):d,l=o[c+1];(s[f]===void 0||s[f]===null)&&(s[f]=/^\d+$/.test(l)?[]:{}),s=s[f]}let a=o[o.length-1],n=Array.isArray(s)?Number(a):a;s[n]=r}async function le(e){let t=await g(w(e));if(!t.exists())return{found:!1,fields:{}};let r=t.data();return{found:!0,fields:M(r.fields||{}),raw:r}}function F(e){return{type:"cms-write-receipt",title:e.title,summary:e.summary,docId:e.docId,adminUrl:e.docId?ve(e.docId):void 0,details:[...e.details||[],{label:"Status",value:"Saved to draft"},{label:"Publishing",value:"Manual publish still required"}]}}function v(e){return{toolName:e.toolName,title:e.title,summary:e.summary,docId:e.docId,path:e.path,details:e.details||[],error:e.error,errors:e.errors,hint:e.hint}}async function Xe(e,t){if(!ye(e))throw new Error(`not a write tool: ${e}`);switch(e){case"doc_set":return pe(t);case"doc_create":return be(t);case"doc_updateField":return Ce(t);case"doc_edit":return _e(t);case"doc_duplicate":return Te(t)}}async function pe(e){let{collection:t}=D(e.docId),r=await T(t),{validateFields:o}=await _(),s=o(e.fields,r);if(s.length>0)return v({toolName:"doc_set",title:"Replace draft fields",summary:`Could not validate the replacement fields for ${e.docId}.`,docId:e.docId,error:"VALIDATION_FAILED",errors:s,hint:"The fields payload does not match the collection schema. Read the doc and schema, then retry with a valid payload."});let a=await le(e.docId);return{toolName:"doc_set",title:"Replace draft fields",summary:`Replace all draft fields for ${e.docId}.`,docId:e.docId,before:a.found?a.fields:{},after:e.fields||{},details:[{label:"Document",value:e.docId},{label:"Operation",value:a.found?"Replace draft":"Create draft"}]}}async function be(e){let{collection:t}=D(e.docId);if((await g(w(e.docId))).exists())return v({toolName:"doc_create",title:"Create draft document",summary:`${e.docId} already exists.`,docId:e.docId,error:"ALREADY_EXISTS",hint:"Use an unused slug, or use an update tool for the existing draft."});if(e.fields){let o=await T(t),{validateFields:s}=await _(),a=s(e.fields,o);if(a.length>0)return v({toolName:"doc_create",title:"Create draft document",summary:`Could not validate the initial fields for ${e.docId}.`,docId:e.docId,error:"VALIDATION_FAILED",errors:a,hint:"The fields payload does not match the collection schema."})}return{toolName:"doc_create",title:"Create draft document",summary:`Create ${e.docId} as a new draft document.`,docId:e.docId,before:{},after:e.fields||{},details:[{label:"Document",value:e.docId},{label:"Operation",value:"Create draft"}]}}async function Ce(e){let t=q(e.value),{collection:r}=D(e.docId),o=await T(r),{validateValueAtPath:s}=await _(),a=s(o,e.path,t);if(a.length>0)return v({toolName:"doc_updateField",title:"Update draft field",summary:`Could not validate ${e.path} for ${e.docId}.`,docId:e.docId,path:e.path,error:"VALIDATION_FAILED",errors:a,hint:"The value does not match the field schema. Inspect the doc and schema, then retry with a valid value."});let n=w(e.docId),c=await g(n);if(!c.exists())return v({toolName:"doc_updateField",title:"Update draft field",summary:`${e.docId} does not exist.`,docId:e.docId,path:e.path,error:"NOT_FOUND",hint:`Doc "${e.docId}" does not exist.`});let d=c.data(),f=z(d.fields||{},e.path);if(!f.ok)return v({toolName:"doc_updateField",title:"Update draft field",summary:`Could not resolve ${e.path} in ${e.docId}.`,docId:e.docId,path:e.path,error:"VALIDATION_FAILED",errors:[f.error],hint:"Use zero-based array indices for existing array items, or set the whole array field when appending or removing items."});let l=M(d.fields||{}),I=we(l);return De(I,e.path,t),{toolName:"doc_updateField",title:"Update draft field",summary:`Update ${e.path} in ${e.docId}.`,docId:e.docId,path:e.path,before:l,after:I,details:[{label:"Document",value:e.docId},{label:"Field path",value:e.path},{label:"Operation",value:"Update draft field"}]}}async function _e(e){let t=ce(e.operations),{collection:r}=D(e.docId),o=await T(r),s=await le(e.docId);if(!s.found)return v({toolName:"doc_edit",title:"Edit draft document",summary:`${e.docId} does not exist.`,docId:e.docId,error:"NOT_FOUND",hint:`Doc "${e.docId}" does not exist. Create it with \`doc_create\` first.`});let{applyDocEdits:a,validateFields:n}=await _(),c=a(s.fields,t);if(!c.ok)return v({toolName:"doc_edit",title:"Edit draft document",summary:`Operation ${c.error.opIndex+1} (${c.error.op}) could not be applied to ${e.docId}.`,docId:e.docId,error:"INVALID_OPERATION",errors:[c.error],hint:"Fix the failing operation. Use zero-based array indices, target arrays for insert_item/remove_item, and read the doc with `doc_get` to confirm the current shape."});let d=n(c.fields,o);return d.length>0?v({toolName:"doc_edit",title:"Edit draft document",summary:`The edits to ${e.docId} did not match the collection schema.`,docId:e.docId,error:"VALIDATION_FAILED",errors:d,hint:"The resulting fields do not match the collection schema. Inspect the doc and schema, then retry with valid values."}):{toolName:"doc_edit",title:"Edit draft document",summary:`Apply ${t.length} edit${t.length===1?"":"s"} to ${e.docId}.`,docId:e.docId,before:s.fields,after:c.fields,details:[{label:"Document",value:e.docId},...t.map((f,l)=>({label:`Operation ${l+1}`,value:de(f)}))]}}async function Te(e){let t=w(e.fromDocId),r=await g(t);if(!r.exists())return v({toolName:"doc_duplicate",title:"Duplicate draft document",summary:`${e.fromDocId} does not exist.`,docId:e.toDocId,error:"NOT_FOUND",hint:`Source doc "${e.fromDocId}" does not exist.`,details:[{label:"Source",value:e.fromDocId}]});let o=w(e.toDocId);if((await g(o)).exists())return v({toolName:"doc_duplicate",title:"Duplicate draft document",summary:`${e.toDocId} already exists.`,docId:e.toDocId,error:"ALREADY_EXISTS",hint:`Target doc "${e.toDocId}" already exists.`,details:[{label:"Source",value:e.fromDocId},{label:"Target",value:e.toDocId}]});let a=r.data(),n=M(a.fields||{});return{toolName:"doc_duplicate",title:"Duplicate draft document",summary:`Duplicate ${e.fromDocId} to ${e.toDocId}.`,docId:e.toDocId,before:{},after:n,details:[{label:"Source",value:e.fromDocId},{label:"Target",value:e.toDocId},{label:"Operation",value:"Create draft copy"}]}}async function T(e){return await ee(e)}async function Ae(e){let{collection:t,slug:r}=D(e.docId),o=await T(t),{validateFields:s}=await _(),a=s(e.fields,o);if(a.length>0)return{success:!1,docId:e.docId,error:"VALIDATION_FAILED",errors:a,hint:"The fields payload did not match the collection schema. Read the doc with `doc_get` for an example of the expected shape, then retry with a valid payload."};let{firebase:n}=E(),c=w(e.docId),d=await g(c),l=(d.exists()?d.data():{}).sys||{},I=n.user?.email||"root-cms-ai",u={id:e.docId,collection:t,slug:r,sys:{...l,createdAt:l.createdAt??b(),createdBy:l.createdBy??I,modifiedAt:b(),modifiedBy:I,locales:l.locales??["en"]},fields:N(e.fields)};return await P(c,u),{success:!0,docId:e.docId,receipt:F({title:"Updated draft document",summary:`Replaced all draft fields for ${e.docId}.`,docId:e.docId,details:[{label:"Document",value:e.docId},{label:"Operation",value:"Replace draft fields"}]})}}async function xe(e){let{collection:t,slug:r}=D(e.docId),o=w(e.docId);if((await g(o)).exists())return{success:!1,docId:e.docId,error:"ALREADY_EXISTS",hint:"A doc with this id already exists. Use `doc_set` to overwrite."};if(e.fields){let d=await T(t),{validateFields:f}=await _(),l=f(e.fields,d);if(l.length>0)return{success:!1,docId:e.docId,error:"VALIDATION_FAILED",errors:l,hint:"The fields payload did not match the collection schema."}}let{firebase:a}=E(),n=a.user?.email||"root-cms-ai",c={id:e.docId,collection:t,slug:r,sys:{createdAt:b(),createdBy:n,modifiedAt:b(),modifiedBy:n,locales:["en"]},fields:e.fields?N(e.fields):{}};return await P(o,c),{success:!0,docId:e.docId,receipt:F({title:"Created draft document",summary:`Created ${e.docId} as a new draft document.`,docId:e.docId,details:[{label:"Document",value:e.docId},{label:"Operation",value:"Create draft"}]})}}async function Ee(e){let t=q(e.value),{collection:r}=D(e.docId),o=await T(r),{validateValueAtPath:s}=await _(),a=s(o,e.path,t);if(a.length>0)return{success:!1,docId:e.docId,path:e.path,error:"VALIDATION_FAILED",errors:a,hint:"The value did not match the field schema. Inspect the doc with `doc_get` to see the expected shape, then retry with a valid value."};let n=w(e.docId),c=await g(n);if(!c.exists())return{success:!1,docId:e.docId,path:e.path,error:"NOT_FOUND",hint:`Doc "${e.docId}" does not exist.`};let d=c.data(),f=z(d.fields||{},e.path);if(!f.ok)return{success:!1,docId:e.docId,path:e.path,error:"VALIDATION_FAILED",errors:[f.error],hint:"The path could not be resolved against the current draft. Use zero-based array indices for existing array items, or set the whole array field when appending or removing items."};let{firebase:l}=E(),I=`fields.${f.path}`,u=N(t);return await B(n,{[I]:u,"sys.modifiedAt":b(),"sys.modifiedBy":l.user?.email||"root-cms-ai"}),{success:!0,docId:e.docId,path:e.path,receipt:F({title:"Updated draft field",summary:`Updated ${e.path} in ${e.docId}.`,docId:e.docId,details:[{label:"Document",value:e.docId},{label:"Field path",value:e.path},{label:"Operation",value:"Update draft field"}]})}}async function Oe(e){let t=ce(e.operations),{collection:r}=D(e.docId),o=await T(r),s=w(e.docId),a=await g(s);if(!a.exists())return{success:!1,docId:e.docId,error:"NOT_FOUND",hint:`Doc "${e.docId}" does not exist.`};let n=a.data(),c=M(n.fields||{}),{applyDocEdits:d,validateFields:f}=await _(),l=d(c,t);if(!l.ok)return{success:!1,docId:e.docId,error:"INVALID_OPERATION",errors:[l.error],hint:"Fix the failing operation. Use zero-based array indices, target arrays for insert_item/remove_item, and read the doc with `doc_get` to confirm the current shape."};let I=f(l.fields,o);if(I.length>0)return{success:!1,docId:e.docId,error:"VALIDATION_FAILED",errors:I,hint:"The resulting fields did not match the collection schema. Inspect the doc with `doc_get`, then retry with valid values."};let{firebase:u}=E();return await B(s,{fields:N(l.fields),"sys.modifiedAt":b(),"sys.modifiedBy":u.user?.email||"root-cms-ai"}),{success:!0,docId:e.docId,receipt:F({title:"Edited draft document",summary:`Applied ${t.length} edit${t.length===1?"":"s"} to ${e.docId}.`,docId:e.docId,details:[{label:"Document",value:e.docId},{label:"Operations",value:String(t.length)},...t.map((h,m)=>({label:`Operation ${m+1}`,value:de(h)}))]})}}async function Se(e){let t=w(e.fromDocId),r=await g(t);if(!r.exists())return{success:!1,error:"NOT_FOUND",hint:`Source doc "${e.fromDocId}" does not exist.`};let o=w(e.toDocId);if((await g(o)).exists())return{success:!1,error:"ALREADY_EXISTS",hint:`Target doc "${e.toDocId}" already exists.`};let{collection:a,slug:n}=D(e.toDocId),{firebase:c}=E(),d=c.user?.email||"root-cms-ai",f=r.data(),l={id:e.toDocId,collection:a,slug:n,sys:{createdAt:b(),createdBy:d,modifiedAt:b(),modifiedBy:d,locales:f.sys?.locales??["en"]},fields:f.fields||{}};return await P(o,l),{success:!0,fromDocId:e.fromDocId,toDocId:e.toDocId,receipt:F({title:"Duplicated draft document",summary:`Duplicated ${e.fromDocId} to ${e.toDocId}.`,docId:e.toDocId,details:[{label:"Source",value:e.fromDocId},{label:"Target",value:e.toDocId},{label:"Operation",value:"Create draft copy"}]})}}async function Ne(e){let t=await fetch("/cms/api/ai.translate",{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({sourceText:e.sourceText,targetLocales:e.targetLocales,description:e.description})});if(!t.ok)throw new Error(`ai.translate failed: ${t.status}`);let r=await t.json();if(!r.success)throw new Error(r.error||"translation failed");return{translations:r.translations}}var $e={doc_set:Ae,doc_create:xe,doc_updateField:Ee,doc_edit:Oe,doc_duplicate:Se,doc_translateField:Ne};async function Ye(e,t){let r=$e[e];if(!r)return{error:"UNKNOWN_TOOL",toolName:e};try{return await r(t)}catch(o){return console.error(`tool ${e} failed:`,o),{error:"TOOL_EXECUTION_FAILED",message:o?.message||String(o)}}}export{Le as a,ye as b,Xe as c,Ye as d};
|
|
1
|
+
import{c as Q,e as z,f as N,g as Z}from"./chunk-344GZOGG.js";import{a as ee}from"./chunk-YDO2EDVY.js";import{a as G,c as K,n as g,p as P,q as B,v as b}from"./chunk-VD6G5NV4.js";import{c as V,e as O,h as S,k as L,y as j}from"./chunk-LROR6N3B.js";import{b as ie,d as ne}from"./chunk-PVAE643M.js";var re=ie((ke,te)=>{"use strict";function fe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let r,o=0;return function(...a){clearTimeout(r);let n=Date.now(),c=n-o,d=t-c;d<=0?(o=n,e.apply(this,a)):r=setTimeout(()=>{o=Date.now(),e.apply(this,a)},d)}}te.exports=fe});j();var se=ne(re(),1);j();j();var oe=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},i=(e,t,r)=>(oe(e,t,"read from private field"),r?r.call(e):t.get(e)),p=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},C=(e,t,r,o)=>(oe(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r);function me(e,t){return t!=null?(0,se.default)(e,t):e}var y,U,W,$,k,R,A,J,X,Ie=class{constructor(e=[]){p(this,y,void 0),p(this,U,"ready"),p(this,W,void 0),p(this,$,new Set),p(this,k,new Set),p(this,R,new Set),this.pushMessage=t=>{C(this,y,i(this,y).concat(t)),i(this,A).call(this)},this.popMessage=()=>{C(this,y,i(this,y).slice(0,-1)),i(this,A).call(this)},this.replaceMessage=(t,r)=>{C(this,y,[...i(this,y).slice(0,t),this.snapshot(r),...i(this,y).slice(t+1)]),i(this,A).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,r)=>{let o=r?me(t,r):t;return i(this,$).add(o),()=>{i(this,$).delete(o)}},this["~registerStatusCallback"]=t=>(i(this,k).add(t),()=>{i(this,k).delete(t)}),this["~registerErrorCallback"]=t=>(i(this,R).add(t),()=>{i(this,R).delete(t)}),p(this,A,()=>{i(this,$).forEach(t=>t())}),p(this,J,()=>{i(this,k).forEach(t=>t())}),p(this,X,()=>{i(this,R).forEach(t=>t())}),C(this,y,e)}get status(){return i(this,U)}set status(e){C(this,U,e),i(this,J).call(this)}get error(){return i(this,W)}set error(e){C(this,W,e),i(this,X).call(this)}get messages(){return i(this,y)}set messages(e){C(this,y,[...e]),i(this,A).call(this)}};y=new WeakMap;U=new WeakMap;W=new WeakMap;$=new WeakMap;k=new WeakMap;R=new WeakMap;A=new WeakMap;J=new WeakMap;X=new WeakMap;var x,ae=class extends Q{constructor({messages:e,...t}){let r=new Ie(e);super({...t,state:r}),p(this,x,void 0),this["~registerMessagesCallback"]=(o,s)=>i(this,x)["~registerMessagesCallback"](o,s),this["~registerStatusCallback"]=o=>i(this,x)["~registerStatusCallback"](o),this["~registerErrorCallback"]=o=>i(this,x)["~registerErrorCallback"](o),C(this,x,r)}};x=new WeakMap;function Le({experimental_throttle:e,resume:t=!1,...r}={}){let o=O("chat"in r?{}:{onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen});"chat"in r||(o.current={onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen});let s={...r,onToolCall:u=>{var h,m;return(m=(h=o.current).onToolCall)==null?void 0:m.call(h,u)},onData:u=>{var h,m;return(m=(h=o.current).onData)==null?void 0:m.call(h,u)},onFinish:u=>{var h,m;return(m=(h=o.current).onFinish)==null?void 0:m.call(h,u)},onError:u=>{var h,m;return(m=(h=o.current).onError)==null?void 0:m.call(h,u)},sendAutomaticallyWhen:u=>{var h,m,H;return(H=(m=(h=o.current).sendAutomaticallyWhen)==null?void 0:m.call(h,u))!=null?H:!1}},a=O("chat"in r?r.chat:new ae(s));("chat"in r&&r.chat!==a.current||"id"in r&&a.current.id!==r.id)&&(a.current="chat"in r?r.chat:new ae(s));let c=S(u=>a.current["~registerMessagesCallback"](u,e),[e,a.current.id]),d=L(c,()=>a.current.messages,()=>a.current.messages),f=L(a.current["~registerStatusCallback"],()=>a.current.status,()=>a.current.status),l=L(a.current["~registerErrorCallback"],()=>a.current.error,()=>a.current.error),I=S(u=>{typeof u=="function"&&(u=u(a.current.messages)),a.current.messages=u},[a]);return V(()=>{t&&a.current.resumeStream()},[t,a]),{id:a.current.id,messages:d,setMessages:I,sendMessage:a.current.sendMessage,regenerate:a.current.regenerate,clearError:a.current.clearError,stop:a.current.stop,error:l,resumeStream:a.current.resumeStream,status:f,addToolResult:a.current.addToolOutput,addToolOutput:a.current.addToolOutput,addToolApprovalResponse:a.current.addToolApprovalResponse}}var Y=null;function _(){return Y||(Y=import("./ai-tools-4DWMFQS6.js")),Y}var ge=["doc_set","doc_create","doc_updateField","doc_edit","doc_duplicate"];function ye(e){return ge.includes(e)}function E(){let e=window;return{rootConfig:e.__ROOT_CTX.rootConfig,firebase:e.firebase}}function ve(e){let{collection:t,slug:r}=D(e);return`/cms/content/${encodeURIComponent(t)}/${encodeURIComponent(r)}`}function D(e){let t=e.indexOf("/");if(t<=0||t===e.length-1)throw new Error(`invalid docId: "${e}" (expected "Collection/slug")`);return{collection:e.slice(0,t),slug:e.slice(t+1).replace(/\//g,"--")}}function w(e){let{collection:t,slug:r}=D(e),{firebase:o,rootConfig:s}=E();return K(o.db,"Projects",s.projectId,"Collections",t,"Drafts",r)}function M(e){return Z(e,{isTimestamp:t=>t instanceof G,timestampToValue:t=>t.toMillis()})}function we(e){return JSON.parse(JSON.stringify(e??null))}function q(e){if(typeof e!="string")return e;let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function ce(e){return Array.isArray(e)?e.map(t=>{let r={op:t?.op,path:t?.path};return t&&"value"in t&&(r.value=q(t.value)),t&&t.index!==void 0&&t.index!==null&&(r.index=t.index),r}):[]}function de(e){switch(e.op){case"set":return`Set ${e.path}`;case"insert_item":return e.index===void 0?`Insert into ${e.path} (append)`:`Insert into ${e.path} at ${e.index}`;case"remove_item":return`Remove ${e.path}[${e.index}]`;default:return`${e.op} ${e.path}`}}function De(e,t,r){let o=t.split("."),s=e;for(let c=0;c<o.length-1;c++){let d=o[c],f=Array.isArray(s)?Number(d):d,l=o[c+1];(s[f]===void 0||s[f]===null)&&(s[f]=/^\d+$/.test(l)?[]:{}),s=s[f]}let a=o[o.length-1],n=Array.isArray(s)?Number(a):a;s[n]=r}async function le(e){let t=await g(w(e));if(!t.exists())return{found:!1,fields:{}};let r=t.data();return{found:!0,fields:M(r.fields||{}),raw:r}}function F(e){return{type:"cms-write-receipt",title:e.title,summary:e.summary,docId:e.docId,adminUrl:e.docId?ve(e.docId):void 0,details:[...e.details||[],{label:"Status",value:"Saved to draft"},{label:"Publishing",value:"Manual publish still required"}]}}function v(e){return{toolName:e.toolName,title:e.title,summary:e.summary,docId:e.docId,path:e.path,details:e.details||[],error:e.error,errors:e.errors,hint:e.hint}}async function Xe(e,t){if(!ye(e))throw new Error(`not a write tool: ${e}`);switch(e){case"doc_set":return pe(t);case"doc_create":return be(t);case"doc_updateField":return Ce(t);case"doc_edit":return _e(t);case"doc_duplicate":return Te(t)}}async function pe(e){let{collection:t}=D(e.docId),r=await T(t),{validateFields:o}=await _(),s=o(e.fields,r);if(s.length>0)return v({toolName:"doc_set",title:"Replace draft fields",summary:`Could not validate the replacement fields for ${e.docId}.`,docId:e.docId,error:"VALIDATION_FAILED",errors:s,hint:"The fields payload does not match the collection schema. Read the doc and schema, then retry with a valid payload."});let a=await le(e.docId);return{toolName:"doc_set",title:"Replace draft fields",summary:`Replace all draft fields for ${e.docId}.`,docId:e.docId,before:a.found?a.fields:{},after:e.fields||{},details:[{label:"Document",value:e.docId},{label:"Operation",value:a.found?"Replace draft":"Create draft"}]}}async function be(e){let{collection:t}=D(e.docId);if((await g(w(e.docId))).exists())return v({toolName:"doc_create",title:"Create draft document",summary:`${e.docId} already exists.`,docId:e.docId,error:"ALREADY_EXISTS",hint:"Use an unused slug, or use an update tool for the existing draft."});if(e.fields){let o=await T(t),{validateFields:s}=await _(),a=s(e.fields,o);if(a.length>0)return v({toolName:"doc_create",title:"Create draft document",summary:`Could not validate the initial fields for ${e.docId}.`,docId:e.docId,error:"VALIDATION_FAILED",errors:a,hint:"The fields payload does not match the collection schema."})}return{toolName:"doc_create",title:"Create draft document",summary:`Create ${e.docId} as a new draft document.`,docId:e.docId,before:{},after:e.fields||{},details:[{label:"Document",value:e.docId},{label:"Operation",value:"Create draft"}]}}async function Ce(e){let t=q(e.value),{collection:r}=D(e.docId),o=await T(r),{validateValueAtPath:s}=await _(),a=s(o,e.path,t);if(a.length>0)return v({toolName:"doc_updateField",title:"Update draft field",summary:`Could not validate ${e.path} for ${e.docId}.`,docId:e.docId,path:e.path,error:"VALIDATION_FAILED",errors:a,hint:"The value does not match the field schema. Inspect the doc and schema, then retry with a valid value."});let n=w(e.docId),c=await g(n);if(!c.exists())return v({toolName:"doc_updateField",title:"Update draft field",summary:`${e.docId} does not exist.`,docId:e.docId,path:e.path,error:"NOT_FOUND",hint:`Doc "${e.docId}" does not exist.`});let d=c.data(),f=z(d.fields||{},e.path);if(!f.ok)return v({toolName:"doc_updateField",title:"Update draft field",summary:`Could not resolve ${e.path} in ${e.docId}.`,docId:e.docId,path:e.path,error:"VALIDATION_FAILED",errors:[f.error],hint:"Use zero-based array indices for existing array items, or set the whole array field when appending or removing items."});let l=M(d.fields||{}),I=we(l);return De(I,e.path,t),{toolName:"doc_updateField",title:"Update draft field",summary:`Update ${e.path} in ${e.docId}.`,docId:e.docId,path:e.path,before:l,after:I,details:[{label:"Document",value:e.docId},{label:"Field path",value:e.path},{label:"Operation",value:"Update draft field"}]}}async function _e(e){let t=ce(e.operations),{collection:r}=D(e.docId),o=await T(r),s=await le(e.docId);if(!s.found)return v({toolName:"doc_edit",title:"Edit draft document",summary:`${e.docId} does not exist.`,docId:e.docId,error:"NOT_FOUND",hint:`Doc "${e.docId}" does not exist. Create it with \`doc_create\` first.`});let{applyDocEdits:a,validateFields:n}=await _(),c=a(s.fields,t);if(!c.ok)return v({toolName:"doc_edit",title:"Edit draft document",summary:`Operation ${c.error.opIndex+1} (${c.error.op}) could not be applied to ${e.docId}.`,docId:e.docId,error:"INVALID_OPERATION",errors:[c.error],hint:"Fix the failing operation. Use zero-based array indices, target arrays for insert_item/remove_item, and read the doc with `doc_get` to confirm the current shape."});let d=n(c.fields,o);return d.length>0?v({toolName:"doc_edit",title:"Edit draft document",summary:`The edits to ${e.docId} did not match the collection schema.`,docId:e.docId,error:"VALIDATION_FAILED",errors:d,hint:"The resulting fields do not match the collection schema. Inspect the doc and schema, then retry with valid values."}):{toolName:"doc_edit",title:"Edit draft document",summary:`Apply ${t.length} edit${t.length===1?"":"s"} to ${e.docId}.`,docId:e.docId,before:s.fields,after:c.fields,details:[{label:"Document",value:e.docId},...t.map((f,l)=>({label:`Operation ${l+1}`,value:de(f)}))]}}async function Te(e){let t=w(e.fromDocId),r=await g(t);if(!r.exists())return v({toolName:"doc_duplicate",title:"Duplicate draft document",summary:`${e.fromDocId} does not exist.`,docId:e.toDocId,error:"NOT_FOUND",hint:`Source doc "${e.fromDocId}" does not exist.`,details:[{label:"Source",value:e.fromDocId}]});let o=w(e.toDocId);if((await g(o)).exists())return v({toolName:"doc_duplicate",title:"Duplicate draft document",summary:`${e.toDocId} already exists.`,docId:e.toDocId,error:"ALREADY_EXISTS",hint:`Target doc "${e.toDocId}" already exists.`,details:[{label:"Source",value:e.fromDocId},{label:"Target",value:e.toDocId}]});let a=r.data(),n=M(a.fields||{});return{toolName:"doc_duplicate",title:"Duplicate draft document",summary:`Duplicate ${e.fromDocId} to ${e.toDocId}.`,docId:e.toDocId,before:{},after:n,details:[{label:"Source",value:e.fromDocId},{label:"Target",value:e.toDocId},{label:"Operation",value:"Create draft copy"}]}}async function T(e){return await ee(e)}async function Ae(e){let{collection:t,slug:r}=D(e.docId),o=await T(t),{validateFields:s}=await _(),a=s(e.fields,o);if(a.length>0)return{success:!1,docId:e.docId,error:"VALIDATION_FAILED",errors:a,hint:"The fields payload did not match the collection schema. Read the doc with `doc_get` for an example of the expected shape, then retry with a valid payload."};let{firebase:n}=E(),c=w(e.docId),d=await g(c),l=(d.exists()?d.data():{}).sys||{},I=n.user?.email||"root-cms-ai",u={id:e.docId,collection:t,slug:r,sys:{...l,createdAt:l.createdAt??b(),createdBy:l.createdBy??I,modifiedAt:b(),modifiedBy:I,locales:l.locales??["en"]},fields:N(e.fields)};return await P(c,u),{success:!0,docId:e.docId,receipt:F({title:"Updated draft document",summary:`Replaced all draft fields for ${e.docId}.`,docId:e.docId,details:[{label:"Document",value:e.docId},{label:"Operation",value:"Replace draft fields"}]})}}async function xe(e){let{collection:t,slug:r}=D(e.docId),o=w(e.docId);if((await g(o)).exists())return{success:!1,docId:e.docId,error:"ALREADY_EXISTS",hint:"A doc with this id already exists. Use `doc_set` to overwrite."};if(e.fields){let d=await T(t),{validateFields:f}=await _(),l=f(e.fields,d);if(l.length>0)return{success:!1,docId:e.docId,error:"VALIDATION_FAILED",errors:l,hint:"The fields payload did not match the collection schema."}}let{firebase:a}=E(),n=a.user?.email||"root-cms-ai",c={id:e.docId,collection:t,slug:r,sys:{createdAt:b(),createdBy:n,modifiedAt:b(),modifiedBy:n,locales:["en"]},fields:e.fields?N(e.fields):{}};return await P(o,c),{success:!0,docId:e.docId,receipt:F({title:"Created draft document",summary:`Created ${e.docId} as a new draft document.`,docId:e.docId,details:[{label:"Document",value:e.docId},{label:"Operation",value:"Create draft"}]})}}async function Ee(e){let t=q(e.value),{collection:r}=D(e.docId),o=await T(r),{validateValueAtPath:s}=await _(),a=s(o,e.path,t);if(a.length>0)return{success:!1,docId:e.docId,path:e.path,error:"VALIDATION_FAILED",errors:a,hint:"The value did not match the field schema. Inspect the doc with `doc_get` to see the expected shape, then retry with a valid value."};let n=w(e.docId),c=await g(n);if(!c.exists())return{success:!1,docId:e.docId,path:e.path,error:"NOT_FOUND",hint:`Doc "${e.docId}" does not exist.`};let d=c.data(),f=z(d.fields||{},e.path);if(!f.ok)return{success:!1,docId:e.docId,path:e.path,error:"VALIDATION_FAILED",errors:[f.error],hint:"The path could not be resolved against the current draft. Use zero-based array indices for existing array items, or set the whole array field when appending or removing items."};let{firebase:l}=E(),I=`fields.${f.path}`,u=N(t);return await B(n,{[I]:u,"sys.modifiedAt":b(),"sys.modifiedBy":l.user?.email||"root-cms-ai"}),{success:!0,docId:e.docId,path:e.path,receipt:F({title:"Updated draft field",summary:`Updated ${e.path} in ${e.docId}.`,docId:e.docId,details:[{label:"Document",value:e.docId},{label:"Field path",value:e.path},{label:"Operation",value:"Update draft field"}]})}}async function Oe(e){let t=ce(e.operations),{collection:r}=D(e.docId),o=await T(r),s=w(e.docId),a=await g(s);if(!a.exists())return{success:!1,docId:e.docId,error:"NOT_FOUND",hint:`Doc "${e.docId}" does not exist.`};let n=a.data(),c=M(n.fields||{}),{applyDocEdits:d,validateFields:f}=await _(),l=d(c,t);if(!l.ok)return{success:!1,docId:e.docId,error:"INVALID_OPERATION",errors:[l.error],hint:"Fix the failing operation. Use zero-based array indices, target arrays for insert_item/remove_item, and read the doc with `doc_get` to confirm the current shape."};let I=f(l.fields,o);if(I.length>0)return{success:!1,docId:e.docId,error:"VALIDATION_FAILED",errors:I,hint:"The resulting fields did not match the collection schema. Inspect the doc with `doc_get`, then retry with valid values."};let{firebase:u}=E();return await B(s,{fields:N(l.fields),"sys.modifiedAt":b(),"sys.modifiedBy":u.user?.email||"root-cms-ai"}),{success:!0,docId:e.docId,receipt:F({title:"Edited draft document",summary:`Applied ${t.length} edit${t.length===1?"":"s"} to ${e.docId}.`,docId:e.docId,details:[{label:"Document",value:e.docId},{label:"Operations",value:String(t.length)},...t.map((h,m)=>({label:`Operation ${m+1}`,value:de(h)}))]})}}async function Se(e){let t=w(e.fromDocId),r=await g(t);if(!r.exists())return{success:!1,error:"NOT_FOUND",hint:`Source doc "${e.fromDocId}" does not exist.`};let o=w(e.toDocId);if((await g(o)).exists())return{success:!1,error:"ALREADY_EXISTS",hint:`Target doc "${e.toDocId}" already exists.`};let{collection:a,slug:n}=D(e.toDocId),{firebase:c}=E(),d=c.user?.email||"root-cms-ai",f=r.data(),l={id:e.toDocId,collection:a,slug:n,sys:{createdAt:b(),createdBy:d,modifiedAt:b(),modifiedBy:d,locales:f.sys?.locales??["en"]},fields:f.fields||{}};return await P(o,l),{success:!0,fromDocId:e.fromDocId,toDocId:e.toDocId,receipt:F({title:"Duplicated draft document",summary:`Duplicated ${e.fromDocId} to ${e.toDocId}.`,docId:e.toDocId,details:[{label:"Source",value:e.fromDocId},{label:"Target",value:e.toDocId},{label:"Operation",value:"Create draft copy"}]})}}async function Ne(e){let t=await fetch("/cms/api/ai.translate",{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({sourceText:e.sourceText,targetLocales:e.targetLocales,description:e.description})});if(!t.ok)throw new Error(`ai.translate failed: ${t.status}`);let r=await t.json();if(!r.success)throw new Error(r.error||"translation failed");return{translations:r.translations}}var $e={doc_set:Ae,doc_create:xe,doc_updateField:Ee,doc_edit:Oe,doc_duplicate:Se,doc_translateField:Ne};async function Ye(e,t){let r=$e[e];if(!r)return{error:"UNKNOWN_TOOL",toolName:e};try{return await r(t)}catch(o){return console.error(`tool ${e} failed:`,o),{error:"TOOL_EXECUTION_FAILED",message:o?.message||String(o)}}}export{Le as a,ye as b,Xe as c,Ye as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as t}from"./chunk-
|
|
1
|
+
import{a as t}from"./chunk-QHJOTXYB.js";function s(e){if(typeof e=="object"&&e!==null){let o=e;if(typeof o.code=="string"&&typeof o.message=="string")return`${o.code}: ${o.message}`;if(typeof o.body=="string")return o.body;if(typeof o.message=="string")return o.message}return String(e)}async function i(e){try{await e()}catch(o){console.error(o);let r=s(o);t({title:"Error",message:r,color:"red",autoClose:!1})}}export{s as a,i as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as h}from"./chunk-YDO2EDVY.js";import{
|
|
1
|
+
import{a as h}from"./chunk-YDO2EDVY.js";import{a as x}from"./chunk-5MV6XVGA.js";import{g as y}from"./chunk-YMBBWVBB.js";import{c as f,n as g}from"./chunk-VD6G5NV4.js";async function b(e){let t=window.firebase.db,r=window.__ROOT_CTX.rootConfig.projectId,[o,a]=e.split("/",2),i=await h(o),n=f(t,"Projects",r,"Collections",o,"Drafts",a),c=(await g(n)).data()||{},p=new Set;return m(p,i.fields,c.fields||{},i.types||{}),Array.from(p)}async function C(e){let t=window.firebase.db,r=window.__ROOT_CTX.rootConfig.projectId,[o,a]=e.split("/",2),i=await h(o),n=f(t,"Projects",r,"Collections",o,"Drafts",a),c=(await g(n)).data()||{},p=new Map;return d(p,i.fields,c.fields||{},i.types||{}),p}function m(e,t,r,o={}){t.forEach(a=>{if(!a.id)return;let i=r[a.id],n=`@${a.id}`,s=r[n];s?.translate===!1||s?.disableTranslations||R(e,a,i,o,s)})}function d(e,t,r,o={}){t.forEach(a=>{if(!a.id)return;let i=r[a.id],n=`@${a.id}`,s=r[n];if(s?.translate===!1||s?.disableTranslations)return;let c=s?.description;S(e,a,i,o,c,s)})}function R(e,t,r,o={},a){if(!r)return;function i(n){let s=y(n);s&&e.add(s)}if(t.type==="object")m(e,t.fields||[],r,o);else if(t.type==="array"){let n=r._array||[];for(let s of n)R(e,t.of,r[s],o)}else if(t.type==="string"||t.type==="select")t.translate&&i(r);else if(t.type==="image")t.translate&&r&&r.alt&&t.alt!==!1&&a?.alt!==!1&&i(r.alt);else if(t.type==="multiselect"){if(t.translate&&Array.isArray(r))for(let n of r)i(n)}else if(t.type==="oneof"){let n=t.types||[],s;typeof n[0]=="string"?n.includes(r._type)&&(s=o[r._type]):s=n.find(c=>c.name===r._type),s&&m(e,s.fields||[],r,o)}else t.type==="richtext"?t.translate&&T(e,r):console.log(`extract: ignoring field, id=${t.id}, type=${t.type}`)}function S(e,t,r,o={},a,i){if(!r)return;function n(s){let c=y(s);if(c){let p=e.get(c);(!p||!p.description)&&e.set(c,{description:a})}}if(t.type==="object")d(e,t.fields||[],r,o);else if(t.type==="array"){let s=r._array||[];for(let c of s)S(e,t.of,r[c],o,a)}else if(t.type==="string"||t.type==="select")t.translate&&n(r);else if(t.type==="image")t.translate&&r&&r.alt&&t.alt!==!1&&i?.alt!==!1&&n(r.alt);else if(t.type==="multiselect"){if(t.translate&&Array.isArray(r))for(let s of r)n(s)}else if(t.type==="oneof"){let s=t.types||[],c;typeof s[0]=="string"?s.includes(r._type)&&(c=o[r._type]):c=s.find(p=>p.name===r._type),c&&d(e,c.fields||[],r,o)}else if(t.type==="richtext"&&t.translate){let s=new Set;T(s,r),s.forEach(c=>n(c))}}function T(e,t){(t?.blocks||[]).forEach(o=>{l(e,o)})}function l(e,t){if(!t?.type)return;function r(n){if(!n)return;let s=y(n);s&&e.add(s)}function o(n){n&&Object.values(n).forEach(s=>{a(s)})}function a(n){if(typeof n=="string"){r(n);return}if(Array.isArray(n)){n.forEach(s=>a(s));return}x(n)&&Object.values(n).forEach(s=>a(s))}function i(n){n&&n.forEach(s=>{r(s.content),o(s.components),i(s.items)})}t.type==="heading"||t.type==="paragraph"?(r(t.data?.text),o(t.data?.components)):t.type==="orderedList"||t.type==="unorderedList"?i(t.data?.items):t.type==="html"?r(t.data?.html):t.type==="table"&&(t.data?.rows||[]).forEach(s=>{(s.cells||[]).forEach(p=>{(p.blocks||[]).forEach(w=>{l(e,w)})})})}export{b as a,C as b,R as c};
|