@open-commune/core 0.2.15 → 0.2.16
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/dist/dtos.d.mts +1 -1
- package/dist/dtos.d.ts +1 -1
- package/dist/dtos.mjs +1 -1
- package/dist/index.d.mts +338 -93
- package/dist/index.d.ts +338 -93
- package/dist/index.mjs +3 -1
- package/dist/shared/{core.ZROqCA7w.d.mts → core.7Us3D2yq.d.mts} +97 -12
- package/dist/shared/{core.Cot86Med.d.ts → core.C6dz9OyV.d.ts} +97 -12
- package/dist/shared/core.QEqE4rFK.mjs +1 -0
- package/package.json +1 -1
- package/dist/shared/core.aw1RlSUK.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{homedir as Et}from"node:os";import{join as j}from"node:path";import{z as r}from"zod";import{Database as vt}from"bun:sqlite";import{mkdirSync as _t,existsSync as Ot}from"node:fs";import{drizzle as It}from"drizzle-orm/bun-sqlite";import{migrate as bt}from"drizzle-orm/bun-sqlite/migrator";import{v as St,w as d,x as l,y as p,z as w,E as m,r as G,a as Q,t as U,l as pe,u as he,s as me,j as V,b as ye,A as x,q as we,p as fe,B as _,o as ge,m as Ee,n as ve,C as v,D as a,i as _e,f as Oe,g as J,h as Ie,e as be,d as Se,c as Ae}from"./shared/core.aw1RlSUK.mjs";export{F as addressSchema,k as isErrorType}from"./shared/core.aw1RlSUK.mjs";import{sql as R,eq as o,and as b,isNull as C,gt as P,desc as D,notExists as At,or as Z,lt as Ue,isNotNull as Ne,inArray as X,like as De,asc as Me}from"drizzle-orm";import{S3Client as Ut,PutObjectCommand as Te,HeadObjectCommand as Nt,DeleteObjectsCommand as Dt,GetObjectCommand as Mt}from"@aws-sdk/client-s3";import{getSignedUrl as xe}from"@aws-sdk/s3-request-presigner";import{initTRPC as Tt,TRPCError as L}from"@trpc/server";import{randomBytes as ee,createHash as xt}from"node:crypto";import{SignJWT as Rt,jwtVerify as kt}from"jose";import{consola as Re}from"consola";import{nanoid as ke}from"nanoid";import{buildDataSchema as Ce}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS,fieldDefinitionSchema}from"./domains/collections/utils.mjs";import{PUBLICATION_STATUSES as te}from"./domains/collections/constants.mjs";export{FIELD_TYPES}from"./domains/collections/constants.mjs";import"drizzle-zod";import"drizzle-orm/sqlite-core";const k=r.string().min(1),Ct=r.object({COMMUN_DATA_DIR:r.string().default(j(Et(),".commun")),COMMUN_MIGRATIONS_DIR:r.string().optional(),COMMUN_S3_ENDPOINT:k,COMMUN_S3_REGION:r.string().default("fr-par"),COMMUN_S3_BUCKET:k,COMMUN_S3_ACCESS_KEY:k,COMMUN_S3_SECRET_KEY:k,COMMUN_EMAIL_WEBHOOK_URL:k,COMMUN_EMAIL_WEBHOOK_TOKEN:r.string().optional(),COMMUN_ADMIN_URL:r.string().optional(),COMMUN_JWT_SECRET:k});function Be(i=process.env){return Ct.parse({COMMUN_DATA_DIR:i.COMMUN_DATA_DIR,COMMUN_MIGRATIONS_DIR:i.COMMUN_MIGRATIONS_DIR,COMMUN_S3_ENDPOINT:i.COMMUN_S3_ENDPOINT,COMMUN_S3_REGION:i.COMMUN_S3_REGION,COMMUN_S3_BUCKET:i.COMMUN_S3_BUCKET,COMMUN_S3_ACCESS_KEY:i.COMMUN_S3_ACCESS_KEY,COMMUN_S3_SECRET_KEY:i.COMMUN_S3_SECRET_KEY,COMMUN_EMAIL_WEBHOOK_URL:i.COMMUN_EMAIL_WEBHOOK_URL,COMMUN_EMAIL_WEBHOOK_TOKEN:i.COMMUN_EMAIL_WEBHOOK_TOKEN,COMMUN_ADMIN_URL:i.COMMUN_ADMIN_URL,COMMUN_JWT_SECRET:i.COMMUN_JWT_SECRET})}function Bt(){const i=import.meta.dir;return i?j(i,"..","..","..","drizzle"):void 0}function $e(i,e){const t=e??Bt();_t(i,{recursive:!0});const s=new vt(j(i,"commun.db"));s.exec("PRAGMA journal_mode=WAL"),s.exec("PRAGMA foreign_keys=ON"),s.exec("PRAGMA busy_timeout=5000");const n=It({client:s,schema:St});return t&&Ot(j(t,"meta","_journal.json"))&&bt(n,{migrationsFolder:t}),n}class W{constructor(e){this.config=e}static fromEnv(e){return new W({url:e.COMMUN_EMAIL_WEBHOOK_URL,token:e.COMMUN_EMAIL_WEBHOOK_TOKEN})}async sendEvent(e){const t=await fetch(this.config.url,{method:"POST",headers:{"content-type":"application/json",...this.config.token?{authorization:`Bearer ${this.config.token}`}:{}},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`email webhook ${t.status}: ${(await t.text()).slice(0,200)}`)}}class je{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(R`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Pe=168*3600,$t="medias/";class Le{constructor(e){this.config=e,this.client=new Ut({region:e.region,endpoint:e.endpoint,forcePathStyle:!0,credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,s){return xe(this.client,new Te({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:s}),{expiresIn:Pe})}async put(e,t,s){await this.client.send(new Te({Bucket:this.config.bucket,Key:e,Body:t,ContentType:s}))}async head(e){try{return{size:(await this.client.send(new Nt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Dt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith($t)?Promise.resolve(this.publicUrl(e)):xe(this.client,new Mt({Bucket:this.config.bucket,Key:e}),{expiresIn:Pe})}publicUrl(e){const t=this.config.endpoint.replace(/\/+$/,""),s=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${s}`}}function qe(i){return new Le({endpoint:i.COMMUN_S3_ENDPOINT,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const f={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class q extends Error{}function y(i,e){return class extends q{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const ie=(i,e)=>i instanceof Error&&i.message.includes("UNIQUE constraint failed")&&i.message.includes(e),se=Tt.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof q?{type:t.type}:{}}}}}),O=se.router,jt=se.procedure,Ke=se.middleware,Pt=Ke(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof q)throw new L({code:t.trpcCode,message:t.message,cause:t})}return e}),M=jt.use(Pt),ze=i=>Ke(({ctx:e,next:t})=>{if(!e.session)throw new L({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new L({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),u=M.use(ze()),g=M.use(ze("admin")),Lt=O({ping:M.query(({ctx:i})=>i.services.health.check())});class Fe{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(d).where(o(d.email,e)).get()}async findUserById(e){return this.db.select().from(d).where(o(d.id,e)).get()}async listUsers(){return this.db.select().from(d).all()}async hasAnyUser(){return this.db.select({id:d.id}).from(d).limit(1).all().length>0}async deleteUser(e){this.db.delete(d).where(o(d.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(d).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(o(d.id,t.id)).returning().get():this.db.insert(d).values(e).returning().get()}async insertSession(e){return this.db.insert(l).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:l,user:d}).from(l).innerJoin(d,o(d.id,l.userId)).where(b(o(l.id,e),C(l.revokedAt),P(l.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(l).set({revokedAt:t}).where(o(l.id,e)).run()}async findSessionById(e){return this.db.select().from(l).where(o(l.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(l).where(b(o(l.userId,e),C(l.revokedAt),P(l.expiresAt,t))).orderBy(D(l.createdAt)).all()}async updateUser(e,t){return this.db.update(d).set(t).where(o(d.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(p).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(p).where(b(o(p.tokenHash,e),C(p.usedAt),P(p.expiresAt,t))).get()}async listPendingInvitations(e){return this.db.select().from(p).where(b(C(p.usedAt),P(p.expiresAt,e),At(this.db.select({one:R`1`}).from(d).where(o(d.email,p.email))))).orderBy(D(p.createdAt)).all()}async deleteInvitation(e){return!!this.db.delete(p).where(o(p.id,e)).returning().get()}async markInvitationUsed(e,t){this.db.update(p).set({usedAt:t}).where(o(p.id,e)).run()}async insertApiToken(e){return this.db.insert(w).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(w).where(b(o(w.tokenHash,e),C(w.revokedAt))).get()}async touchApiToken(e,t){this.db.update(w).set({lastUsedAt:t}).where(o(w.id,e)).run()}async revokeApiToken(e,t){this.db.update(w).set({revokedAt:t}).where(o(w.id,e)).run()}async listApiTokens(){return this.db.select({id:w.id,name:w.name,lastUsedAt:w.lastUsedAt,revokedAt:w.revokedAt,createdAt:w.createdAt}).from(w).orderBy(D(w.createdAt)).all()}async purgeExpired(e){this.db.delete(l).where(Z(Ue(l.expiresAt,e),Ne(l.revokedAt))).run(),this.db.delete(p).where(Z(Ue(p.expiresAt,e),Ne(p.usedAt))).run()}}const ne=y(m.USER_NOT_FOUND,f.NOT_FOUND),He=y(m.SESSION_NOT_FOUND,f.NOT_FOUND),re=y(m.INVITATION_INVALID,f.BAD_REQUEST),We=y(m.CANNOT_REMOVE_SELF,f.BAD_REQUEST),Ye=y(m.TOO_MANY_ATTEMPTS,f.TOO_MANY_REQUESTS),B=i=>xt("sha256").update(i).digest("hex"),S=()=>new Date().toISOString(),qt=720*3600*1e3,Ge=168*3600*1e3,Kt=Bun.password.hashSync("commun-dummy-password-for-timing"),zt=5*6e4,Ft=10,$=new Map,Qe=i=>{const e=Date.now(),t=($.get(i)??[]).filter(s=>e-s<zt);return t.length?$.set(i,t):$.delete(i),t},Ht=i=>Qe(i).length>=Ft,Wt=i=>{$.set(i,[...Qe(i),Date.now()])},Yt=i=>$.delete(i);class Ve{constructor(e,t={}){this.repository=e,this.options=t}jwtKey(){if(!this.options.jwtSecret)throw new Error("COMMUN_JWT_SECRET manquant \u2014 requis pour signer les sessions (fail-fast au boot)");return new TextEncoder().encode(this.options.jwtSecret)}async sendEmailEvent(e){try{await this.options.email?.sendEvent(e)}catch(t){Re.warn(`[email] \xE9chec d'\xE9mission ${e.eventName} \u2192 ${e.email}: ${String(t)}`)}}hashPassword(e){return Bun.password.hash(e)}verifyPassword(e,t){return Bun.password.verify(e,t)}async login(e,t,s){const n=e.toLowerCase();if(Ht(n))throw new Ye;const c=await this.repository.findUserByEmail(n),E=await this.verifyPassword(t,c?.passwordHash??Kt);return!c?.passwordHash||!E?(Wt(n),null):(Yt(n),this.createSession(c,s))}async createSession(e,t){const s=new Date(Date.now()+qt).toISOString(),n=await this.repository.insertSession({userId:e.id,expiresAt:s,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Rt({session:n.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(s)).sign(this.jwtKey()),session:{sessionId:n.id,user:e,expiresAt:s}}}async verifySession(e){let t;try{const{payload:n}=await kt(e,this.jwtKey());if(typeof n.session!="string")return null;t=n.session}catch{return null}const s=await this.repository.findActiveSessionWithUser(t,S());return s?{sessionId:s.session.id,user:s.user,expiresAt:s.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,S())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,S())).map(s=>({id:s.id,createdAt:s.createdAt,expiresAt:s.expiresAt,ua:s.ua,ip:s.ip,current:s.id===t}))}async revokeOwnSession(e,t){const s=await this.repository.findSessionById(t);if(!s||s.userId!==e)throw new He(`session not found: ${t}`);await this.repository.revokeSession(t,S())}async purgeExpired(){await this.repository.purgeExpired(S())}async createInvitation(e){const t=ee(32).toString("base64url"),s=new Date(Date.now()+Ge).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:B(t),expiresAt:s}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:s}}async listPendingInvitations(){return(await this.repository.listPendingInvitations(S())).map(({id:e,email:t,role:s,expiresAt:n})=>({id:e,email:t,role:s,expiresAt:n}))}async revokeInvitation(e){if(!await this.repository.deleteInvitation(e))throw new re}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const s=ee(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:B(s),expiresAt:new Date(Date.now()+Ge).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${s}`}})}async acceptInvitation(e,t){const s=await this.repository.findValidInvitation(B(e),S());if(!s)throw new re;const n=await this.repository.findUserByEmail(s.email),c=t.name?.trim()||n?.name||s.email.split("@")[0]||"Membre",E=await this.repository.activateUser({email:s.email,name:c,passwordHash:await this.hashPassword(t.password),role:s.role});return await this.repository.markInvitationUsed(s.id,S()),E}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new ne(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new We;await this.repository.deleteUser(t)}async updateUser(e,t){const s=await this.repository.updateUser(e,t);if(!s)throw new ne(`user not found: ${e}`);return s}async createApiToken(e){const t=`commun_${ee(24).toString("base64url")}`,s=await this.repository.insertApiToken({name:e,tokenHash:B(t)});return{token:t,record:s}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(B(e));return t?(await this.repository.touchApiToken(t.id,S()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,S())}async listApiTokens(){return this.repository.listApiTokens()}}const Je=O({login:M.input(pe).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new L({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:U(t.session.user)}}),logout:u.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:u.query(({ctx:i})=>({user:U(i.session.user)})),sessions:O({list:u.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:u.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:M.input(Q).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:U(t)}}),requestPasswordReset:M.input(G).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Ze=O({list:g.query(async({ctx:i})=>(await i.services.users.listUsers()).map(U)),directory:u.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:g.input(r.object({id:r.string()})).query(async({ctx:i,input:e})=>U(await i.services.users.getUser(e.id))),invite:g.input(V).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:g.input(me).mutation(async({ctx:i,input:e})=>U(await i.services.users.updateUser(e.id,e.data))),updateOwnProfile:u.input(he).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.updateUser(i.session.user.id,e);return{user:U(t)}}),remove:g.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),Xe=O({list:g.query(({ctx:i})=>i.services.users.listApiTokens()),create:g.input(ye).mutation(async({ctx:i,input:e})=>{const{token:t,record:s}=await i.services.users.createApiToken(e.name);return{token:t,id:s.id,name:s.name}}),revoke:g.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),et=O({create:g.input(V).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),list:g.query(({ctx:i})=>i.services.users.listPendingInvitations()),revoke:g.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeInvitation(e.id),{revoked:e.id})),accept:M.input(Q).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:U(t)}}),requestPasswordReset:M.input(G).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))});class tt{constructor(e){this.db=e}async get(){return this.db.select().from(x).where(o(x.id,1)).get()}async insert(e){return this.db.insert(x).values({...e,id:1}).returning().get()}async update(e){return this.db.update(x).set(e).where(o(x.id,1)).returning().get()}}const it=y(m.ORGANIZATION_NOT_INITIALIZED,f.NOT_FOUND),st=y(m.ORGANIZATION_ALREADY_INITIALIZED,f.BAD_REQUEST),nt=y(m.DEPLOY_HOOK_MISSING,f.BAD_REQUEST),oe=y(m.DEPLOY_FAILED,f.INTERNAL_SERVER_ERROR),Gt=3e4;class rt{constructor(e,t={}){this.repository=e,this.options=t}async get(){return await this.repository.get()??null}async init(e){if(await this.repository.get())throw new st;return this.repository.insert(e)}async update(e,t){const s=await this.repository.update({...e,updatedBy:t??null});if(!s)throw new it;return s}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new nt;const t=this.options.fetchImpl??fetch;let s;try{s=await t(e,{signal:AbortSignal.timeout(Gt)})}catch(n){throw new oe(`deploy hook unreachable: ${n instanceof Error?n.message:String(n)}`)}if(!s.ok)throw new oe(`deploy hook: ${s.status} ${s.statusText}`);return{status:s.status}}}const ot=O({get:u.query(({ctx:i})=>i.services.organization.get()),init:g.input(fe).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:g.input(we).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:u.mutation(({ctx:i})=>i.services.organization.deploy())});class at{constructor(e){this.db=e}async insert(e){return this.db.insert(_).values(e).returning().get()}async findById(e){return this.db.select().from(_).where(o(_.id,e)).get()}async list(){return this.db.select().from(_).orderBy(D(_.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(_).where(R`json_extract(${_.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(_).set(t).where(o(_.id,e)).returning().get()}async delete(e){this.db.delete(_).where(o(_.id,e)).run()}}const K=y(m.MEDIA_NOT_FOUND,f.NOT_FOUND),ae=y(m.UNSUPPORTED_MIME,f.BAD_REQUEST),ct=y(m.UPLOAD_INCOMPLETE,f.BAD_REQUEST),ce=new Set(["image/jpeg","image/png","image/webp","image/gif","application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet"]),Qt=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],ue=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",ut="medias/";class dt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,s){if(!ce.has(t))throw new ae(`unsupported mime type: ${t}`);const n=`${ut}${ke(10)}/${ue(e)}`;return{key:n,url:await this.storage.presignedPutUrl(n,t,s)}}async finalize(e,t){const s=await this.storage.head(e.key);if(!s)throw new ct(`object not found in storage: ${e.key}`);const n=await this.repository.insert({filename:ue(e.filename),mime:e.mime,size:s.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Re.info(`[media] resize \xE0 impl\xE9menter pour ${n.id} (${Qt.join(", ")})`),n}async uploadDirect(e,t,s,n,c){if(!ce.has(t))throw new ae(`unsupported mime type: ${t}`);const E=`${ut}${ke(10)}/${ue(e)}`;return await this.storage.put(E,s,t),this.finalize({key:E,filename:e,mime:t,metaData:n},c)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new K(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,s){const n=await this.repository.update(e,{...t,updatedBy:s??null});if(!n)throw new K(`media not found: ${e}`);return n}async remove(e){const t=await this.repository.findById(e);if(!t)throw new K(`media not found: ${e}`);const s=t.objects;await this.storage.remove([s.original,...Object.values(s.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async objectUrls(e){const t=e.objects,s={original:await this.storage.url(t.original)};for(const[n,c]of Object.entries(t.variants??{}))s[n]=await this.storage.url(c);return s}}const lt=O({requestUpload:u.input(ve).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:u.input(Ee).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:u.query(({ctx:i})=>i.services.media.listResolved()),get:u.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:u.input(r.object({id:r.string(),data:ge})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:u.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))});class pt{constructor(e){this.db=e}async list(){return this.db.select().from(v).all()}async findBySlug(e){return this.db.select().from(v).where(o(v.slug,e)).get()}async findById(e){return this.db.select().from(v).where(o(v.id,e)).get()}async findByLegacyId(e){return this.db.select().from(v).where(R`json_extract(${v.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(v).values(e).returning().get()}async update(e,t){return this.db.update(v).set(t).where(o(v.id,e)).returning().get()}async delete(e){return this.db.delete(v).where(o(v.id,e)).returning().get()}}class ht{constructor(e){this.db=e}async list(e){return this.db.select().from(a).where(o(a.collectionId,e)).orderBy(D(a.updatedAt)).all()}narrowing(e){const t=[o(a.collectionId,e.collectionId)];return e.status?.length&&t.push(X(a.status,e.status)),e.search?.trim()&&t.push(this.matching(e.search)),b(...t)}matching(e){const t=`%${e.trim()}%`;return Z(De(a.title,t),De(a.data,t))}async search(e){const t=[this.matching(e.search)];return e.collectionIds?.length&&t.push(X(a.collectionId,e.collectionIds)),e.status?.length&&t.push(X(a.status,e.status)),this.db.select().from(a).where(b(...t)).orderBy(D(a.updatedAt)).limit(e.limit).all()}async countMatching(e){const[t]=this.db.select({total:R`count(*)`}).from(a).where(this.narrowing(e)).all();return t?.total??0}async listPaginated(e,t){const s={recent:D(a.updatedAt),oldest:Me(a.updatedAt),title:Me(a.title)};return this.db.select().from(a).where(this.narrowing({...t,collectionId:e})).orderBy(s[t.order??"recent"]).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(a).where(b(o(a.collectionId,e),o(a.status,"published"))).orderBy(D(a.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(a).where(b(o(a.collectionId,e),o(a.slug,t))).get()}async findById(e){return this.db.select().from(a).where(o(a.id,e)).get()}async findByDataField(e,t,s){return this.db.select().from(a).where(b(o(a.collectionId,e),R`json_extract(${a.data}, ${`$.${t}`}) = ${s}`)).get()}async insert(e){return this.db.insert(a).values(e).returning().get()}async update(e,t){return this.db.update(a).set(t).where(o(a.id,e)).returning().get()}async delete(e){return this.db.delete(a).where(o(a.id,e)).returning().get()}}const z=y(m.COLLECTION_NOT_FOUND,f.NOT_FOUND),F=y(m.ENTRY_NOT_FOUND,f.NOT_FOUND),mt=y(m.INVALID_ENTRY_DATA,f.BAD_REQUEST),de=y(m.DUPLICATE_SLUG,f.BAD_REQUEST);function yt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function H(i,e){const t=[];for(const s of i){if(s.type!=="relation")continue;const n=e[s.name];typeof n=="string"&&n?t.push(n):Array.isArray(n)&&t.push(...n.filter(c=>typeof c=="string"))}return[...new Set(t)]}class wt{constructor(e,t,s){this.definitions=e,this.entries=t,this.media=s}async listDefinitions(){return this.definitions.list()}async getDefinition(e){const t=await this.definitions.findBySlug(e)??await this.definitions.findById(e);if(!t)throw new z(`collection not found: ${e}`);return t}async createDefinition(e,t){const s=e.slug||await this.uniqueDefinitionSlug(yt(e.name));try{return await this.definitions.insert({...e,slug:s,createdBy:t??null,updatedBy:t??null})}catch(n){throw this.definitionSlugConflict(n,s)}}async updateDefinition(e,t,s){const n=await this.definitions.update(e,{...t,updatedBy:s??null}).catch(c=>{throw this.definitionSlugConflict(c,t.slug??"")});if(!n)throw new z(`collection not found: ${e}`);return n}async removeDefinition(e){if(!await this.definitions.delete(e))throw new z(`collection not found: ${e}`)}validateData(e,t){const s=Ce(e.fields).safeParse(t);if(!s.success)throw new mt(`invalid data for collection ${e.slug}: ${s.error.message}`);return s.data}async listEntries(e){return this.entries.list((await this.getDefinition(e)).id)}async getEntry(e){const t=await this.entries.findById(e);if(!t)throw new F(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){const s=await this.getDefinition(e);return this.entries.listPaginated(s.id,{skip:t.skip??0,limit:t.limit??20,status:t.status,search:t.search,order:t.order})}async countEntries(e,t={}){const s=await this.getDefinition(e);return this.entries.countMatching({collectionId:s.id,status:t.status,search:t.search})}async searchEntries(e){const t=e.collections?.length?await Promise.all(e.collections.map(n=>this.getDefinition(n))):await this.definitions.list(),s=new Map(t.map(n=>[n.id,n.slug]));return(await this.entries.search({search:e.query,collectionIds:e.collections?.length?[...s.keys()]:void 0,status:e.status,limit:e.limit??20})).map(n=>({...n,collectionSlug:s.get(n.collectionId)??""}))}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,s){const n=await this.getDefinition(e),c=this.validateData(n,t.data),E=await this.uniqueEntrySlug(n.id,t.slug||yt(t.title)),h=await this.entries.insert({...t,slug:E,data:c,collectionId:n.id,createdBy:s??null,updatedBy:s??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(n,h.id,[],H(n.fields,c)),h}async updateEntry(e,t,s){const n=await this.entries.findById(e);if(!n)throw new F(`entry not found: ${e}`);const c=await this.getDefinition(n.collectionId),E=new Set(c.fields.map(I=>I.name)),h=Object.fromEntries(Object.entries(n.data??{}).filter(([I])=>!E.has(I))),A=t.data?{...n.data,...t.data}:n.data,N=Object.fromEntries(Object.entries(A).filter(([I])=>E.has(I)||I in(t.data??{}))),T=t.data?{...h,...this.validateData(c,N)}:void 0,Y={...t,updatedBy:s??null};T&&(Y.data=T),t.status==="published"&&!t.publishedAt&&(Y.publishedAt=new Date().toISOString());try{const I=await this.entries.update(e,Y);return T&&await this.linkRelations(c,e,H(c.fields,n.data),H(c.fields,T)),t.related&&await this.linkRelations(c,e,n.related??[],t.related),I}catch(I){throw this.entrySlugConflict(I,c.slug,t.slug??n.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new F(`entry not found: ${e}`);const s=await this.getDefinition(t.collectionId);await this.linkRelations(s,e,H(s.fields,t.data),[]),await this.entries.delete(e)}definitionSlugConflict(e,t){return ie(e,"collection_definitions.slug")?new de(`le slug "${t}" est d\xE9j\xE0 celui d'une collection`):e}entrySlugConflict(e,t,s){return ie(e,"entries.slug")?new de(`le slug "${s}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let s=t;for(let n=1;await this.entries.findBySlug(e,s);n++)s=`${t}-${n}`;return s}async uniqueDefinitionSlug(e){let t=e;for(let s=1;await this.definitions.findBySlug(t);s++)t=`${e}-${s}`;return t}async linkRelations(e,t,s,n){const c=n.filter(h=>!s.includes(h)),E=s.filter(h=>!n.includes(h));for(const h of c){const A=await this.entries.findById(h);if(!A)continue;const N=new Set(A.related??[]);N.add(t),await this.entries.update(h,{related:[...N]})}for(const h of E){const A=await this.entries.findById(h);A&&await this.entries.update(h,{related:(A.related??[]).filter(N=>N!==t)})}}}const le=r.string().describe("Id or slug of the collection"),ft=r.array(r.enum(te)).optional().describe("Keep only entries in these publication statuses"),gt=O({list:u.query(({ctx:i})=>i.services.collections.listDefinitions()),get:u.input(r.object({idOrSlug:le})).output(Ae).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:g.input(Se).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:g.input(r.object({id:r.string(),data:be})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:g.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:O({get:u.input(r.object({id:r.string().describe("Id of the entry")})).output(J).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),search:u.input(r.object({query:r.string().trim().min(1).max(200).describe("Text to look for"),collections:r.array(le).optional().describe("Search only these collections (ids or slugs); all of them when omitted"),status:ft,limit:r.number().int().min(1).max(50).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(Ie)).query(({ctx:i,input:e})=>i.services.collections.searchEntries(e)),list:u.input(r.object({collectionId:le,status:ft,search:r.string().max(200).optional().describe("Keep only entries whose title or field values contain this text"),order:r.enum(["recent","oldest","title"]).optional().describe("recent (last updated first, the default), oldest, or title"),skip:r.number().int().min(0).optional().describe("Entries to skip, for paging"),limit:r.number().int().min(1).max(100).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(J)).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),count:u.input(r.object({collectionId:r.string(),status:r.array(r.enum(te)).optional(),search:r.string().max(200).optional()})).query(({ctx:i,input:e})=>i.services.collections.countEntries(e.collectionId,e)),create:u.input(r.object({collectionId:r.string(),data:Oe})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:u.input(r.object({id:r.string(),data:_e})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:u.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})});function Vt({env:i}={}){const e=i??Be(),t=$e(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),s=qe(e),n=W.fromEnv(e),c=new Ve(new Fe(t),{email:n,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),E=new at(t),h=new dt(E,s),A=new wt(new pt(t),new ht(t),h),N=new rt(new tt(t)),T={health:new je(t),users:c,organization:N,media:h,collections:A};return{env:e,db:t,storage:s,services:T}}const Jt=O({health:Lt,auth:Je,users:Ze,invitations:et,apiTokens:Xe,organization:ot,media:lt,collections:gt});export{ce as ALLOWED_MIME,We as CannotRemoveSelfError,z as CollectionNotFoundError,wt as CollectionsService,pt as DefinitionRepository,oe as DeployFailedError,nt as DeployHookMissingError,q as DomainError,de as DuplicateSlugError,m as ERROR_TYPES,W as EmailService,F as EntryNotFoundError,ht as EntryRepository,je as HealthService,mt as InvalidEntryDataError,re as InvitationInvalidError,K as MediaNotFoundError,at as MediaRepository,dt as MediaService,st as OrganizationAlreadyInitializedError,it as OrganizationNotInitializedError,tt as OrganizationRepository,rt as OrganizationService,te as PUBLICATION_STATUSES,Le as S3Storage,He as SessionNotFoundError,Ye as TooManyAttemptsError,ae as UnsupportedMimeError,ct as UploadIncompleteError,ne as UserNotFoundError,Fe as UsersRepository,Ve as UsersService,Q as acceptInvitationDto,ye as apiTokenCreateDto,w as apiTokens,Xe as apiTokensRouter,Jt as appRouter,Je as authRouter,Ce as buildDataSchema,v as collectionDefinitions,gt as collectionsRouter,$e as connectDb,Vt as createCore,qe as createStorage,y as createTypedError,Se as definitionCreateDto,Ae as definitionDto,be as definitionUpdateDto,a as entries,Oe as entryCreateDto,J as entryDto,Ie as entrySearchHitDto,_e as entryUpdateDto,p as invitations,et as invitationsRouter,V as inviteDto,ie as isUniqueViolation,pe as loginDto,_ as media,Ee as mediaFinalizeDto,ve as mediaRequestUploadDto,lt as mediaRouter,ge as mediaUpdateDto,x as organization,fe as organizationInitDto,ot as organizationRouter,we as organizationUpdateDto,Be as parseEnv,G as requestPasswordResetDto,l as sessions,U as toPublicUser,he as updateOwnProfileDto,me as userUpdateDto,d as users,Ze as usersRouter};
|
|
1
|
+
import{homedir as bt}from"node:os";import{join as L}from"node:path";import{z as r}from"zod";import{Database as St}from"bun:sqlite";import{mkdirSync as Mt,existsSync as Dt}from"node:fs";import{drizzle as Ct}from"drizzle-orm/bun-sqlite";import{migrate as Rt}from"drizzle-orm/bun-sqlite/migrator";import{y as Tt,z as h,B as p,C as y,D as v,E as w,u as J,a as Z,v as R,o as me,w as ye,x as we,m as X,b as fe,F as k,t as ge,s as Ee,G as A,r as _e,p as ve,q as Oe,H as I,I as a,l as Ie,i as Ue,j as K,k as Ne,h as Ae,f as be,g as Se,e as Me,c as De}from"./shared/core.QEqE4rFK.mjs";export{A as AUDIENCE_PERIODS,J as addressSchema,d as audienceQuerySchema,n as isErrorType}from"./shared/core.QEqE4rFK.mjs";import{sql as m,eq as c,and as b,isNull as $,gt as q,desc as S,notExists as kt,or as ee,lt as Ce,isNotNull as Re,inArray as te,like as Te,asc as ie}from"drizzle-orm";import{S3Client as xt,PutObjectCommand as ke,HeadObjectCommand as $t,DeleteObjectsCommand as Bt,GetObjectCommand as Pt}from"@aws-sdk/client-s3";import{getSignedUrl as xe}from"@aws-sdk/s3-request-presigner";import{initTRPC as jt,TRPCError as z}from"@trpc/server";import{randomBytes as se,createHash as Lt}from"node:crypto";import{SignJWT as Kt,jwtVerify as qt}from"jose";import{consola as $e}from"consola";import{nanoid as Be}from"nanoid";import{buildDataSchema as Pe}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS,fieldDefinitionSchema}from"./domains/collections/utils.mjs";import{PUBLICATION_STATUSES as je}from"./domains/collections/constants.mjs";export{FIELD_TYPES}from"./domains/collections/constants.mjs";import"drizzle-zod";import"drizzle-orm/sqlite-core";const x=r.string().min(1),zt=r.object({COMMUN_DATA_DIR:r.string().default(L(bt(),".commun")),COMMUN_MIGRATIONS_DIR:r.string().optional(),COMMUN_S3_ENDPOINT:x,COMMUN_S3_REGION:r.string().default("fr-par"),COMMUN_S3_BUCKET:x,COMMUN_S3_ACCESS_KEY:x,COMMUN_S3_SECRET_KEY:x,COMMUN_EMAIL_WEBHOOK_URL:x,COMMUN_EMAIL_WEBHOOK_TOKEN:r.string().optional(),COMMUN_ADMIN_URL:r.string().optional(),COMMUN_JWT_SECRET:x,OPEN_COMMUNE_AUDIENCE_URL:r.url().optional(),OPEN_COMMUNE_AUDIENCE_TOKEN:r.string().optional(),OPEN_COMMUNE_AUDIENCE_VIEWERS:r.string().optional()});function Le(i=process.env){return zt.parse({COMMUN_DATA_DIR:i.COMMUN_DATA_DIR,COMMUN_MIGRATIONS_DIR:i.COMMUN_MIGRATIONS_DIR,COMMUN_S3_ENDPOINT:i.COMMUN_S3_ENDPOINT,COMMUN_S3_REGION:i.COMMUN_S3_REGION,COMMUN_S3_BUCKET:i.COMMUN_S3_BUCKET,COMMUN_S3_ACCESS_KEY:i.COMMUN_S3_ACCESS_KEY,COMMUN_S3_SECRET_KEY:i.COMMUN_S3_SECRET_KEY,COMMUN_EMAIL_WEBHOOK_URL:i.COMMUN_EMAIL_WEBHOOK_URL,COMMUN_EMAIL_WEBHOOK_TOKEN:i.COMMUN_EMAIL_WEBHOOK_TOKEN,COMMUN_ADMIN_URL:i.COMMUN_ADMIN_URL,COMMUN_JWT_SECRET:i.COMMUN_JWT_SECRET,OPEN_COMMUNE_AUDIENCE_URL:i.OPEN_COMMUNE_AUDIENCE_URL||void 0,OPEN_COMMUNE_AUDIENCE_TOKEN:i.OPEN_COMMUNE_AUDIENCE_TOKEN||void 0,OPEN_COMMUNE_AUDIENCE_VIEWERS:i.OPEN_COMMUNE_AUDIENCE_VIEWERS||void 0})}function Ft(){const i=import.meta.dir;return i?L(i,"..","..","..","drizzle"):void 0}function Ke(i,e){const t=e??Ft();Mt(i,{recursive:!0});const s=new St(L(i,"commun.db"));s.exec("PRAGMA journal_mode=WAL"),s.exec("PRAGMA foreign_keys=ON"),s.exec("PRAGMA busy_timeout=5000");const n=Ct({client:s,schema:Tt});return t&&Dt(L(t,"meta","_journal.json"))&&Rt(n,{migrationsFolder:t}),n}class Q{constructor(e){this.config=e}static fromEnv(e){return new Q({url:e.COMMUN_EMAIL_WEBHOOK_URL,token:e.COMMUN_EMAIL_WEBHOOK_TOKEN})}async sendEvent(e){const t=await fetch(this.config.url,{method:"POST",headers:{"content-type":"application/json",...this.config.token?{authorization:`Bearer ${this.config.token}`}:{}},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`email webhook ${t.status}: ${(await t.text()).slice(0,200)}`)}}class qe{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(m`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const ze=168*3600,Ht="medias/";class Fe{constructor(e){this.config=e,this.client=new xt({region:e.region,endpoint:e.endpoint,forcePathStyle:!0,credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,s){return xe(this.client,new ke({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:s}),{expiresIn:ze})}async put(e,t,s){await this.client.send(new ke({Bucket:this.config.bucket,Key:e,Body:t,ContentType:s}))}async head(e){try{return{size:(await this.client.send(new $t({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Bt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Ht)?Promise.resolve(this.publicUrl(e)):xe(this.client,new Pt({Bucket:this.config.bucket,Key:e}),{expiresIn:ze})}publicUrl(e){const t=this.config.endpoint.replace(/\/+$/,""),s=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${s}`}}function He(i){return new Fe({endpoint:i.COMMUN_S3_ENDPOINT,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const E={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class F extends Error{}function f(i,e){return class extends F{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const ne=(i,e)=>i instanceof Error&&i.message.includes("UNIQUE constraint failed")&&i.message.includes(e),H=jt.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof F?{type:t.type}:{}}}}}),U=H.router,Yt=H.mergeRouters,Ye=H.procedure,re=H.middleware,Wt=re(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof F)throw new z({code:t.trpcCode,message:t.message,cause:t})}return e}),T=Ye.use(Wt),We=i=>re(({ctx:e,next:t})=>{if(!e.session)throw new z({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new z({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),l=T.use(We()),_=T.use(We("admin")),Gt=U({ping:T.query(({ctx:i})=>i.services.health.check())});class Ge{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(h).where(c(h.email,e)).get()}async findUserById(e){return this.db.select().from(h).where(c(h.id,e)).get()}async listUsers(){return this.db.select().from(h).all()}async hasAnyUser(){return this.db.select({id:h.id}).from(h).limit(1).all().length>0}async deleteUser(e){this.db.delete(h).where(c(h.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(h).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(c(h.id,t.id)).returning().get():this.db.insert(h).values(e).returning().get()}async insertSession(e){return this.db.insert(p).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:p,user:h}).from(p).innerJoin(h,c(h.id,p.userId)).where(b(c(p.id,e),$(p.revokedAt),q(p.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(p).set({revokedAt:t}).where(c(p.id,e)).run()}async findSessionById(e){return this.db.select().from(p).where(c(p.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(p).where(b(c(p.userId,e),$(p.revokedAt),q(p.expiresAt,t))).orderBy(S(p.createdAt)).all()}async updateUser(e,t){return this.db.update(h).set(t).where(c(h.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(y).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(y).where(b(c(y.tokenHash,e),$(y.usedAt),q(y.expiresAt,t))).get()}async listPendingInvitations(e){return this.db.select().from(y).where(b($(y.usedAt),q(y.expiresAt,e),kt(this.db.select({one:m`1`}).from(h).where(c(h.email,y.email))))).orderBy(S(y.createdAt)).all()}async deleteInvitation(e){return!!this.db.delete(y).where(c(y.id,e)).returning().get()}async markInvitationUsed(e,t){this.db.update(y).set({usedAt:t}).where(c(y.id,e)).run()}async insertApiToken(e){return this.db.insert(v).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(v).where(b(c(v.tokenHash,e),$(v.revokedAt))).get()}async touchApiToken(e,t){this.db.update(v).set({lastUsedAt:t}).where(c(v.id,e)).run()}async revokeApiToken(e,t){this.db.update(v).set({revokedAt:t}).where(c(v.id,e)).run()}async listApiTokens(){return this.db.select({id:v.id,name:v.name,lastUsedAt:v.lastUsedAt,revokedAt:v.revokedAt,createdAt:v.createdAt}).from(v).orderBy(S(v.createdAt)).all()}async purgeExpired(e){this.db.delete(p).where(ee(Ce(p.expiresAt,e),Re(p.revokedAt))).run(),this.db.delete(y).where(ee(Ce(y.expiresAt,e),Re(y.usedAt))).run()}}const oe=f(w.USER_NOT_FOUND,E.NOT_FOUND),Ve=f(w.SESSION_NOT_FOUND,E.NOT_FOUND),ae=f(w.INVITATION_INVALID,E.BAD_REQUEST),Qe=f(w.CANNOT_REMOVE_SELF,E.BAD_REQUEST),Je=f(w.TOO_MANY_ATTEMPTS,E.TOO_MANY_REQUESTS),B=i=>Lt("sha256").update(i).digest("hex"),M=()=>new Date().toISOString(),Vt=720*3600*1e3,Ze=168*3600*1e3,Qt=Bun.password.hashSync("commun-dummy-password-for-timing"),Jt=5*6e4,Zt=10,P=new Map,Xe=i=>{const e=Date.now(),t=(P.get(i)??[]).filter(s=>e-s<Jt);return t.length?P.set(i,t):P.delete(i),t},Xt=i=>Xe(i).length>=Zt,ei=i=>{P.set(i,[...Xe(i),Date.now()])},ti=i=>P.delete(i);class et{constructor(e,t={}){this.repository=e,this.options=t}jwtKey(){if(!this.options.jwtSecret)throw new Error("COMMUN_JWT_SECRET manquant \u2014 requis pour signer les sessions (fail-fast au boot)");return new TextEncoder().encode(this.options.jwtSecret)}async sendEmailEvent(e){try{await this.options.email?.sendEvent(e)}catch(t){$e.warn(`[email] \xE9chec d'\xE9mission ${e.eventName} \u2192 ${e.email}: ${String(t)}`)}}hashPassword(e){return Bun.password.hash(e)}verifyPassword(e,t){return Bun.password.verify(e,t)}async login(e,t,s){const n=e.toLowerCase();if(Xt(n))throw new Je;const o=await this.repository.findUserByEmail(n),d=await this.verifyPassword(t,o?.passwordHash??Qt);return!o?.passwordHash||!d?(ei(n),null):(ti(n),this.createSession(o,s))}async createSession(e,t){const s=new Date(Date.now()+Vt).toISOString(),n=await this.repository.insertSession({userId:e.id,expiresAt:s,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Kt({session:n.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(s)).sign(this.jwtKey()),session:{sessionId:n.id,user:e,expiresAt:s}}}async verifySession(e){let t;try{const{payload:n}=await qt(e,this.jwtKey());if(typeof n.session!="string")return null;t=n.session}catch{return null}const s=await this.repository.findActiveSessionWithUser(t,M());return s?{sessionId:s.session.id,user:s.user,expiresAt:s.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,M())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,M())).map(s=>({id:s.id,createdAt:s.createdAt,expiresAt:s.expiresAt,ua:s.ua,ip:s.ip,current:s.id===t}))}async revokeOwnSession(e,t){const s=await this.repository.findSessionById(t);if(!s||s.userId!==e)throw new Ve(`session not found: ${t}`);await this.repository.revokeSession(t,M())}async purgeExpired(){await this.repository.purgeExpired(M())}async createInvitation(e){const t=se(32).toString("base64url"),s=new Date(Date.now()+Ze).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:B(t),expiresAt:s}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:s}}async listPendingInvitations(){return(await this.repository.listPendingInvitations(M())).map(({id:e,email:t,role:s,expiresAt:n})=>({id:e,email:t,role:s,expiresAt:n}))}async revokeInvitation(e){if(!await this.repository.deleteInvitation(e))throw new ae}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const s=se(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:B(s),expiresAt:new Date(Date.now()+Ze).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${s}`}})}async acceptInvitation(e,t){const s=await this.repository.findValidInvitation(B(e),M());if(!s)throw new ae;const n=await this.repository.findUserByEmail(s.email),o=t.name?.trim()||n?.name||s.email.split("@")[0]||"Membre",d=await this.repository.activateUser({email:s.email,name:o,passwordHash:await this.hashPassword(t.password),role:s.role});return await this.repository.markInvitationUsed(s.id,M()),d}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new oe(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new Qe;await this.repository.deleteUser(t)}async updateUser(e,t){const s=await this.repository.updateUser(e,t);if(!s)throw new oe(`user not found: ${e}`);return s}async createApiToken(e){const t=`commun_${se(24).toString("base64url")}`,s=await this.repository.insertApiToken({name:e,tokenHash:B(t)});return{token:t,record:s}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(B(e));return t?(await this.repository.touchApiToken(t.id,M()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,M())}async listApiTokens(){return this.repository.listApiTokens()}}const tt=U({login:T.input(me).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new z({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:R(t.session.user)}}),logout:l.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:l.query(({ctx:i})=>({user:R(i.session.user)})),sessions:U({list:l.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:l.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:T.input(Z).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:R(t)}}),requestPasswordReset:T.input(J).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),it=U({list:_.query(async({ctx:i})=>(await i.services.users.listUsers()).map(R)),directory:l.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:_.input(r.object({id:r.string()})).query(async({ctx:i,input:e})=>R(await i.services.users.getUser(e.id))),invite:_.input(X).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:_.input(we).mutation(async({ctx:i,input:e})=>R(await i.services.users.updateUser(e.id,e.data))),updateOwnProfile:l.input(ye).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.updateUser(i.session.user.id,e);return{user:R(t)}}),remove:_.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),st=U({list:_.query(({ctx:i})=>i.services.users.listApiTokens()),create:_.input(fe).mutation(async({ctx:i,input:e})=>{const{token:t,record:s}=await i.services.users.createApiToken(e.name);return{token:t,id:s.id,name:s.name}}),revoke:_.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),nt=U({create:_.input(X).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),list:_.query(({ctx:i})=>i.services.users.listPendingInvitations()),revoke:_.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeInvitation(e.id),{revoked:e.id})),accept:T.input(Z).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:R(t)}}),requestPasswordReset:T.input(J).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))});class rt{constructor(e){this.db=e}async get(){return this.db.select().from(k).where(c(k.id,1)).get()}async insert(e){return this.db.insert(k).values({...e,id:1}).returning().get()}async update(e){return this.db.update(k).set(e).where(c(k.id,1)).returning().get()}}const ot=f(w.ORGANIZATION_NOT_INITIALIZED,E.NOT_FOUND),at=f(w.ORGANIZATION_ALREADY_INITIALIZED,E.BAD_REQUEST),ct=f(w.DEPLOY_HOOK_MISSING,E.BAD_REQUEST),ce=f(w.DEPLOY_FAILED,E.INTERNAL_SERVER_ERROR),ii=3e4;class lt{constructor(e,t={}){this.repository=e,this.options=t}async get(){return await this.repository.get()??null}async init(e){if(await this.repository.get())throw new at;return this.repository.insert(e)}async update(e,t){const s=await this.repository.update({...e,updatedBy:t??null});if(!s)throw new ot;return s}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new ct;const t=this.options.fetchImpl??fetch;let s;try{s=await t(e,{signal:AbortSignal.timeout(ii)})}catch(n){throw new ce(`deploy hook unreachable: ${n instanceof Error?n.message:String(n)}`)}if(!s.ok)throw new ce(`deploy hook: ${s.status} ${s.statusText}`);return{status:s.status}}}const dt=U({get:l.query(({ctx:i})=>i.services.organization.get()),init:_.input(Ee).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:_.input(ge).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:l.mutation(({ctx:i})=>i.services.organization.deploy())});class ut{constructor(e){this.db=e}async insert(e){return this.db.insert(A).values(e).returning().get()}async findById(e){return this.db.select().from(A).where(c(A.id,e)).get()}async list(){return this.db.select().from(A).orderBy(S(A.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(A).where(m`json_extract(${A.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(A).set(t).where(c(A.id,e)).returning().get()}async delete(e){this.db.delete(A).where(c(A.id,e)).run()}}const Y=f(w.MEDIA_NOT_FOUND,E.NOT_FOUND),le=f(w.UNSUPPORTED_MIME,E.BAD_REQUEST),ht=f(w.UPLOAD_INCOMPLETE,E.BAD_REQUEST),de=new Set(["image/jpeg","image/png","image/webp","image/gif","application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet"]),si=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],ue=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",pt="medias/";class mt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,s){if(!de.has(t))throw new le(`unsupported mime type: ${t}`);const n=`${pt}${Be(10)}/${ue(e)}`;return{key:n,url:await this.storage.presignedPutUrl(n,t,s)}}async finalize(e,t){const s=await this.storage.head(e.key);if(!s)throw new ht(`object not found in storage: ${e.key}`);const n=await this.repository.insert({filename:ue(e.filename),mime:e.mime,size:s.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return $e.info(`[media] resize \xE0 impl\xE9menter pour ${n.id} (${si.join(", ")})`),n}async uploadDirect(e,t,s,n,o){if(!de.has(t))throw new le(`unsupported mime type: ${t}`);const d=`${pt}${Be(10)}/${ue(e)}`;return await this.storage.put(d,s,t),this.finalize({key:d,filename:e,mime:t,metaData:n},o)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,s){const n=await this.repository.update(e,{...t,updatedBy:s??null});if(!n)throw new Y(`media not found: ${e}`);return n}async remove(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);const s=t.objects;await this.storage.remove([s.original,...Object.values(s.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async objectUrls(e){const t=e.objects,s={original:await this.storage.url(t.original)};for(const[n,o]of Object.entries(t.variants??{}))s[n]=await this.storage.url(o);return s}}const yt=U({requestUpload:l.input(Oe).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:l.input(ve).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:l.query(({ctx:i})=>i.services.media.listResolved()),get:l.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:l.input(r.object({id:r.string(),data:_e})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:l.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))});class wt{constructor(e){this.db=e}async list(){return this.db.select().from(I).all()}async findBySlug(e){return this.db.select().from(I).where(c(I.slug,e)).get()}async findById(e){return this.db.select().from(I).where(c(I.id,e)).get()}async findByLegacyId(e){return this.db.select().from(I).where(m`json_extract(${I.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(I).values(e).returning().get()}async update(e,t){return this.db.update(I).set(t).where(c(I.id,e)).returning().get()}async delete(e){return this.db.delete(I).where(c(I.id,e)).returning().get()}}const ni="[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*";class ft{constructor(e){this.db=e}async list(e){return this.db.select().from(a).where(c(a.collectionId,e)).orderBy(S(a.updatedAt)).all()}narrowing(e){const t=[];if(e.collectionId&&t.push(c(a.collectionId,e.collectionId)),e.status?.length&&t.push(te(a.status,e.status)),e.search?.trim()&&t.push(this.matching(e.search)),(e.date?.gte||e.date?.lte)&&t.push(m`exists (select 1 from ${this.spans()} where ${this.within(e.date)})`),e.references?.length){const s=m.join(e.references.map(n=>m`${n}`),m`, `);t.push(m`exists (select 1 from json_tree(${a.data}) where type = 'text' and value in (${s}))`)}return t.length>0?b(...t):void 0}spans(){return m`(select min(value) as span_start, max(value) as span_end from json_tree(${a.data})
|
|
2
|
+
where type = 'text' and value glob ${ni}
|
|
3
|
+
group by case when path = '$' or typeof(key) = 'integer' then id else parent end)`}within(e={}){const t=[];return e.gte&&t.push(m`substr(span_end, 1, ${e.gte.length}) >= ${e.gte}`),e.lte&&t.push(m`substr(span_start, 1, ${e.lte.length}) <= ${e.lte}`),t.length>0?b(...t):m`1`}dateKey(e,t){const s=t?m`max(span_start)`:m`min(span_start)`;return m`(select ${s} from ${this.spans()} where ${this.within(e)})`}matching(e){const t=`%${e.trim()}%`;return ee(Te(a.title,t),Te(a.data,t))}async search(e){const t=[this.matching(e.search)];return e.collectionIds?.length&&t.push(te(a.collectionId,e.collectionIds)),e.status?.length&&t.push(te(a.status,e.status)),this.db.select().from(a).where(b(...t)).orderBy(S(a.updatedAt)).limit(e.limit).all()}async countMatching(e){const[t]=this.db.select({total:m`count(*)`}).from(a).where(this.narrowing(e)).all();return t?.total??0}async listRecent(e){return this.db.select().from(a).orderBy(S(a.updatedAt)).limit(e).all()}async listPaginated(e){const t=e.order??(e.date?"date_asc":"recent"),s=o=>{const d=this.dateKey(e.date,o);return[m`${d} is null`,o?S(d):ie(d)]},n={recent:()=>[S(a.updatedAt)],oldest:()=>[ie(a.updatedAt)],title:()=>[ie(a.title)],date_asc:()=>s(!1),date_desc:()=>s(!0)};return this.db.select().from(a).where(this.narrowing(e)).orderBy(...n[t]()).limit(e.limit).offset(e.skip).all()}async listPublished(e){return this.db.select().from(a).where(b(c(a.collectionId,e),c(a.status,"published"))).orderBy(S(a.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(a).where(b(c(a.collectionId,e),c(a.slug,t))).get()}async findById(e){return this.db.select().from(a).where(c(a.id,e)).get()}async findByDataField(e,t,s){return this.db.select().from(a).where(b(c(a.collectionId,e),m`json_extract(${a.data}, ${`$.${t}`}) = ${s}`)).get()}async insert(e){return this.db.insert(a).values(e).returning().get()}async update(e,t){return this.db.update(a).set(t).where(c(a.id,e)).returning().get()}async delete(e){return this.db.delete(a).where(c(a.id,e)).returning().get()}}const W=f(w.COLLECTION_NOT_FOUND,E.NOT_FOUND),G=f(w.ENTRY_NOT_FOUND,E.NOT_FOUND),gt=f(w.INVALID_ENTRY_DATA,E.BAD_REQUEST),he=f(w.DUPLICATE_SLUG,E.BAD_REQUEST);function Et(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function V(i,e){const t=[];for(const s of i){if(s.type!=="relation")continue;const n=e[s.name];typeof n=="string"&&n?t.push(n):Array.isArray(n)&&t.push(...n.filter(o=>typeof o=="string"))}return[...new Set(t)]}class _t{constructor(e,t,s){this.definitions=e,this.entries=t,this.media=s}async listDefinitions(){return this.definitions.list()}async getDefinition(e){const t=await this.definitions.findBySlug(e)??await this.definitions.findById(e);if(!t)throw new W(`collection not found: ${e}`);return t}async createDefinition(e,t){const s=e.slug||await this.uniqueDefinitionSlug(Et(e.name));try{return await this.definitions.insert({...e,slug:s,createdBy:t??null,updatedBy:t??null})}catch(n){throw this.definitionSlugConflict(n,s)}}async updateDefinition(e,t,s){const n=await this.definitions.update(e,{...t,updatedBy:s??null}).catch(o=>{throw this.definitionSlugConflict(o,t.slug??"")});if(!n)throw new W(`collection not found: ${e}`);return n}async removeDefinition(e){if(!await this.definitions.delete(e))throw new W(`collection not found: ${e}`)}validateData(e,t){const s=Pe(e.fields).safeParse(t);if(!s.success)throw new gt(`invalid data for collection ${e.slug}: ${s.error.message}`);return s.data}async listEntries(e){return this.entries.list((await this.getDefinition(e)).id)}async getEntry(e){const t=await this.entries.findById(e);if(!t)throw new G(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){return this.entries.listPaginated({...t,collectionId:await this.collectionIdOf(e),skip:t.skip??0,limit:t.limit??20})}async collectionIdOf(e){return e?(await this.getDefinition(e)).id:void 0}async listRecentEntries(e=5){return this.entries.listRecent(e)}async countEntries(e,t={}){return this.entries.countMatching({...t,collectionId:await this.collectionIdOf(e)})}async searchEntries(e){const t=e.collections?.length?await Promise.all(e.collections.map(n=>this.getDefinition(n))):await this.definitions.list(),s=new Map(t.map(n=>[n.id,n.slug]));return(await this.entries.search({search:e.query,collectionIds:e.collections?.length?[...s.keys()]:void 0,status:e.status,limit:e.limit??20})).map(n=>({...n,collectionSlug:s.get(n.collectionId)??""}))}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,s){const n=await this.getDefinition(e),o=this.validateData(n,t.data),d=await this.uniqueEntrySlug(n.id,t.slug||Et(t.title)),u=await this.entries.insert({...t,slug:d,data:o,collectionId:n.id,createdBy:s??null,updatedBy:s??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(n,u.id,[],V(n.fields,o)),u}async updateEntry(e,t,s){const n=await this.entries.findById(e);if(!n)throw new G(`entry not found: ${e}`);const o=await this.getDefinition(n.collectionId),d=new Set(o.fields.map(N=>N.name)),u=Object.fromEntries(Object.entries(n.data??{}).filter(([N])=>!d.has(N))),O=t.data?{...n.data,...t.data}:n.data,g=Object.fromEntries(Object.entries(O).filter(([N])=>d.has(N)||N in(t.data??{}))),D=t.data?{...u,...this.validateData(o,g)}:void 0,C={...t,updatedBy:s??null};D&&(C.data=D),t.status==="published"&&!t.publishedAt&&(C.publishedAt=new Date().toISOString());try{const N=await this.entries.update(e,C);return D&&await this.linkRelations(o,e,V(o.fields,n.data),V(o.fields,D)),t.related&&await this.linkRelations(o,e,n.related??[],t.related),N}catch(N){throw this.entrySlugConflict(N,o.slug,t.slug??n.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new G(`entry not found: ${e}`);const s=await this.getDefinition(t.collectionId);await this.linkRelations(s,e,V(s.fields,t.data),[]),await this.entries.delete(e)}definitionSlugConflict(e,t){return ne(e,"collection_definitions.slug")?new he(`le slug "${t}" est d\xE9j\xE0 celui d'une collection`):e}entrySlugConflict(e,t,s){return ne(e,"entries.slug")?new he(`le slug "${s}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let s=t;for(let n=1;await this.entries.findBySlug(e,s);n++)s=`${t}-${n}`;return s}async uniqueDefinitionSlug(e){let t=e;for(let s=1;await this.definitions.findBySlug(t);s++)t=`${e}-${s}`;return t}async linkRelations(e,t,s,n){const o=n.filter(u=>!s.includes(u)),d=s.filter(u=>!n.includes(u));for(const u of o){const O=await this.entries.findById(u);if(!O)continue;const g=new Set(O.related??[]);g.add(t),await this.entries.update(u,{related:[...g]})}for(const u of d){const O=await this.entries.findById(u);O&&await this.entries.update(u,{related:(O.related??[]).filter(g=>g!==t)})}}}const pe=r.string().describe("Id or slug of the collection"),vt=r.array(r.enum(je)).optional().describe("Keep only entries in these publication statuses"),Ot=r.string().regex(/^\d{4}(-(0[1-9]|1[0-2])(-(0[1-9]|[12]\d|3[01]))?)?$/,"An ISO 8601 date: YYYY, YYYY-MM or YYYY-MM-DD"),It={collectionId:pe.optional().describe("Id or slug of the collection; every collection of the site when omitted"),status:vt,search:r.string().max(200).optional().describe("Keep only entries whose title or field values contain this text"),date:r.object({gte:Ot.optional().describe("From this date, included"),lte:Ot.optional().describe("Up to this date, included")}).optional().describe('Keep only entries with a date in this period, read from any of their fields (the sessions of an event). Each bound is an ISO 8601 date at the precision meant, and is compared at that precision: {gte:"2026",lte:"2026"} is the year 2026, {gte:"2026-11",lte:"2026-11"} November 2026, {gte:"<today>"} what is to come, {lte:"<today>"} what is past. An entry is kept when one of its dates, or the span of a session, overlaps the period. Entries with no date are left out'),references:r.array(r.string()).optional().describe("Keep only entries whose fields reference one of these entries, by id (a theme, a place)")},Ut=U({list:l.query(({ctx:i})=>i.services.collections.listDefinitions()),get:l.input(r.object({idOrSlug:pe})).output(Se).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:_.input(be).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:_.input(r.object({id:r.string(),data:Ae})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:_.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:U({get:l.input(r.object({id:r.string().describe("Id of the entry")})).output(K).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),search:l.input(r.object({query:r.string().trim().min(1).max(200).describe("Text to look for"),collections:r.array(pe).optional().describe("Search only these collections (ids or slugs); all of them when omitted"),status:vt,limit:r.number().int().min(1).max(50).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(Ne)).query(({ctx:i,input:e})=>i.services.collections.searchEntries(e)),list:l.input(r.object({...It,order:r.enum(["recent","oldest","title","date_asc","date_desc"]).optional().describe("recent (last updated first, the default), oldest, title, date_asc (the earliest date first, the default with a period) or date_desc (the latest first: the last one held)"),skip:r.number().int().min(0).optional().describe("Entries to skip, for paging"),limit:r.number().int().min(1).max(100).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(K)).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),recent:l.input(r.object({limit:r.number().int().min(1).max(20).optional()}).optional()).output(r.array(K)).query(({ctx:i,input:e})=>i.services.collections.listRecentEntries(e?.limit)),count:l.input(r.object(It)).query(({ctx:i,input:e})=>i.services.collections.countEntries(e.collectionId,e)),create:l.input(r.object({collectionId:r.string(),data:Ue})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:l.input(r.object({id:r.string(),data:Ie})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:l.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})}),j=f(w.AUDIENCE_UNAVAILABLE,E.NOT_FOUND),ri=6e4,oi=10*6e4,ai=2e3;class Nt{constructor(e,t){this.collections=e,this.config=t,this.viewers=(t.viewers??"").split(",").map(s=>s.trim().toLowerCase()).filter(Boolean)}cache=new Map;names;viewers;async summary(e,t){if(!this.config.url)throw new j("no audience source");if(this.viewers.length&&!this.viewers.includes(t.trim().toLowerCase()))throw new j("not among the viewers");const s=`${e.period}:${e.collection??""}:${e.entry??""}`,n=this.cache.get(s);if(n&&Date.now()-n.at<ri)return n.value;const o=e.entry?await this.entrySlug(e.entry):void 0;if(e.entry&&!o)throw new j(`unknown entry ${e.entry}`);const d=await this.ask(this.config.url,new URLSearchParams({period:String(e.period),...e.collection?{collection:e.collection}:{},...o?{entry:o}:{}}));if(!d)throw new j("the source did not answer");const u=await this.knownNames(),O={...d,top:(d.top??[]).map(g=>{const D=g.path.split("/").filter(Boolean),C=u.entries.get(D.at(-1)??""),N=!C&&D.length===1&&g.collection?u.collections.get(g.collection):void 0;return{path:g.path,collection:g.collection??null,visits:g.views,title:g.path==="/"?"Accueil":C?.title??N??g.path,entryId:C?.id??null}})};return this.cache.set(s,{at:Date.now(),value:O}),O}async ask(e,t){const s=this.config.fetchImpl??fetch;try{const n=await s(`${e.replace(/\/$/,"")}/summary?${t}`,{headers:this.config.token?{authorization:`Bearer ${this.config.token}`}:{},signal:AbortSignal.timeout(ai)});if(!n.ok)return null;const o=Me.safeParse(await n.json());return o.success?o.data:null}catch{return null}}async entrySlug(e){try{return(await this.collections.getEntry(e)).slug||void 0}catch{return}}async knownNames(){if(this.names&&Date.now()-this.names.at<oi)return this.names;const e=new Map,t=new Map;for(const s of await this.collections.listDefinitions()){t.set(s.slug,s.name);for(const n of await this.collections.listPublishedEntries(s.id))e.set(n.slug,{id:n.id,title:n.title})}return this.names={at:Date.now(),entries:e,collections:t},this.names}}const At=U({summary:l.input(De).query(({ctx:i,input:e})=>i.services.audience.summary(e,i.session.user.email))});function ci({env:i}={}){const e=i??Le(),t=Ke(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),s=He(e),n=Q.fromEnv(e),o=new et(new Ge(t),{email:n,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),d=new ut(t),u=new mt(d,s),O=new _t(new wt(t),new ft(t),u),g=new lt(new rt(t)),D=new Nt(O,{url:e.OPEN_COMMUNE_AUDIENCE_URL,token:e.OPEN_COMMUNE_AUDIENCE_TOKEN,viewers:e.OPEN_COMMUNE_AUDIENCE_VIEWERS}),C={health:new qe(t),users:o,organization:g,media:u,collections:O,audience:D};return{env:e,db:t,storage:s,services:C}}const li=U({health:Gt,auth:tt,users:it,invitations:nt,apiTokens:st,organization:dt,media:yt,collections:Ut,audience:At});export{de as ALLOWED_MIME,Nt as AudienceService,j as AudienceUnavailableError,Qe as CannotRemoveSelfError,W as CollectionNotFoundError,_t as CollectionsService,wt as DefinitionRepository,ce as DeployFailedError,ct as DeployHookMissingError,F as DomainError,he as DuplicateSlugError,w as ERROR_TYPES,Q as EmailService,G as EntryNotFoundError,ft as EntryRepository,qe as HealthService,gt as InvalidEntryDataError,ae as InvitationInvalidError,Y as MediaNotFoundError,ut as MediaRepository,mt as MediaService,at as OrganizationAlreadyInitializedError,ot as OrganizationNotInitializedError,rt as OrganizationRepository,lt as OrganizationService,je as PUBLICATION_STATUSES,Fe as S3Storage,Ve as SessionNotFoundError,Je as TooManyAttemptsError,le as UnsupportedMimeError,ht as UploadIncompleteError,oe as UserNotFoundError,Ge as UsersRepository,et as UsersService,Z as acceptInvitationDto,_ as adminProcedure,fe as apiTokenCreateDto,v as apiTokens,st as apiTokensRouter,li as appRouter,De as audienceAskDto,At as audienceRouter,Me as audienceSummarySchema,tt as authRouter,Pe as buildDataSchema,I as collectionDefinitions,Ut as collectionsRouter,Ke as connectDb,ci as createCore,He as createStorage,f as createTypedError,be as definitionCreateDto,Se as definitionDto,Ae as definitionUpdateDto,a as entries,Ue as entryCreateDto,K as entryDto,Ne as entrySearchHitDto,Ie as entryUpdateDto,y as invitations,nt as invitationsRouter,X as inviteDto,ne as isUniqueViolation,me as loginDto,A as media,ve as mediaFinalizeDto,Oe as mediaRequestUploadDto,yt as mediaRouter,_e as mediaUpdateDto,Yt as mergeRouters,re as middleware,k as organization,Ee as organizationInitDto,dt as organizationRouter,ge as organizationUpdateDto,Le as parseEnv,T as procedure,l as protectedProcedure,Ye as publicProcedure,J as requestPasswordResetDto,U as router,p as sessions,R as toPublicUser,ye as updateOwnProfileDto,we as userUpdateDto,h as users,it as usersRouter};
|
|
@@ -16,14 +16,14 @@ declare const definitionCreateDto: z.ZodObject<{
|
|
|
16
16
|
type: z.ZodEnum<{
|
|
17
17
|
number: "number";
|
|
18
18
|
boolean: "boolean";
|
|
19
|
-
json: "json";
|
|
20
|
-
date: "date";
|
|
21
19
|
text: "text";
|
|
22
20
|
"rich-text": "rich-text";
|
|
21
|
+
date: "date";
|
|
23
22
|
media: "media";
|
|
24
23
|
relation: "relation";
|
|
25
24
|
select: "select";
|
|
26
25
|
steps: "steps";
|
|
26
|
+
json: "json";
|
|
27
27
|
}>;
|
|
28
28
|
required: z.ZodDefault<z.ZodBoolean>;
|
|
29
29
|
hidden: z.ZodDefault<z.ZodBoolean>;
|
|
@@ -48,14 +48,14 @@ declare const definitionUpdateDto: z.ZodObject<{
|
|
|
48
48
|
type: z.ZodEnum<{
|
|
49
49
|
number: "number";
|
|
50
50
|
boolean: "boolean";
|
|
51
|
-
json: "json";
|
|
52
|
-
date: "date";
|
|
53
51
|
text: "text";
|
|
54
52
|
"rich-text": "rich-text";
|
|
53
|
+
date: "date";
|
|
55
54
|
media: "media";
|
|
56
55
|
relation: "relation";
|
|
57
56
|
select: "select";
|
|
58
57
|
steps: "steps";
|
|
58
|
+
json: "json";
|
|
59
59
|
}>;
|
|
60
60
|
required: z.ZodDefault<z.ZodBoolean>;
|
|
61
61
|
hidden: z.ZodDefault<z.ZodBoolean>;
|
|
@@ -151,7 +151,7 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
|
|
|
151
151
|
data: {
|
|
152
152
|
name: string;
|
|
153
153
|
label: string;
|
|
154
|
-
type: "number" | "boolean" | "
|
|
154
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
155
155
|
required: boolean;
|
|
156
156
|
hidden: boolean;
|
|
157
157
|
options?: string[] | undefined;
|
|
@@ -171,7 +171,7 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
|
|
|
171
171
|
$type: {
|
|
172
172
|
name: string;
|
|
173
173
|
label: string;
|
|
174
|
-
type: "number" | "boolean" | "
|
|
174
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
175
175
|
required: boolean;
|
|
176
176
|
hidden: boolean;
|
|
177
177
|
options?: string[] | undefined;
|
|
@@ -337,14 +337,14 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
|
|
|
337
337
|
type: z.ZodUnion<[z.ZodEnum<{
|
|
338
338
|
number: "number";
|
|
339
339
|
boolean: "boolean";
|
|
340
|
-
json: "json";
|
|
341
|
-
date: "date";
|
|
342
340
|
text: "text";
|
|
343
341
|
"rich-text": "rich-text";
|
|
342
|
+
date: "date";
|
|
344
343
|
media: "media";
|
|
345
344
|
relation: "relation";
|
|
346
345
|
select: "select";
|
|
347
346
|
steps: "steps";
|
|
347
|
+
json: "json";
|
|
348
348
|
}>, z.ZodString]>;
|
|
349
349
|
required: z.ZodDefault<z.ZodBoolean>;
|
|
350
350
|
hidden: z.ZodDefault<z.ZodBoolean>;
|
|
@@ -1945,7 +1945,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
|
|
|
1945
1945
|
data: {
|
|
1946
1946
|
name: string;
|
|
1947
1947
|
label: string;
|
|
1948
|
-
type: "number" | "boolean" | "
|
|
1948
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
1949
1949
|
required: boolean;
|
|
1950
1950
|
hidden: boolean;
|
|
1951
1951
|
options?: string[] | undefined;
|
|
@@ -1965,7 +1965,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
|
|
|
1965
1965
|
$type: {
|
|
1966
1966
|
name: string;
|
|
1967
1967
|
label: string;
|
|
1968
|
-
type: "number" | "boolean" | "
|
|
1968
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
1969
1969
|
required: boolean;
|
|
1970
1970
|
hidden: boolean;
|
|
1971
1971
|
options?: string[] | undefined;
|
|
@@ -2463,6 +2463,90 @@ declare const apiTokenCreateDto: z.ZodObject<{
|
|
|
2463
2463
|
}, z.core.$strip>;
|
|
2464
2464
|
type ApiTokenCreateDto = z.infer<typeof apiTokenCreateDto>;
|
|
2465
2465
|
|
|
2466
|
+
/**
|
|
2467
|
+
* The audience source contract, version 1: what the admin asks an audience
|
|
2468
|
+
* source, and what it expects back. The product ships the panels and this
|
|
2469
|
+
* contract; it ships no source. A source is whatever answers it — the cloud's
|
|
2470
|
+
* measurement service, or a converter in front of Matomo or Plausible.
|
|
2471
|
+
*
|
|
2472
|
+
* The admin calls `GET <OPEN_COMMUNE_AUDIENCE_URL>/summary` with the query
|
|
2473
|
+
* below, and `Authorization: Bearer <OPEN_COMMUNE_AUDIENCE_TOKEN>` when a
|
|
2474
|
+
* token is set. Any answer
|
|
2475
|
+
* other than a 200 that parses hides the panels: nothing a source does can
|
|
2476
|
+
* break the admin.
|
|
2477
|
+
*
|
|
2478
|
+
* Every block but the period, the visits and the daily curve is optional: a
|
|
2479
|
+
* source sends what it measures, and the panel leaves out what is missing.
|
|
2480
|
+
*/
|
|
2481
|
+
declare const AUDIENCE_PERIODS: readonly [7, 30, 90];
|
|
2482
|
+
declare const audienceQuerySchema: z.ZodObject<{
|
|
2483
|
+
period: z.ZodPipe<z.ZodCoercedNumber<unknown>, z.ZodUnion<z.ZodLiteral<7 | 30 | 90>[]>>;
|
|
2484
|
+
collection: z.ZodOptional<z.ZodString>;
|
|
2485
|
+
entry: z.ZodOptional<z.ZodString>;
|
|
2486
|
+
}, z.core.$strip>;
|
|
2487
|
+
declare const audienceSummarySchema: z.ZodObject<{
|
|
2488
|
+
period: z.ZodObject<{
|
|
2489
|
+
from: z.ZodString;
|
|
2490
|
+
to: z.ZodString;
|
|
2491
|
+
days: z.ZodNumber;
|
|
2492
|
+
}, z.core.$strip>;
|
|
2493
|
+
visits: z.ZodNumber;
|
|
2494
|
+
visitsPrevious: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2495
|
+
visitors: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2496
|
+
readingMs: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2497
|
+
viewsPerVisit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2498
|
+
rightNow: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2499
|
+
daily: z.ZodArray<z.ZodObject<{
|
|
2500
|
+
day: z.ZodString;
|
|
2501
|
+
visits: z.ZodNumber;
|
|
2502
|
+
}, z.core.$strip>>;
|
|
2503
|
+
top: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
2504
|
+
path: z.ZodString;
|
|
2505
|
+
collection: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
2506
|
+
views: z.ZodNumber;
|
|
2507
|
+
}, z.core.$strip>>>;
|
|
2508
|
+
sources: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
2509
|
+
name: z.ZodString;
|
|
2510
|
+
share: z.ZodNumber;
|
|
2511
|
+
}, z.core.$strip>>>;
|
|
2512
|
+
devices: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
2513
|
+
name: z.ZodString;
|
|
2514
|
+
share: z.ZodNumber;
|
|
2515
|
+
}, z.core.$strip>>>;
|
|
2516
|
+
campaigns: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
2517
|
+
name: z.ZodString;
|
|
2518
|
+
visits: z.ZodNumber;
|
|
2519
|
+
}, z.core.$strip>>>;
|
|
2520
|
+
depth: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
2521
|
+
reached25: z.ZodNumber;
|
|
2522
|
+
reached50: z.ZodNumber;
|
|
2523
|
+
reachedEnd: z.ZodNumber;
|
|
2524
|
+
}, z.core.$strip>>>;
|
|
2525
|
+
}, z.core.$strip>;
|
|
2526
|
+
type AudienceQuery = z.infer<typeof audienceQuerySchema>;
|
|
2527
|
+
type AudienceSummary = z.infer<typeof audienceSummarySchema>;
|
|
2528
|
+
/** What the admin's own route hands its panels: the source's answer, its pages named. */
|
|
2529
|
+
type AudiencePanelData = Omit<AudienceSummary, 'top'> & {
|
|
2530
|
+
top: {
|
|
2531
|
+
path: string;
|
|
2532
|
+
collection: string | null;
|
|
2533
|
+
visits: number;
|
|
2534
|
+
title: string;
|
|
2535
|
+
entryId: string | null;
|
|
2536
|
+
}[];
|
|
2537
|
+
};
|
|
2538
|
+
/**
|
|
2539
|
+
* What the admin asks its own instance (`audience.summary`): a period, and to
|
|
2540
|
+
* narrow it a collection's slug, then an entry's id. The instance turns the
|
|
2541
|
+
* entry's id into its slug before it asks the source.
|
|
2542
|
+
*/
|
|
2543
|
+
declare const audienceAskDto: z.ZodObject<{
|
|
2544
|
+
period: z.ZodPipe<z.ZodCoercedNumber<unknown>, z.ZodUnion<z.ZodLiteral<7 | 30 | 90>[]>>;
|
|
2545
|
+
collection: z.ZodOptional<z.ZodString>;
|
|
2546
|
+
entry: z.ZodOptional<z.ZodString>;
|
|
2547
|
+
}, z.core.$strip>;
|
|
2548
|
+
type AudienceAsk = z.infer<typeof audienceAskDto>;
|
|
2549
|
+
|
|
2466
2550
|
/**
|
|
2467
2551
|
* Every refusal the core can answer with — the catalogue a consumer codes
|
|
2468
2552
|
* against. A domain error travels as its `type` beside the transport code;
|
|
@@ -2475,6 +2559,7 @@ type ApiTokenCreateDto = z.infer<typeof apiTokenCreateDto>;
|
|
|
2475
2559
|
* words the new one.
|
|
2476
2560
|
*/
|
|
2477
2561
|
declare const ERROR_TYPES: {
|
|
2562
|
+
readonly AUDIENCE_UNAVAILABLE: "audience-unavailable-error";
|
|
2478
2563
|
readonly COLLECTION_NOT_FOUND: "collection-not-found-error";
|
|
2479
2564
|
readonly ENTRY_NOT_FOUND: "entry-not-found-error";
|
|
2480
2565
|
readonly INVALID_ENTRY_DATA: "invalid-entry-data-error";
|
|
@@ -2496,5 +2581,5 @@ type ErrorType = (typeof ERROR_TYPES)[keyof typeof ERROR_TYPES];
|
|
|
2496
2581
|
/** Narrows what a response carried to a type of the catalogue. */
|
|
2497
2582
|
declare const isErrorType: (value: unknown) => value is ErrorType;
|
|
2498
2583
|
|
|
2499
|
-
export {
|
|
2500
|
-
export type { ApiToken as A, CollectionDefinition as C, DefinitionCreateDto as D, Entry as E, Invitation as I, LoginDto as L, Media as M, NewOrganization as N, Organization as O, PublicUser as P, RequestPasswordResetDto as R, Session as S, User as U, OrganizationInitDto as a, OrganizationUpdateDto as b, NewMedia as c, MediaFinalizeDto as d, MediaUpdateDto as e, NewCollectionDefinition as f, NewEntry as g, DefinitionUpdateDto as h, EntrySearchHit as i, EntryCreateDto as j, EntryUpdateDto as k,
|
|
2584
|
+
export { entryDto as $, acceptInvitationDto as F, addressSchema as G, apiTokenCreateDto as H, apiTokens as J, audienceAskDto as K, audienceQuerySchema as Q, audienceSummarySchema as T, collectionDefinitions as V, definitionCreateDto as W, definitionDto as X, definitionUpdateDto as Y, entries as Z, entryCreateDto as _, entrySearchHitDto as a0, entryUpdateDto as a1, invitations as a2, inviteDto as a3, isErrorType as a4, loginDto as a5, media as a6, mediaFinalizeDto as a7, mediaRequestUploadDto as a8, mediaUpdateDto as a9, organization as aa, organizationInitDto as ab, organizationUpdateDto as ac, requestPasswordResetDto as ad, sessions as ae, toPublicUser as af, updateOwnProfileDto as ag, userUpdateDto as ah, users as ai, AUDIENCE_PERIODS as o, schema as s, ERROR_TYPES as v };
|
|
2585
|
+
export type { ApiToken as A, UserUpdateDto as B, CollectionDefinition as C, DefinitionCreateDto as D, Entry as E, Invitation as I, LoginDto as L, Media as M, NewOrganization as N, Organization as O, PublicUser as P, RequestPasswordResetDto as R, Session as S, User as U, OrganizationInitDto as a, OrganizationUpdateDto as b, NewMedia as c, MediaFinalizeDto as d, MediaUpdateDto as e, NewCollectionDefinition as f, NewEntry as g, DefinitionUpdateDto as h, EntrySearchHit as i, EntryCreateDto as j, EntryUpdateDto as k, AudienceAsk as l, AudiencePanelData as m, ErrorType as n, AcceptInvitationDto as p, Address as q, ApiTokenCreateDto as r, AudienceQuery as t, AudienceSummary as u, InviteDto as w, MediaRequestUploadDto as x, NewUser as y, UpdateOwnProfileDto as z };
|
|
@@ -16,14 +16,14 @@ declare const definitionCreateDto: z.ZodObject<{
|
|
|
16
16
|
type: z.ZodEnum<{
|
|
17
17
|
number: "number";
|
|
18
18
|
boolean: "boolean";
|
|
19
|
-
json: "json";
|
|
20
|
-
date: "date";
|
|
21
19
|
text: "text";
|
|
22
20
|
"rich-text": "rich-text";
|
|
21
|
+
date: "date";
|
|
23
22
|
media: "media";
|
|
24
23
|
relation: "relation";
|
|
25
24
|
select: "select";
|
|
26
25
|
steps: "steps";
|
|
26
|
+
json: "json";
|
|
27
27
|
}>;
|
|
28
28
|
required: z.ZodDefault<z.ZodBoolean>;
|
|
29
29
|
hidden: z.ZodDefault<z.ZodBoolean>;
|
|
@@ -48,14 +48,14 @@ declare const definitionUpdateDto: z.ZodObject<{
|
|
|
48
48
|
type: z.ZodEnum<{
|
|
49
49
|
number: "number";
|
|
50
50
|
boolean: "boolean";
|
|
51
|
-
json: "json";
|
|
52
|
-
date: "date";
|
|
53
51
|
text: "text";
|
|
54
52
|
"rich-text": "rich-text";
|
|
53
|
+
date: "date";
|
|
55
54
|
media: "media";
|
|
56
55
|
relation: "relation";
|
|
57
56
|
select: "select";
|
|
58
57
|
steps: "steps";
|
|
58
|
+
json: "json";
|
|
59
59
|
}>;
|
|
60
60
|
required: z.ZodDefault<z.ZodBoolean>;
|
|
61
61
|
hidden: z.ZodDefault<z.ZodBoolean>;
|
|
@@ -151,7 +151,7 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
|
|
|
151
151
|
data: {
|
|
152
152
|
name: string;
|
|
153
153
|
label: string;
|
|
154
|
-
type: "number" | "boolean" | "
|
|
154
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
155
155
|
required: boolean;
|
|
156
156
|
hidden: boolean;
|
|
157
157
|
options?: string[] | undefined;
|
|
@@ -171,7 +171,7 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
|
|
|
171
171
|
$type: {
|
|
172
172
|
name: string;
|
|
173
173
|
label: string;
|
|
174
|
-
type: "number" | "boolean" | "
|
|
174
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
175
175
|
required: boolean;
|
|
176
176
|
hidden: boolean;
|
|
177
177
|
options?: string[] | undefined;
|
|
@@ -337,14 +337,14 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
|
|
|
337
337
|
type: z.ZodUnion<[z.ZodEnum<{
|
|
338
338
|
number: "number";
|
|
339
339
|
boolean: "boolean";
|
|
340
|
-
json: "json";
|
|
341
|
-
date: "date";
|
|
342
340
|
text: "text";
|
|
343
341
|
"rich-text": "rich-text";
|
|
342
|
+
date: "date";
|
|
344
343
|
media: "media";
|
|
345
344
|
relation: "relation";
|
|
346
345
|
select: "select";
|
|
347
346
|
steps: "steps";
|
|
347
|
+
json: "json";
|
|
348
348
|
}>, z.ZodString]>;
|
|
349
349
|
required: z.ZodDefault<z.ZodBoolean>;
|
|
350
350
|
hidden: z.ZodDefault<z.ZodBoolean>;
|
|
@@ -1945,7 +1945,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
|
|
|
1945
1945
|
data: {
|
|
1946
1946
|
name: string;
|
|
1947
1947
|
label: string;
|
|
1948
|
-
type: "number" | "boolean" | "
|
|
1948
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
1949
1949
|
required: boolean;
|
|
1950
1950
|
hidden: boolean;
|
|
1951
1951
|
options?: string[] | undefined;
|
|
@@ -1965,7 +1965,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
|
|
|
1965
1965
|
$type: {
|
|
1966
1966
|
name: string;
|
|
1967
1967
|
label: string;
|
|
1968
|
-
type: "number" | "boolean" | "
|
|
1968
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
1969
1969
|
required: boolean;
|
|
1970
1970
|
hidden: boolean;
|
|
1971
1971
|
options?: string[] | undefined;
|
|
@@ -2463,6 +2463,90 @@ declare const apiTokenCreateDto: z.ZodObject<{
|
|
|
2463
2463
|
}, z.core.$strip>;
|
|
2464
2464
|
type ApiTokenCreateDto = z.infer<typeof apiTokenCreateDto>;
|
|
2465
2465
|
|
|
2466
|
+
/**
|
|
2467
|
+
* The audience source contract, version 1: what the admin asks an audience
|
|
2468
|
+
* source, and what it expects back. The product ships the panels and this
|
|
2469
|
+
* contract; it ships no source. A source is whatever answers it — the cloud's
|
|
2470
|
+
* measurement service, or a converter in front of Matomo or Plausible.
|
|
2471
|
+
*
|
|
2472
|
+
* The admin calls `GET <OPEN_COMMUNE_AUDIENCE_URL>/summary` with the query
|
|
2473
|
+
* below, and `Authorization: Bearer <OPEN_COMMUNE_AUDIENCE_TOKEN>` when a
|
|
2474
|
+
* token is set. Any answer
|
|
2475
|
+
* other than a 200 that parses hides the panels: nothing a source does can
|
|
2476
|
+
* break the admin.
|
|
2477
|
+
*
|
|
2478
|
+
* Every block but the period, the visits and the daily curve is optional: a
|
|
2479
|
+
* source sends what it measures, and the panel leaves out what is missing.
|
|
2480
|
+
*/
|
|
2481
|
+
declare const AUDIENCE_PERIODS: readonly [7, 30, 90];
|
|
2482
|
+
declare const audienceQuerySchema: z.ZodObject<{
|
|
2483
|
+
period: z.ZodPipe<z.ZodCoercedNumber<unknown>, z.ZodUnion<z.ZodLiteral<7 | 30 | 90>[]>>;
|
|
2484
|
+
collection: z.ZodOptional<z.ZodString>;
|
|
2485
|
+
entry: z.ZodOptional<z.ZodString>;
|
|
2486
|
+
}, z.core.$strip>;
|
|
2487
|
+
declare const audienceSummarySchema: z.ZodObject<{
|
|
2488
|
+
period: z.ZodObject<{
|
|
2489
|
+
from: z.ZodString;
|
|
2490
|
+
to: z.ZodString;
|
|
2491
|
+
days: z.ZodNumber;
|
|
2492
|
+
}, z.core.$strip>;
|
|
2493
|
+
visits: z.ZodNumber;
|
|
2494
|
+
visitsPrevious: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2495
|
+
visitors: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2496
|
+
readingMs: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2497
|
+
viewsPerVisit: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2498
|
+
rightNow: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
2499
|
+
daily: z.ZodArray<z.ZodObject<{
|
|
2500
|
+
day: z.ZodString;
|
|
2501
|
+
visits: z.ZodNumber;
|
|
2502
|
+
}, z.core.$strip>>;
|
|
2503
|
+
top: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
2504
|
+
path: z.ZodString;
|
|
2505
|
+
collection: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
2506
|
+
views: z.ZodNumber;
|
|
2507
|
+
}, z.core.$strip>>>;
|
|
2508
|
+
sources: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
2509
|
+
name: z.ZodString;
|
|
2510
|
+
share: z.ZodNumber;
|
|
2511
|
+
}, z.core.$strip>>>;
|
|
2512
|
+
devices: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
2513
|
+
name: z.ZodString;
|
|
2514
|
+
share: z.ZodNumber;
|
|
2515
|
+
}, z.core.$strip>>>;
|
|
2516
|
+
campaigns: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
2517
|
+
name: z.ZodString;
|
|
2518
|
+
visits: z.ZodNumber;
|
|
2519
|
+
}, z.core.$strip>>>;
|
|
2520
|
+
depth: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
2521
|
+
reached25: z.ZodNumber;
|
|
2522
|
+
reached50: z.ZodNumber;
|
|
2523
|
+
reachedEnd: z.ZodNumber;
|
|
2524
|
+
}, z.core.$strip>>>;
|
|
2525
|
+
}, z.core.$strip>;
|
|
2526
|
+
type AudienceQuery = z.infer<typeof audienceQuerySchema>;
|
|
2527
|
+
type AudienceSummary = z.infer<typeof audienceSummarySchema>;
|
|
2528
|
+
/** What the admin's own route hands its panels: the source's answer, its pages named. */
|
|
2529
|
+
type AudiencePanelData = Omit<AudienceSummary, 'top'> & {
|
|
2530
|
+
top: {
|
|
2531
|
+
path: string;
|
|
2532
|
+
collection: string | null;
|
|
2533
|
+
visits: number;
|
|
2534
|
+
title: string;
|
|
2535
|
+
entryId: string | null;
|
|
2536
|
+
}[];
|
|
2537
|
+
};
|
|
2538
|
+
/**
|
|
2539
|
+
* What the admin asks its own instance (`audience.summary`): a period, and to
|
|
2540
|
+
* narrow it a collection's slug, then an entry's id. The instance turns the
|
|
2541
|
+
* entry's id into its slug before it asks the source.
|
|
2542
|
+
*/
|
|
2543
|
+
declare const audienceAskDto: z.ZodObject<{
|
|
2544
|
+
period: z.ZodPipe<z.ZodCoercedNumber<unknown>, z.ZodUnion<z.ZodLiteral<7 | 30 | 90>[]>>;
|
|
2545
|
+
collection: z.ZodOptional<z.ZodString>;
|
|
2546
|
+
entry: z.ZodOptional<z.ZodString>;
|
|
2547
|
+
}, z.core.$strip>;
|
|
2548
|
+
type AudienceAsk = z.infer<typeof audienceAskDto>;
|
|
2549
|
+
|
|
2466
2550
|
/**
|
|
2467
2551
|
* Every refusal the core can answer with — the catalogue a consumer codes
|
|
2468
2552
|
* against. A domain error travels as its `type` beside the transport code;
|
|
@@ -2475,6 +2559,7 @@ type ApiTokenCreateDto = z.infer<typeof apiTokenCreateDto>;
|
|
|
2475
2559
|
* words the new one.
|
|
2476
2560
|
*/
|
|
2477
2561
|
declare const ERROR_TYPES: {
|
|
2562
|
+
readonly AUDIENCE_UNAVAILABLE: "audience-unavailable-error";
|
|
2478
2563
|
readonly COLLECTION_NOT_FOUND: "collection-not-found-error";
|
|
2479
2564
|
readonly ENTRY_NOT_FOUND: "entry-not-found-error";
|
|
2480
2565
|
readonly INVALID_ENTRY_DATA: "invalid-entry-data-error";
|
|
@@ -2496,5 +2581,5 @@ type ErrorType = (typeof ERROR_TYPES)[keyof typeof ERROR_TYPES];
|
|
|
2496
2581
|
/** Narrows what a response carried to a type of the catalogue. */
|
|
2497
2582
|
declare const isErrorType: (value: unknown) => value is ErrorType;
|
|
2498
2583
|
|
|
2499
|
-
export {
|
|
2500
|
-
export type { ApiToken as A, CollectionDefinition as C, DefinitionCreateDto as D, Entry as E, Invitation as I, LoginDto as L, Media as M, NewOrganization as N, Organization as O, PublicUser as P, RequestPasswordResetDto as R, Session as S, User as U, OrganizationInitDto as a, OrganizationUpdateDto as b, NewMedia as c, MediaFinalizeDto as d, MediaUpdateDto as e, NewCollectionDefinition as f, NewEntry as g, DefinitionUpdateDto as h, EntrySearchHit as i, EntryCreateDto as j, EntryUpdateDto as k,
|
|
2584
|
+
export { entryDto as $, acceptInvitationDto as F, addressSchema as G, apiTokenCreateDto as H, apiTokens as J, audienceAskDto as K, audienceQuerySchema as Q, audienceSummarySchema as T, collectionDefinitions as V, definitionCreateDto as W, definitionDto as X, definitionUpdateDto as Y, entries as Z, entryCreateDto as _, entrySearchHitDto as a0, entryUpdateDto as a1, invitations as a2, inviteDto as a3, isErrorType as a4, loginDto as a5, media as a6, mediaFinalizeDto as a7, mediaRequestUploadDto as a8, mediaUpdateDto as a9, organization as aa, organizationInitDto as ab, organizationUpdateDto as ac, requestPasswordResetDto as ad, sessions as ae, toPublicUser as af, updateOwnProfileDto as ag, userUpdateDto as ah, users as ai, AUDIENCE_PERIODS as o, schema as s, ERROR_TYPES as v };
|
|
2585
|
+
export type { ApiToken as A, UserUpdateDto as B, CollectionDefinition as C, DefinitionCreateDto as D, Entry as E, Invitation as I, LoginDto as L, Media as M, NewOrganization as N, Organization as O, PublicUser as P, RequestPasswordResetDto as R, Session as S, User as U, OrganizationInitDto as a, OrganizationUpdateDto as b, NewMedia as c, MediaFinalizeDto as d, MediaUpdateDto as e, NewCollectionDefinition as f, NewEntry as g, DefinitionUpdateDto as h, EntrySearchHit as i, EntryCreateDto as j, EntryUpdateDto as k, AudienceAsk as l, AudiencePanelData as m, ErrorType as n, AcceptInvitationDto as p, Address as q, ApiTokenCreateDto as r, AudienceQuery as t, AudienceSummary as u, InviteDto as w, MediaRequestUploadDto as x, NewUser as y, UpdateOwnProfileDto as z };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createInsertSchema as p,createUpdateSchema as c,createSelectSchema as f}from"drizzle-zod";import{z as e}from"zod";import{fieldDefinitionSchema as y,fieldReadSchema as R}from"../domains/collections/utils.mjs";import{sqliteTable as i,text as t,integer as h,uniqueIndex as C}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as D,FIELD_TYPES as F}from"../domains/collections/constants.mjs";const I={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},z={createdBy:!0,updatedBy:!0},g={...I,...z},r=()=>t("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),a=()=>t("created_at").notNull().$defaultFn(()=>new Date().toISOString()),l=()=>t("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),u=()=>t("legacy_extra",{mode:"json"}).$type(),B=()=>t("status",{enum:D}).notNull().default("draft"),M=()=>t("published_at"),b=e.object({street:e.string().optional(),postalCode:e.string().optional(),city:e.string().optional()}),m=i("organization",{id:h("id").primaryKey().default(1),name:t("name").notNull(),type:t("type",{enum:["commune","intercommunality","syndicate","other"]}).notNull().default("commune"),slug:t("slug").notNull(),description:t("description"),address:t("address",{mode:"json"}).$type(),deployment:t("deployment",{mode:"json"}).$type(),settings:t("settings",{mode:"json"}).$type(),updatedBy:t("updated_by"),legacyExtra:u(),createdAt:a(),updatedAt:l()}),_=i("users",{id:r(),email:t("email").notNull().unique(),name:t("name").notNull(),passwordHash:t("password_hash"),role:t("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),createdAt:a(),updatedAt:l()}),A=i("sessions",{id:r(),userId:t("user_id").notNull().references(()=>_.id,{onDelete:"cascade"}),expiresAt:t("expires_at").notNull(),revokedAt:t("revoked_at"),ua:t("ua"),ip:t("ip"),createdAt:a()}),S=i("invitations",{id:r(),email:t("email").notNull(),tokenHash:t("token_hash").notNull().unique(),role:t("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),expiresAt:t("expires_at").notNull(),usedAt:t("used_at"),createdAt:a()}),E=i("api_tokens",{id:r(),name:t("name").notNull(),tokenHash:t("token_hash").notNull().unique(),lastUsedAt:t("last_used_at"),revokedAt:t("revoked_at"),createdAt:a()}),N=i("media",{id:r(),filename:t("filename").notNull(),mime:t("mime").notNull(),size:h("size").notNull(),alt:t("alt"),caption:t("caption"),objects:t("objects",{mode:"json"}).$type().notNull(),metaData:t("meta_data",{mode:"json"}).$type(),createdBy:t("created_by"),updatedBy:t("updated_by"),legacyExtra:u(),createdAt:a(),updatedAt:l()}),s=i("collection_definitions",{id:r(),name:t("name").notNull(),slug:t("slug").notNull().unique(),description:t("description"),fields:t("fields",{mode:"json"}).$type().notNull(),editor:t("editor",{mode:"json"}).$type(),display:t("display",{mode:"json"}).$type(),headings:t("headings",{mode:"json"}).$type(),createdBy:t("created_by"),updatedBy:t("updated_by"),legacyExtra:u(),createdAt:a(),updatedAt:l()}),d=i("entries",{id:r(),collectionId:t("collection_id").notNull().references(()=>s.id,{onDelete:"cascade"}),title:t("title").notNull(),slug:t("slug").notNull(),data:t("data",{mode:"json"}).$type().notNull(),related:t("related",{mode:"json"}).$type(),createdBy:t("created_by"),updatedBy:t("updated_by"),status:B(),publishedAt:M(),legacyExtra:u(),createdAt:a(),updatedAt:l()},n=>[C("entries_slug_unique").on(n.collectionId,n.slug)]),q={__proto__:null,FIELD_TYPES:F,PUBLICATION_STATUSES:D,addressSchema:b,apiTokens:E,collectionDefinitions:s,entries:d,fieldDefinitionSchema:y,invitations:S,media:N,organization:m,sessions:A,users:_},Y=p(s).omit(g).extend({fields:e.array(y).min(1),slug:e.string().optional()}),V=c(s).omit(g).extend({fields:e.array(y).min(1).optional()}),H=f(s,{fields:e.array(R).describe("The fields every entry of the collection is made of")}),O={...g,related:!0,collectionId:!0},G=p(d).omit(O).extend({slug:e.string().optional()}),Z=c(d).omit(O).extend({related:e.array(e.string()).optional()}),T=f(d,{collectionId:n=>n.describe("Id of the collection the entry belongs to"),slug:n=>n.describe("Route segment of the entry on the published site"),data:e.record(e.string(),e.unknown()).describe("Values of the collection\u2019s fields, keyed by field name"),related:e.array(e.string()).nullable().describe("Ids of the entries that reference this one"),status:n=>n.describe("Publication status; only `published` entries are on the public site")}),K=T.extend({collectionSlug:e.string().describe("Slug of the collection the entry belongs to")}),J=e.object({filename:e.string().min(1),mime:e.string().min(1),metaData:e.record(e.string(),e.string()).optional()}),Q=e.object({key:e.string().min(1),filename:e.string().min(1),mime:e.string().min(1),alt:e.string().optional(),metaData:e.record(e.string(),e.unknown()).optional()}),W=c(N).pick({alt:!0,caption:!0,filename:!0}),j={...I,updatedBy:!0},U={name:n=>n.trim().min(1)},X=p(m,U).omit(j),ee=c(m,U).omit(j),te=e.object({email:e.email(),password:e.string().min(1)}),ne=e.object({token:e.string().min(1),name:e.string().min(1).optional(),password:e.string().min(10)}),oe=e.object({email:e.email()}),ie=e.object({email:e.email(),role:e.enum(["admin","redacteur"])}),ae=e.object({id:e.string(),data:e.object({name:e.string().min(1).optional(),role:e.enum(["admin","redacteur"]).optional(),email:e.email().optional()})}),re=e.strictObject({name:e.string().trim().min(1).max(120)}),se=({id:n,email:x,name:P,role:w})=>({id:n,email:x,name:P,role:w}),le=e.object({name:e.string().min(1)}),v=[7,30,90],L=e.object({period:e.coerce.number().pipe(e.union(v.map(n=>e.literal(n)))),collection:e.string().min(1).optional(),entry:e.string().min(1).optional()}),k=e.object({name:e.string(),share:e.number()}),o=e.number().nonnegative(),de=e.object({period:e.object({from:e.string(),to:e.string(),days:e.number()}),visits:o,visitsPrevious:o.nullish(),visitors:o.nullish(),readingMs:o.nullish(),viewsPerVisit:o.nullish(),rightNow:o.nullish(),daily:e.array(e.object({day:e.string(),visits:o})),top:e.array(e.object({path:e.string(),collection:e.string().nullish(),views:o})).optional(),sources:e.array(k).optional(),devices:e.array(k).optional(),campaigns:e.array(e.object({name:e.string(),visits:o})).optional(),depth:e.object({reached25:o,reached50:o,reachedEnd:o}).nullish()}),ce=e.object({period:L.shape.period,collection:e.string().min(1).optional(),entry:e.string().min(1).optional()}).refine(n=>!n.entry||n.collection,{message:"an entry is asked within its collection",path:["collection"]}),$={AUDIENCE_UNAVAILABLE:"audience-unavailable-error",COLLECTION_NOT_FOUND:"collection-not-found-error",ENTRY_NOT_FOUND:"entry-not-found-error",INVALID_ENTRY_DATA:"invalid-entry-data-error",DUPLICATE_SLUG:"duplicate-slug-error",MEDIA_NOT_FOUND:"media-not-found-error",UNSUPPORTED_MIME:"unsupported-mime-error",UPLOAD_INCOMPLETE:"upload-incomplete-error",ORGANIZATION_NOT_INITIALIZED:"organization-not-initialized-error",ORGANIZATION_ALREADY_INITIALIZED:"organization-already-initialized-error",DEPLOY_HOOK_MISSING:"deploy-hook-missing-error",DEPLOY_FAILED:"deploy-failed-error",USER_NOT_FOUND:"user-not-found-error",SESSION_NOT_FOUND:"session-not-found-error",INVITATION_INVALID:"invitation-invalid-error",CANNOT_REMOVE_SELF:"cannot-remove-self-error",TOO_MANY_ATTEMPTS:"too-many-attempts-error"},ue=new Set(Object.values($)),me=n=>typeof n=="string"&&ue.has(n);export{v as A,A as B,S as C,E as D,$ as E,m as F,N as G,s as H,d as I,b as J,ne as a,le as b,ce as c,L as d,de as e,Y as f,H as g,V as h,G as i,T as j,K as k,Z as l,ie as m,me as n,te as o,Q as p,J as q,W as r,X as s,ee as t,oe as u,se as v,re as w,ae as x,q as y,_ as z};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createInsertSchema as m,createUpdateSchema as l,createSelectSchema as N}from"drizzle-zod";import{z as t}from"zod";import{fieldDefinitionSchema as p,fieldReadSchema as $}from"../domains/collections/utils.mjs";import{sqliteTable as n,text as e,integer as f,uniqueIndex as P}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as D,FIELD_TYPES as v}from"../domains/collections/constants.mjs";const I={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},R={createdBy:!0,updatedBy:!0},y={...I,...R},i=()=>e("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),a=()=>e("created_at").notNull().$defaultFn(()=>new Date().toISOString()),s=()=>e("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),u=()=>e("legacy_extra",{mode:"json"}).$type(),F=()=>e("status",{enum:D}).notNull().default("draft"),z=()=>e("published_at"),A=t.object({street:t.string().optional(),postalCode:t.string().optional(),city:t.string().optional()}),c=n("organization",{id:f("id").primaryKey().default(1),name:e("name").notNull(),type:e("type",{enum:["commune","intercommunality","syndicate","other"]}).notNull().default("commune"),slug:e("slug").notNull(),description:e("description"),address:e("address",{mode:"json"}).$type(),deployment:e("deployment",{mode:"json"}).$type(),settings:e("settings",{mode:"json"}).$type(),updatedBy:e("updated_by"),legacyExtra:u(),createdAt:a(),updatedAt:s()}),g=n("users",{id:i(),email:e("email").notNull().unique(),name:e("name").notNull(),passwordHash:e("password_hash"),role:e("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),createdAt:a(),updatedAt:s()}),T=n("sessions",{id:i(),userId:e("user_id").notNull().references(()=>g.id,{onDelete:"cascade"}),expiresAt:e("expires_at").notNull(),revokedAt:e("revoked_at"),ua:e("ua"),ip:e("ip"),createdAt:a()}),O=n("invitations",{id:i(),email:e("email").notNull(),tokenHash:e("token_hash").notNull().unique(),role:e("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),expiresAt:e("expires_at").notNull(),usedAt:e("used_at"),createdAt:a()}),S=n("api_tokens",{id:i(),name:e("name").notNull(),tokenHash:e("token_hash").notNull().unique(),lastUsedAt:e("last_used_at"),revokedAt:e("revoked_at"),createdAt:a()}),_=n("media",{id:i(),filename:e("filename").notNull(),mime:e("mime").notNull(),size:f("size").notNull(),alt:e("alt"),caption:e("caption"),objects:e("objects",{mode:"json"}).$type().notNull(),metaData:e("meta_data",{mode:"json"}).$type(),createdBy:e("created_by"),updatedBy:e("updated_by"),legacyExtra:u(),createdAt:a(),updatedAt:s()}),r=n("collection_definitions",{id:i(),name:e("name").notNull(),slug:e("slug").notNull().unique(),description:e("description"),fields:e("fields",{mode:"json"}).$type().notNull(),editor:e("editor",{mode:"json"}).$type(),display:e("display",{mode:"json"}).$type(),headings:e("headings",{mode:"json"}).$type(),createdBy:e("created_by"),updatedBy:e("updated_by"),legacyExtra:u(),createdAt:a(),updatedAt:s()}),d=n("entries",{id:i(),collectionId:e("collection_id").notNull().references(()=>r.id,{onDelete:"cascade"}),title:e("title").notNull(),slug:e("slug").notNull(),data:e("data",{mode:"json"}).$type().notNull(),related:e("related",{mode:"json"}).$type(),createdBy:e("created_by"),updatedBy:e("updated_by"),status:F(),publishedAt:z(),legacyExtra:u(),createdAt:a(),updatedAt:s()},o=>[P("entries_slug_unique").on(o.collectionId,o.slug)]),C={__proto__:null,FIELD_TYPES:v,PUBLICATION_STATUSES:D,addressSchema:A,apiTokens:S,collectionDefinitions:r,entries:d,fieldDefinitionSchema:p,invitations:O,media:_,organization:c,sessions:T,users:g},w=m(r).omit(y).extend({fields:t.array(p).min(1),slug:t.string().optional()}),B=l(r).omit(y).extend({fields:t.array(p).min(1).optional()}),M=N(r,{fields:t.array($).describe("The fields every entry of the collection is made of")}),b={...y,related:!0,collectionId:!0},q=m(d).omit(b).extend({slug:t.string().optional()}),Y=l(d).omit(b).extend({related:t.array(t.string()).optional()}),h=N(d,{collectionId:o=>o.describe("Id of the collection the entry belongs to"),slug:o=>o.describe("Route segment of the entry on the published site"),data:t.record(t.string(),t.unknown()).describe("Values of the collection\u2019s fields, keyed by field name"),related:t.array(t.string()).nullable().describe("Ids of the entries that reference this one"),status:o=>o.describe("Publication status; only `published` entries are on the public site")}),H=h.extend({collectionSlug:t.string().describe("Slug of the collection the entry belongs to")}),V=t.object({filename:t.string().min(1),mime:t.string().min(1),metaData:t.record(t.string(),t.string()).optional()}),G=t.object({key:t.string().min(1),filename:t.string().min(1),mime:t.string().min(1),alt:t.string().optional(),metaData:t.record(t.string(),t.unknown()).optional()}),Z=l(_).pick({alt:!0,caption:!0,filename:!0}),E={...I,updatedBy:!0},U={name:o=>o.trim().min(1)},K=m(c,U).omit(E),W=l(c,U).omit(E),J=t.object({email:t.email(),password:t.string().min(1)}),Q=t.object({token:t.string().min(1),name:t.string().min(1).optional(),password:t.string().min(10)}),X=t.object({email:t.email()}),ee=t.object({email:t.email(),role:t.enum(["admin","redacteur"])}),te=t.object({id:t.string(),data:t.object({name:t.string().min(1).optional(),role:t.enum(["admin","redacteur"]).optional(),email:t.email().optional()})}),oe=t.strictObject({name:t.string().trim().min(1).max(120)}),ne=({id:o,email:L,name:k,role:x})=>({id:o,email:L,name:k,role:x}),ae=t.object({name:t.string().min(1)}),j={COLLECTION_NOT_FOUND:"collection-not-found-error",ENTRY_NOT_FOUND:"entry-not-found-error",INVALID_ENTRY_DATA:"invalid-entry-data-error",DUPLICATE_SLUG:"duplicate-slug-error",MEDIA_NOT_FOUND:"media-not-found-error",UNSUPPORTED_MIME:"unsupported-mime-error",UPLOAD_INCOMPLETE:"upload-incomplete-error",ORGANIZATION_NOT_INITIALIZED:"organization-not-initialized-error",ORGANIZATION_ALREADY_INITIALIZED:"organization-already-initialized-error",DEPLOY_HOOK_MISSING:"deploy-hook-missing-error",DEPLOY_FAILED:"deploy-failed-error",USER_NOT_FOUND:"user-not-found-error",SESSION_NOT_FOUND:"session-not-found-error",INVITATION_INVALID:"invitation-invalid-error",CANNOT_REMOVE_SELF:"cannot-remove-self-error",TOO_MANY_ATTEMPTS:"too-many-attempts-error"},ie=new Set(Object.values(j)),re=o=>typeof o=="string"&&ie.has(o);export{c as A,_ as B,r as C,d as D,j as E,A as F,Q as a,ae as b,M as c,w as d,B as e,q as f,h as g,H as h,Y as i,ee as j,re as k,J as l,G as m,V as n,Z as o,K as p,W as q,X as r,te as s,ne as t,oe as u,C as v,g as w,T as x,O as y,S as z};
|