import{bq as le,j as e,cH as de,a as P,a8 as k,e as E,T as y,H as x,k as F,ef as v,fD as ue,bh as q,cb as pe,fE as ge,aE as me,br as he,aF as U,aG as B,fF as fe,bE as xe,d4 as ye,fG as Te,bz as Ae,d5 as ke,bQ as Ee,aA as W,P as M,w as Ie,ap as be,r as m,b as je,bp as Ce,z as Se,aj as Pe,v as _e,ak as ve,b4 as Re,b5 as Oe,B as Le,aI as V}from"./strapi-BZkmC8So.js";import{b as Me,c as Ne,d as we}from"./apiTokens-BlBkv4sS.js";import{A as _}from"./constants-Q2dfXdfa.js";import{a as $e,b as De,L as Ue,c as Be,F as Fe,T as Ge}from"./TokenTypeSelect-d7MG1RvI.js";import{t as He,m as qe}from"./tail-Bml3mJ14.js";import"./transferTokens-B0GX_QyP.js";import"./index-DfpctvFQ.js";import"./index-BRVyLNfZ.js";import"./_baseMap-BpnwNTes.js";import"./_baseEach-Bbd_J5Xg.js";const Ve=le.injectEndpoints({endpoints:s=>({getPermissions:s.query({query:()=>"/admin/content-api/permissions",transformResponse:t=>t.data}),getRoutes:s.query({query:()=>"/admin/content-api/routes",transformResponse:t=>t.data})}),overrideExisting:!1}),{useGetPermissionsQuery:Qe,useGetRoutesQuery:Ye}=Ve,[Ke,We]=de("ApiTokenPermissionsContext"),ze=({children:s,...t})=>e.jsx(Ke,{...t,children:s}),G=()=>We("useApiTokenPermissions"),Je=({errors:s={},onChange:t,canEditInputs:a,isCreating:i,values:n={},apiToken:u={},onDispatch:c,setHasChangedPermissions:h})=>{const{formatMessage:r}=P(),p=({target:{value:l}})=>{h(!1),l==="full-access"&&c({type:"SELECT_ALL_ACTIONS"}),l==="read-only"&&c({type:"ON_CHANGE_READ_ONLY"})},I=[{value:"read-only",label:{id:"Settings.tokens.types.read-only",defaultMessage:"Read-only"}},{value:"full-access",label:{id:"Settings.tokens.types.full-access",defaultMessage:"Full access"}},{value:"custom",label:{id:"Settings.tokens.types.custom",defaultMessage:"Custom"}}];return e.jsx(k,{background:"neutral0",hasRadius:!0,shadow:"filterShadow",paddingTop:6,paddingBottom:6,paddingLeft:7,paddingRight:7,children:e.jsxs(E,{direction:"column",alignItems:"stretch",gap:4,children:[e.jsx(y,{variant:"delta",tag:"h2",children:r({id:"global.details",defaultMessage:"Details"})}),e.jsxs(x.Root,{gap:5,children:[e.jsx(x.Item,{col:6,xs:12,direction:"column",alignItems:"stretch",children:e.jsx($e,{error:s.name,value:n.name,canEditInputs:a,onChange:t})},"name"),e.jsx(x.Item,{col:6,xs:12,direction:"column",alignItems:"stretch",children:e.jsx(De,{error:s.description,value:n.description,canEditInputs:a,onChange:t})},"description"),e.jsx(x.Item,{col:6,xs:12,direction:"column",alignItems:"stretch",children:e.jsx(Ue,{isCreating:i,error:s.lifespan,value:n.lifespan,onChange:t,token:u})},"lifespan"),e.jsx(x.Item,{col:6,xs:12,direction:"column",alignItems:"stretch",children:e.jsx(Be,{value:n.type,error:s.type,label:{id:"Settings.tokens.form.type",defaultMessage:"Token type"},onChange:l=>{p({target:{value:l}}),t({target:{name:"type",value:l}})},options:I,canEditInputs:a})},"type")]})]})})},Xe=s=>{switch(s){case"POST":return{text:"success600",border:"success200",background:"success100"};case"GET":return{text:"secondary600",border:"secondary200",background:"secondary100"};case"PUT":return{text:"warning600",border:"warning200",background:"warning100"};case"DELETE":return{text:"danger600",border:"danger200",background:"danger100"};default:return{text:"neutral600",border:"neutral200",background:"neutral100"}}},Ze=F(k)`
  margin: -1px;
  border-radius: ${({theme:s})=>s.spaces[1]} 0 0 ${({theme:s})=>s.spaces[1]};
`,et=({route:s={handler:"Nocontroller.error",method:"GET",path:"/there-is-no-path"}})=>{const{formatMessage:t}=P(),{method:a,handler:i,path:n}=s,u=n?He(n.split("/")):[],[c="",h=""]=i?i.split("."):[],r=Xe(s.method);return e.jsxs(E,{direction:"column",alignItems:"stretch",gap:2,children:[e.jsxs(y,{variant:"delta",tag:"h3",children:[t({id:"Settings.apiTokens.createPage.BoundRoute.title",defaultMessage:"Bound route to"})," ",e.jsx("span",{children:c}),e.jsxs(y,{variant:"delta",textColor:"primary600",children:[".",h]})]}),e.jsxs(E,{hasRadius:!0,background:"neutral0",borderColor:"neutral200",gap:0,children:[e.jsx(Ze,{background:r.background,borderColor:r.border,padding:2,children:e.jsx(y,{fontWeight:"bold",textColor:r.text,children:a})}),e.jsx(k,{paddingLeft:2,paddingRight:2,children:qe(u,p=>e.jsxs(y,{textColor:p.includes(":")?"neutral600":"neutral900",children:["/",p]},p))})]})]})},tt=()=>{const{value:{selectedAction:s,routes:t}}=G(),{formatMessage:a}=P(),i=s?.split(".")[0];return e.jsx(x.Item,{col:5,background:"neutral150",paddingTop:6,paddingBottom:6,paddingLeft:7,paddingRight:7,style:{minHeight:"100%"},direction:"column",alignItems:"stretch",children:s?e.jsx(E,{direction:"column",alignItems:"stretch",gap:2,children:i&&i in t&&t[i].map(n=>n.config.auth?.scope?.includes(s)||n.handler===s?e.jsx(et,{route:n},n.handler):null)}):e.jsxs(E,{direction:"column",alignItems:"stretch",gap:2,children:[e.jsx(y,{variant:"delta",tag:"h3",children:a({id:"Settings.apiTokens.createPage.permissions.header.title",defaultMessage:"Advanced settings"})}),e.jsx(y,{tag:"p",textColor:"neutral600",children:a({id:"Settings.apiTokens.createPage.permissions.header.hint",defaultMessage:"Select the application's actions or the plugin's actions and click on the cog icon to display the bound route"})})]})})},Q=ge`
  background: ${s=>s.theme.colors.primary100};

  #cog {
    opacity: 1;
  }
`,st=F(k)`
  display: flex;
  justify-content: space-between;
  align-items: center;

  #cog {
    opacity: 0;
    path {
      fill: ${s=>s.theme.colors.primary600};
    }
  }

  /* Show active style both on hover and when the action is selected */
  ${s=>s.$isActive&&Q}
  &:hover {
    ${Q}
  }
`,nt=F.div`
  flex: 1;
  align-self: center;
  border-top: 1px solid ${({theme:s})=>s.colors.neutral150};
`,at=({controllers:s=[],label:t,orderNumber:a=0,disabled:i=!1})=>{const{value:{onChangeSelectAll:n,onChange:u,selectedActions:c,setSelectedAction:h,selectedAction:r}}=G(),{formatMessage:p}=P(),I=l=>l===r;return e.jsxs(v.Item,{value:`${t}-${a}`,children:[e.jsx(v.Header,{variant:a%2?"primary":"secondary",children:e.jsx(v.Trigger,{children:ue(t)})}),e.jsx(v.Content,{children:s?.map(l=>{const R=l.actions.every(g=>c.includes(g.actionId)),N=l.actions.some(g=>c.includes(g.actionId));return e.jsxs(k,{children:[e.jsxs(E,{justifyContent:"space-between",alignItems:"center",padding:4,children:[e.jsx(k,{paddingRight:4,children:e.jsx(y,{variant:"sigma",textColor:"neutral600",children:l?.controller})}),e.jsx(nt,{}),e.jsx(k,{paddingLeft:4,children:e.jsx(q,{checked:!R&&N?"indeterminate":R,onCheckedChange:()=>{n({target:{value:[...l.actions]}})},disabled:i,children:p({id:"app.utils.select-all",defaultMessage:"Select all"})})})]}),e.jsx(x.Root,{gap:4,padding:4,children:l?.actions&&l?.actions.map(g=>e.jsx(x.Item,{col:6,direction:"column",alignItems:"stretch",children:e.jsxs(st,{$isActive:I(g.actionId),padding:2,hasRadius:!0,children:[e.jsx(q,{checked:c.includes(g.actionId),name:g.actionId,onCheckedChange:()=>{u({target:{value:g.actionId}})},disabled:i,children:g.action}),e.jsx("button",{type:"button","data-testid":"action-cog",onClick:()=>h({target:{value:g.actionId}}),style:{display:"inline-flex",alignItems:"center"},children:e.jsx(pe,{id:"cog"})})]})},g.actionId))})]},`${t}.${l?.controller}`)})})]})},it=({section:s=null,...t})=>e.jsx(k,{children:e.jsx(v.Root,{size:"M",children:s&&s.map((a,i)=>e.jsx(at,{label:a.label,controllers:a.controllers,orderNumber:i,...t},a.apiId))})}),ot=({...s})=>{const{value:{data:t}}=G(),{formatMessage:a}=P();return e.jsxs(x.Root,{gap:0,shadow:"filterShadow",hasRadius:!0,background:"neutral0",children:[e.jsxs(x.Item,{col:7,paddingTop:6,paddingBottom:6,paddingLeft:7,paddingRight:7,direction:"column",alignItems:"stretch",gap:6,children:[e.jsxs(E,{direction:"column",alignItems:"stretch",gap:2,children:[e.jsx(y,{variant:"delta",tag:"h2",children:a({id:"Settings.apiTokens.createPage.permissions.title",defaultMessage:"Permissions"})}),e.jsx(y,{tag:"p",textColor:"neutral600",children:a({id:"Settings.apiTokens.createPage.permissions.description",defaultMessage:"Only actions bound by a route are listed below."})})]}),t?.permissions&&e.jsx(it,{section:t?.permissions,...s})]}),e.jsx(tt,{})]})},rt=me().shape({name:U().max(100).required(B.required.id),type:U().oneOf(["read-only","full-access","custom"]).required(B.required.id),description:U().nullable(),lifespan:he().integer().min(0).nullable().defined(B.required.id)});function ct(s,t,a,i){for(var n=a-1,u=s.length;++n<u;)if(i(s[n],t))return n;return-1}var lt=ct,dt=xe,ut=Te,pt=lt,gt=ye,mt=fe,ht=Array.prototype,Y=ht.splice;function ft(s,t,a,i){var n=i?pt:ut,u=-1,c=t.length,h=s;for(s===t&&(t=mt(t)),a&&(h=dt(s,gt(a)));++u<c;)for(var r=0,p=t[u],I=a?a(p):p;(r=n(h,I,r,i))>-1;)h!==s&&Y.call(h,r,1),Y.call(s,r,1);return s}var xt=ft,yt=xt;function Tt(s,t){return s&&s.length&&t&&t.length?yt(s,t):s}var At=Tt,kt=ke,Et=At,It=kt(Et),bt=It;const K=Ae(bt),jt=s=>{const t={allActionsIds:[],permissions:[]};return t.permissions=Object.entries(s).map(([a,i])=>({apiId:a,label:a.split("::")[1],controllers:Object.keys(i.controllers).map(n=>({controller:n,actions:n in i.controllers?i.controllers[n].map(u=>{const c=`${a}.${n}.${u}`;return a.includes("api::")&&t.allActionsIds.push(c),{action:u,actionId:c}}).flat():[]})).flat()})),t},Ct={data:{allActionsIds:[],permissions:[]},routes:{},selectedAction:"",selectedActions:[]},St=(s,t)=>Ee(s,a=>{switch(t.type){case"ON_CHANGE":{a.selectedActions.includes(t.value)?K(a.selectedActions,t.value):a.selectedActions.push(t.value);break}case"SELECT_ALL_IN_PERMISSION":{t.value.every(n=>a.selectedActions.includes(n.actionId))?t.value.forEach(n=>{K(a.selectedActions,n.actionId)}):t.value.forEach(n=>{a.selectedActions.push(n.actionId)});break}case"SELECT_ALL_ACTIONS":{a.selectedActions=[...a.data.allActionsIds];break}case"ON_CHANGE_READ_ONLY":{const i=a.data.allActionsIds.filter(n=>n.includes("find")||n.includes("findOne"));a.selectedActions=[...i];break}case"UPDATE_PERMISSIONS_LAYOUT":{a.data=jt(t.value);break}case"UPDATE_ROUTES":{a.routes={...t.value};break}case"UPDATE_PERMISSIONS":{a.selectedActions=[...t.value];break}case"SET_SELECTED_ACTION":{a.selectedAction=t.value;break}default:return a}}),Pt=()=>{const{formatMessage:s}=P(),{toggleNotification:t}=Ie(),{state:a}=be(),i=W(o=>o.admin_app.permissions),[n,u]=m.useState(a?.apiToken?.accessKey?{...a.apiToken}:null),[c,h]=m.useState(!!a?.apiToken?.accessKey),r=m.useRef(null),{trackUsage:p}=je(),I=Ce("EditView",o=>o.setCurrentStep),{allowedActions:{canCreate:l,canUpdate:R,canRegenerate:N}}=Se(i.settings?.["api-tokens"]),[g,f]=m.useReducer(St,Ct),O=Pe("/settings/api-tokens/:id")?.params?.id,T=O==="create",{_unstableFormatAPIError:A,_unstableFormatValidationErrors:H}=_e(),z=ve(),j=Qe(),C=Ye();m.useEffect(()=>{j.error&&t({type:"danger",message:A(j.error)})},[j.error,A,t]),m.useEffect(()=>{C.error&&t({type:"danger",message:A(C.error)})},[C.error,A,t]),m.useEffect(()=>{j.data&&f({type:"UPDATE_PERMISSIONS_LAYOUT",value:j.data})},[j.data]),m.useEffect(()=>{C.data&&f({type:"UPDATE_ROUTES",value:C.data})},[C.data]),m.useEffect(()=>{n&&(n.type==="read-only"&&f({type:"ON_CHANGE_READ_ONLY"}),n.type==="full-access"&&f({type:"SELECT_ALL_ACTIONS"}),n.type==="custom"&&f({type:"UPDATE_PERMISSIONS",value:n?.permissions}))},[n]),m.useEffect(()=>{p(T?"didAddTokenFromList":"didEditTokenFromList",{tokenType:_})},[T,p]);const{data:b,error:w,isLoading:J}=Me(O,{skip:!O||T||!!n});m.useEffect(()=>{w&&t({type:"danger",message:A(w)})},[w,A,t]),m.useEffect(()=>{b&&(u(b),b.type==="read-only"&&f({type:"ON_CHANGE_READ_ONLY"}),b.type==="full-access"&&f({type:"SELECT_ALL_ACTIONS"}),b.type==="custom"&&f({type:"UPDATE_PERMISSIONS",value:b?.permissions}))},[b]),m.useEffect(()=>{if(c)return r.current=setTimeout(()=>{h(!1)},3e4),()=>{r.current&&(clearTimeout(r.current),r.current=null)}},[c]);const[X]=Ne(),[Z]=we(),ee=async(o,S)=>{p(T?"willCreateToken":"willEditToken",{tokenType:_});try{if(T){const d=await X({...o,lifespan:o?.lifespan&&o.lifespan!=="0"?parseInt(o.lifespan.toString(),10):null,permissions:o.type==="custom"?g.selectedActions:null});if("error"in d){V(d.error)&&d.error.name==="ValidationError"?S.setErrors(H(d.error)):t({type:"danger",message:A(d.error)});return}t({type:"success",message:s({id:"notification.success.apitokencreated",defaultMessage:"API Token successfully created"})}),p("didCreateToken",{type:d.data.type,tokenType:_}),z(`../api-tokens/${d.data.id.toString()}`,{state:{apiToken:d.data},replace:!0}),I("apiTokens.success")}else{const d=await Z({id:O,name:o.name,description:o.description,type:o.type,permissions:o.type==="custom"?g.selectedActions:null});if("error"in d){V(d.error)&&d.error.name==="ValidationError"?S.setErrors(H(d.error)):t({type:"danger",message:A(d.error)});return}t({type:"success",message:s({id:"notification.success.apitokenedited",defaultMessage:"API Token successfully edited"})}),p("didEditToken",{type:d.data.type,tokenType:_})}}catch{t({type:"danger",message:s({id:"notification.error",defaultMessage:"Something went wrong"})})}},[te,$]=m.useState(!1),se=({target:{value:o}})=>{$(!0),f({type:"ON_CHANGE",value:o})},ne=({target:{value:o}})=>{$(!0),f({type:"SELECT_ALL_IN_PERMISSION",value:o})},ae=({target:{value:o}})=>{f({type:"SET_SELECTED_ACTION",value:o})},ie=()=>{h(o=>!o),r.current&&(clearTimeout(r.current),r.current=null)},oe={...g,onChange:se,onChangeSelectAll:ne,setSelectedAction:ae},D=R&&!T||l&&T,re=!!n?.accessKey;return J?e.jsx(M.Loading,{}):e.jsx(ze,{value:oe,children:e.jsxs(M.Main,{children:[e.jsx(M.Title,{children:s({id:"Settings.PageTitle",defaultMessage:"Settings - {name}"},{name:"API Tokens"})}),e.jsx(Re,{validationSchema:rt,validateOnChange:!1,initialValues:{name:n?.name||"",description:n?.description||"",type:n?.type,lifespan:n?.lifespan},enableReinitialize:!0,onSubmit:(o,S)=>ee(o,S),children:({errors:o,handleChange:S,isSubmitting:d,values:L,setFieldValue:ce})=>(te&&L?.type!=="custom"&&ce("type","custom"),e.jsxs(Oe,{children:[e.jsx(Fe,{title:{id:"Settings.apiTokens.createPage.title",defaultMessage:"Create API Token"},token:n,setToken:u,toggleToken:ie,showToken:c,canEditInputs:D,canRegenerate:N,canShowToken:re,isSubmitting:d,regenerateUrl:"/admin/api-tokens/"}),e.jsx(Le.Content,{children:e.jsxs(E,{direction:"column",alignItems:"stretch",gap:6,children:[n?.accessKey&&c&&e.jsx(Ge,{token:n.accessKey,tokenType:_}),e.jsx(Je,{errors:o,onChange:S,canEditInputs:D,isCreating:T,values:L,apiToken:n,onDispatch:f,setHasChangedPermissions:$}),e.jsx(ot,{disabled:!D||L?.type==="read-only"||L?.type==="full-access"})]})})]}))})]})})},Bt=()=>{const s=W(t=>t.admin_app.permissions.settings?.["api-tokens"].read);return e.jsx(M.Protect,{permissions:s,children:e.jsx(Pt,{})})};export{Pt as EditView,Bt as ProtectedEditView};
