@open-commune/core 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{homedir as bt}from"node:os";import{join as z}from"node:path";import{z as s}from"zod";import{Database as At}from"bun:sqlite";import{mkdirSync as Ut,existsSync as Ot}from"node:fs";import{drizzle as Nt}from"drizzle-orm/bun-sqlite";import{migrate as It}from"drizzle-orm/bun-sqlite/migrator";import{sqliteTable as I,text as o,integer as ue,uniqueIndex as Dt}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as ee,FIELD_TYPES as pe}from"./domains/collections/constants.mjs";import{fieldDefinitionSchema as K,buildDataSchema as me}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS}from"./domains/collections/utils.mjs";import{sql as q,eq as a,and as M,isNull as L,gt as te,desc as R,or as ye,lt as he,isNotNull as ge}from"drizzle-orm";import{S3Client as Mt,PutObjectCommand as we,HeadObjectCommand as kt,DeleteObjectsCommand as Tt,GetObjectCommand as xt}from"@aws-sdk/client-s3";import{getSignedUrl as fe}from"@aws-sdk/s3-request-presigner";import{initTRPC as Rt,TRPCError as H}from"@trpc/server";import{randomBytes as ie,createHash as Ct}from"node:crypto";import{SignJWT as Bt,jwtVerify as $t}from"jose";import{consola as Ee}from"consola";import{createInsertSchema as ne,createUpdateSchema as F}from"drizzle-zod";import{nanoid as _e}from"nanoid";const B=s.string().min(1),jt=s.object({COMMUN_DATA_DIR:s.string().default(z(bt(),".commun")),COMMUN_MIGRATIONS_DIR:s.string().optional(),COMMUN_S3_ENDPOINT:s.string().optional(),COMMUN_S3_REGION:s.string().default("fr-par"),COMMUN_S3_BUCKET:B,COMMUN_S3_ACCESS_KEY:B,COMMUN_S3_SECRET_KEY:B,COMMUN_EMAIL_WEBHOOK_URL:B,COMMUN_EMAIL_WEBHOOK_TOKEN:s.string().optional(),COMMUN_ADMIN_URL:s.string().optional(),COMMUN_JWT_SECRET:B});function ve(i=process.env){return jt.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})}const k=()=>o("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),D=()=>o("created_at").notNull().$defaultFn(()=>new Date().toISOString()),$=()=>o("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),W=()=>o("legacy_extra",{mode:"json"}).$type(),Pt=()=>o("status",{enum:ee}).notNull().default("draft"),zt=()=>o("published_at"),Se=s.object({street:s.string().optional(),postalCode:s.string().optional(),city:s.string().optional()}),U=I("organization",{id:ue("id").primaryKey().default(1),name:o("name").notNull(),type:o("type",{enum:["commune","intercommunality","syndicate","other"]}).notNull().default("commune"),slug:o("slug").notNull(),description:o("description"),address:o("address",{mode:"json"}).$type(),deployment:o("deployment",{mode:"json"}).$type(),settings:o("settings",{mode:"json"}).$type(),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:$()}),u=I("users",{id:k(),email:o("email").notNull().unique(),name:o("name").notNull(),passwordHash:o("password_hash"),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),createdAt:D(),updatedAt:$()}),l=I("sessions",{id:k(),userId:o("user_id").notNull().references(()=>u.id,{onDelete:"cascade"}),expiresAt:o("expires_at").notNull(),revokedAt:o("revoked_at"),ua:o("ua"),ip:o("ip"),createdAt:D()}),v=I("invitations",{id:k(),email:o("email").notNull(),tokenHash:o("token_hash").notNull().unique(),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),expiresAt:o("expires_at").notNull(),usedAt:o("used_at"),createdAt:D()}),y=I("api_tokens",{id:k(),name:o("name").notNull(),tokenHash:o("token_hash").notNull().unique(),lastUsedAt:o("last_used_at"),revokedAt:o("revoked_at"),createdAt:D()}),E=I("media",{id:k(),filename:o("filename").notNull(),mime:o("mime").notNull(),size:ue("size").notNull(),alt:o("alt"),caption:o("caption"),objects:o("objects",{mode:"json"}).$type().notNull(),metaData:o("meta_data",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:$()}),h=I("collection_definitions",{id:k(),name:o("name").notNull(),slug:o("slug").notNull().unique(),description:o("description"),fields:o("fields",{mode:"json"}).$type().notNull(),editor:o("editor",{mode:"json"}).$type(),display:o("display",{mode:"json"}).$type(),headings:o("headings",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:$()}),d=I("entries",{id:k(),collectionId:o("collection_id").notNull().references(()=>h.id,{onDelete:"cascade"}),title:o("title").notNull(),slug:o("slug").notNull(),data:o("data",{mode:"json"}).$type().notNull(),related:o("related",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),status:Pt(),publishedAt:zt(),legacyExtra:W(),createdAt:D(),updatedAt:$()},i=>[Dt("entries_slug_unique").on(i.collectionId,i.slug)]),Kt={__proto__:null,FIELD_TYPES:pe,PUBLICATION_STATUSES:ee,addressSchema:Se,apiTokens:y,collectionDefinitions:h,entries:d,fieldDefinitionSchema:K,invitations:v,media:E,organization:U,sessions:l,users:u};function qt(){const i=import.meta.dir;return i?z(i,"..","..","..","drizzle"):void 0}function be(i,e){const t=e??qt();Ut(i,{recursive:!0});const n=new At(z(i,"commun.db"));n.exec("PRAGMA journal_mode=WAL"),n.exec("PRAGMA foreign_keys=ON"),n.exec("PRAGMA busy_timeout=5000");const r=Nt({client:n,schema:Kt});return t&&Ot(z(t,"meta","_journal.json"))&&It(r,{migrationsFolder:t}),r}class Z{constructor(e){this.config=e}static fromEnv(e){return new Z({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 Ae{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(q`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Ue=168*3600,Lt="medias/";class Oe{constructor(e){this.config=e,this.client=new Mt({region:e.region,...e.endpoint?{endpoint:e.endpoint,forcePathStyle:!0}:{},credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,n){return fe(this.client,new we({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:n}),{expiresIn:Ue})}async put(e,t,n){await this.client.send(new we({Bucket:this.config.bucket,Key:e,Body:t,ContentType:n}))}async head(e){try{return{size:(await this.client.send(new kt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Tt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Lt)?Promise.resolve(this.publicUrl(e)):fe(this.client,new xt({Bucket:this.config.bucket,Key:e}),{expiresIn:Ue})}publicUrl(e){const t=(this.config.endpoint??`https://s3.${this.config.region}.scw.cloud`).replace(/\/+$/,""),n=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${n}`}}function Ne(i){return new Oe({endpoint:i.COMMUN_S3_ENDPOINT||void 0,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const w={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 g(i,e){return class extends Q{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const se=Rt.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof Q?{type:t.type}:{}}}}}),b=se.router,Ht=se.procedure,Ie=se.middleware,Ft=Ie(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof Q)throw new H({code:t.trpcCode,message:t.message,cause:t})}return e}),C=Ht.use(Ft),De=i=>Ie(({ctx:e,next:t})=>{if(!e.session)throw new H({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new H({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),p=C.use(De()),_=C.use(De("admin")),Wt=b({ping:C.query(({ctx:i})=>i.services.health.check())}),Me=s.object({email:s.email(),password:s.string().min(1)}),ke=s.object({token:s.string().min(1),name:s.string().min(1).optional(),password:s.string().min(10)}),Te=s.object({email:s.email()}),xe=s.object({email:s.email(),role:s.enum(["admin","redacteur"])}),Re=s.object({id:s.string(),data:s.object({name:s.string().min(1).optional(),role:s.enum(["admin","redacteur"]).optional(),email:s.email().optional()})}),T=({id:i,email:e,name:t,role:n})=>({id:i,email:e,name:t,role:n}),Ce=s.object({name:s.string().min(1)});class Be{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(u).where(a(u.email,e)).get()}async findUserById(e){return this.db.select().from(u).where(a(u.id,e)).get()}async listUsers(){return this.db.select().from(u).all()}async hasAnyUser(){return this.db.select({id:u.id}).from(u).limit(1).all().length>0}async deleteUser(e){this.db.delete(u).where(a(u.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(u).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(a(u.id,t.id)).returning().get():this.db.insert(u).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:u}).from(l).innerJoin(u,a(u.id,l.userId)).where(M(a(l.id,e),L(l.revokedAt),te(l.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(l).set({revokedAt:t}).where(a(l.id,e)).run()}async findSessionById(e){return this.db.select().from(l).where(a(l.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(l).where(M(a(l.userId,e),L(l.revokedAt),te(l.expiresAt,t))).orderBy(R(l.createdAt)).all()}async updateUser(e,t){return this.db.update(u).set(t).where(a(u.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(v).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(v).where(M(a(v.tokenHash,e),L(v.usedAt),te(v.expiresAt,t))).get()}async markInvitationUsed(e,t){this.db.update(v).set({usedAt:t}).where(a(v.id,e)).run()}async insertApiToken(e){return this.db.insert(y).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(y).where(M(a(y.tokenHash,e),L(y.revokedAt))).get()}async touchApiToken(e,t){this.db.update(y).set({lastUsedAt:t}).where(a(y.id,e)).run()}async revokeApiToken(e,t){this.db.update(y).set({revokedAt:t}).where(a(y.id,e)).run()}async listApiTokens(){return this.db.select({id:y.id,name:y.name,lastUsedAt:y.lastUsedAt,revokedAt:y.revokedAt,createdAt:y.createdAt}).from(y).orderBy(R(y.createdAt)).all()}async purgeExpired(e){this.db.delete(l).where(ye(he(l.expiresAt,e),ge(l.revokedAt))).run(),this.db.delete(v).where(ye(he(v.expiresAt,e),ge(v.usedAt))).run()}}const re=g("user-not-found-error",w.NOT_FOUND),$e=g("session-not-found-error",w.NOT_FOUND),je=g("invitation-invalid-error",w.BAD_REQUEST),Pe=g("cannot-remove-self-error",w.BAD_REQUEST),ze=g("too-many-attempts-error",w.TOO_MANY_REQUESTS),j=i=>Ct("sha256").update(i).digest("hex"),O=()=>new Date().toISOString(),Qt=720*3600*1e3,Ke=168*3600*1e3,Yt=Bun.password.hashSync("commun-dummy-password-for-timing"),Gt=5*6e4,Jt=10,P=new Map,qe=i=>{const e=Date.now(),t=(P.get(i)??[]).filter(n=>e-n<Gt);return t.length?P.set(i,t):P.delete(i),t},Vt=i=>qe(i).length>=Jt,Zt=i=>{P.set(i,[...qe(i),Date.now()])},Xt=i=>P.delete(i);class Le{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){Ee.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,n){const r=e.toLowerCase();if(Vt(r))throw new ze;const c=await this.repository.findUserByEmail(r),f=await this.verifyPassword(t,c?.passwordHash??Yt);return!c?.passwordHash||!f?(Zt(r),null):(Xt(r),this.createSession(c,n))}async createSession(e,t){const n=new Date(Date.now()+Qt).toISOString(),r=await this.repository.insertSession({userId:e.id,expiresAt:n,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Bt({session:r.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(n)).sign(this.jwtKey()),session:{sessionId:r.id,user:e,expiresAt:n}}}async verifySession(e){let t;try{const{payload:r}=await $t(e,this.jwtKey());if(typeof r.session!="string")return null;t=r.session}catch{return null}const n=await this.repository.findActiveSessionWithUser(t,O());return n?{sessionId:n.session.id,user:n.user,expiresAt:n.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,O())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,O())).map(n=>({id:n.id,createdAt:n.createdAt,expiresAt:n.expiresAt,ua:n.ua,ip:n.ip,current:n.id===t}))}async revokeOwnSession(e,t){const n=await this.repository.findSessionById(t);if(!n||n.userId!==e)throw new $e(`session not found: ${t}`);await this.repository.revokeSession(t,O())}async purgeExpired(){await this.repository.purgeExpired(O())}async createInvitation(e){const t=ie(32).toString("base64url"),n=new Date(Date.now()+Ke).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:j(t),expiresAt:n}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:n}}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const n=ie(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:j(n),expiresAt:new Date(Date.now()+Ke).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${n}`}})}async acceptInvitation(e,t){const n=await this.repository.findValidInvitation(j(e),O());if(!n)throw new je;const r=await this.repository.findUserByEmail(n.email),c=t.name?.trim()||r?.name||n.email.split("@")[0]||"Membre",f=await this.repository.activateUser({email:n.email,name:c,passwordHash:await this.hashPassword(t.password),role:n.role});return await this.repository.markInvitationUsed(n.id,O()),f}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new re(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new Pe;await this.repository.deleteUser(t)}async updateUser(e,t){const n=await this.repository.updateUser(e,t);if(!n)throw new re(`user not found: ${e}`);return n}async createApiToken(e){const t=`commun_${ie(24).toString("base64url")}`,n=await this.repository.insertApiToken({name:e,tokenHash:j(t)});return{token:t,record:n}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(j(e));return t?(await this.repository.touchApiToken(t.id,O()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,O())}async listApiTokens(){return this.repository.listApiTokens()}}const He=b({login:C.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 H({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:T(t.session.user)}}),logout:p.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:p.query(({ctx:i})=>({user:T(i.session.user)})),sessions:b({list:p.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:p.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:C.input(ke).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:T(t)}}),requestPasswordReset:C.input(Te).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Fe=b({list:_.query(async({ctx:i})=>(await i.services.users.listUsers()).map(T)),directory:p.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:_.input(s.object({id:s.string()})).query(async({ctx:i,input:e})=>T(await i.services.users.getUser(e.id))),invite:_.input(xe).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:_.input(Re).mutation(async({ctx:i,input:e})=>T(await i.services.users.updateUser(e.id,e.data))),remove:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),We=b({list:_.query(({ctx:i})=>i.services.users.listApiTokens()),create:_.input(Ce).mutation(async({ctx:i,input:e})=>{const{token:t,record:n}=await i.services.users.createApiToken(e.name);return{token:t,id:n.id,name:n.name}}),revoke:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),Qe={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},ei={createdBy:!0,updatedBy:!0},oe={...Qe,...ei},Ye={...Qe,updatedBy:!0},Ge=ne(U).omit(Ye),Je=F(U).omit(Ye);class Ve{constructor(e){this.db=e}async get(){return this.db.select().from(U).where(a(U.id,1)).get()}async insert(e){return this.db.insert(U).values({...e,id:1}).returning().get()}async update(e){return this.db.update(U).set(e).where(a(U.id,1)).returning().get()}}const Ze=g("organization-not-initialized-error",w.NOT_FOUND),Xe=g("organization-already-initialized-error",w.BAD_REQUEST),et=g("deploy-hook-missing-error",w.BAD_REQUEST),ae=g("deploy-failed-error",w.INTERNAL_SERVER_ERROR),ti=3e4;class tt{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 Xe;return this.repository.insert(e)}async update(e,t){const n=await this.repository.update({...e,updatedBy:t??null});if(!n)throw new Ze;return n}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new et;const t=this.options.fetchImpl??fetch;let n;try{n=await t(e,{signal:AbortSignal.timeout(ti)})}catch(r){throw new ae(`deploy hook unreachable: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw new ae(`deploy hook: ${n.status} ${n.statusText}`);return{status:n.status}}}const it=b({get:p.query(({ctx:i})=>i.services.organization.get()),init:_.input(Ge).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:_.input(Je).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:p.mutation(({ctx:i})=>i.services.organization.deploy())}),nt=s.object({filename:s.string().min(1),mime:s.string().min(1),metaData:s.record(s.string(),s.string()).optional()}),st=s.object({key:s.string().min(1),filename:s.string().min(1),mime:s.string().min(1),alt:s.string().optional(),metaData:s.record(s.string(),s.unknown()).optional()}),rt=F(E).pick({alt:!0,caption:!0,filename:!0});class ot{constructor(e){this.db=e}async insert(e){return this.db.insert(E).values(e).returning().get()}async findById(e){return this.db.select().from(E).where(a(E.id,e)).get()}async list(){return this.db.select().from(E).orderBy(R(E.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(E).where(q`json_extract(${E.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(E).set(t).where(a(E.id,e)).returning().get()}async delete(e){this.db.delete(E).where(a(E.id,e)).run()}}const Y=g("media-not-found-error",w.NOT_FOUND),de=g("unsupported-mime-error",w.BAD_REQUEST),at=g("upload-incomplete-error",w.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"]),ii=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],le=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",dt="medias/";class ct{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,n){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const r=`${dt}${_e(10)}/${le(e)}`;return{key:r,url:await this.storage.presignedPutUrl(r,t,n)}}async finalize(e,t){const n=await this.storage.head(e.key);if(!n)throw new at(`object not found in storage: ${e.key}`);const r=await this.repository.insert({filename:le(e.filename),mime:e.mime,size:n.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Ee.info(`[media] resize \xE0 impl\xE9menter pour ${r.id} (${ii.join(", ")})`),r}async uploadDirect(e,t,n,r,c){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const f=`${dt}${_e(10)}/${le(e)}`;return await this.storage.put(f,n,t),this.finalize({key:f,filename:e,mime:t,metaData:r},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 Y(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,n){const r=await this.repository.update(e,{...t,updatedBy:n??null});if(!r)throw new Y(`media not found: ${e}`);return r}async remove(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);const n=t.objects;await this.storage.remove([n.original,...Object.values(n.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,n={original:await this.storage.url(t.original)};for(const[r,c]of Object.entries(t.variants??{}))n[r]=await this.storage.url(c);return n}}const lt=b({requestUpload:p.input(nt).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:p.input(st).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:p.query(({ctx:i})=>i.services.media.listResolved()),get:p.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:p.input(s.object({id:s.string(),data:rt})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:p.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))}),ut=ne(h).omit(oe).extend({fields:s.array(K).min(1),slug:s.string().optional()}),pt=F(h).omit(oe).extend({fields:s.array(K).min(1).optional()}),mt={...oe,related:!0,collectionId:!0},yt=ne(d).omit(mt).extend({slug:s.string().optional()}),ht=F(d).omit(mt).extend({related:s.array(s.string()).optional()});class gt{constructor(e){this.db=e}async list(){return this.db.select().from(h).all()}async findBySlug(e){return this.db.select().from(h).where(a(h.slug,e)).get()}async findById(e){return this.db.select().from(h).where(a(h.id,e)).get()}async findByLegacyId(e){return this.db.select().from(h).where(q`json_extract(${h.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(h).values(e).returning().get()}async update(e,t){return this.db.update(h).set(t).where(a(h.id,e)).returning().get()}async delete(e){return this.db.delete(h).where(a(h.id,e)).returning().get()}}class wt{constructor(e){this.db=e}async list(e){return this.db.select().from(d).where(a(d.collectionId,e)).orderBy(R(d.updatedAt)).all()}async listPaginated(e,t){return this.db.select().from(d).where(a(d.collectionId,e)).orderBy(R(d.updatedAt)).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(d).where(M(a(d.collectionId,e),a(d.status,"published"))).orderBy(R(d.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(d).where(M(a(d.collectionId,e),a(d.slug,t))).get()}async findById(e){return this.db.select().from(d).where(a(d.id,e)).get()}async findByDataField(e,t,n){return this.db.select().from(d).where(M(a(d.collectionId,e),q`json_extract(${d.data}, ${`$.${t}`}) = ${n}`)).get()}async insert(e){return this.db.insert(d).values(e).returning().get()}async update(e,t){return this.db.update(d).set(t).where(a(d.id,e)).returning().get()}async delete(e){return this.db.delete(d).where(a(d.id,e)).returning().get()}}const G=g("collection-not-found-error",w.NOT_FOUND),J=g("entry-not-found-error",w.NOT_FOUND),ft=g("invalid-entry-data-error",w.BAD_REQUEST),Et=g("duplicate-slug-error",w.BAD_REQUEST);function _t(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 n of i){if(n.type!=="relation")continue;const r=e[n.name];typeof r=="string"&&r?t.push(r):Array.isArray(r)&&t.push(...r.filter(c=>typeof c=="string"))}return[...new Set(t)]}class vt{constructor(e,t,n){this.definitions=e,this.entries=t,this.media=n}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 G(`collection not found: ${e}`);return t}async createDefinition(e,t){return this.definitions.insert({...e,slug:e.slug||await this.uniqueDefinitionSlug(_t(e.name)),createdBy:t??null,updatedBy:t??null})}async updateDefinition(e,t,n){const r=await this.definitions.update(e,{...t,updatedBy:n??null});if(!r)throw new G(`collection not found: ${e}`);return r}async removeDefinition(e){if(!await this.definitions.delete(e))throw new G(`collection not found: ${e}`)}validateData(e,t){const n=me(e.fields).safeParse(t);if(!n.success)throw new ft(`invalid data for collection ${e.slug}: ${n.error.message}`);return n.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 J(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){const n=await this.getDefinition(e);return this.entries.listPaginated(n.id,{skip:t.skip??0,limit:t.limit??20})}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,n){const r=await this.getDefinition(e),c=this.validateData(r,t.data),f=await this.uniqueEntrySlug(r.id,t.slug||_t(t.title)),m=await this.entries.insert({...t,slug:f,data:c,collectionId:r.id,createdBy:n??null,updatedBy:n??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(r,m.id,[],V(r.fields,c)),m}async updateEntry(e,t,n){const r=await this.entries.findById(e);if(!r)throw new J(`entry not found: ${e}`);const c=await this.getDefinition(r.collectionId),f=new Set(c.fields.map(S=>S.name)),m=Object.fromEntries(Object.entries(r.data??{}).filter(([S])=>!f.has(S))),A=t.data?{...r.data,...t.data}:r.data,N=Object.fromEntries(Object.entries(A).filter(([S])=>f.has(S)||S in(t.data??{}))),x=t.data?{...m,...this.validateData(c,N)}:void 0,X={...t,updatedBy:n??null};x&&(X.data=x),t.status==="published"&&!t.publishedAt&&(X.publishedAt=new Date().toISOString());try{const S=await this.entries.update(e,X);return x&&await this.linkRelations(c,e,V(c.fields,r.data),V(c.fields,x)),t.related&&await this.linkRelations(c,e,r.related??[],t.related),S}catch(S){throw this.mapSlugConflict(S,c.slug,t.slug??r.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new J(`entry not found: ${e}`);const n=await this.getDefinition(t.collectionId);await this.linkRelations(n,e,V(n.fields,t.data),[]),await this.entries.delete(e)}mapSlugConflict(e,t,n){return e instanceof Error&&e.message.includes("UNIQUE constraint failed")&&e.message.includes("entries.slug")?new Et(`le slug "${n}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let n=t;for(let r=1;await this.entries.findBySlug(e,n);r++)n=`${t}-${r}`;return n}async uniqueDefinitionSlug(e){let t=e;for(let n=1;await this.definitions.findBySlug(t);n++)t=`${e}-${n}`;return t}async linkRelations(e,t,n,r){const c=r.filter(m=>!n.includes(m)),f=n.filter(m=>!r.includes(m));for(const m of c){const A=await this.entries.findById(m);if(!A)continue;const N=new Set(A.related??[]);N.add(t),await this.entries.update(m,{related:[...N]})}for(const m of f){const A=await this.entries.findById(m);A&&await this.entries.update(m,{related:(A.related??[]).filter(N=>N!==t)})}}}const St=b({list:p.query(({ctx:i})=>i.services.collections.listDefinitions()),get:p.input(s.object({idOrSlug:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:_.input(ut).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:_.input(s.object({id:s.string(),data:pt})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:b({get:p.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),list:p.input(s.object({collectionId:s.string(),skip:s.number().int().min(0).optional(),limit:s.number().int().min(1).max(100).optional()})).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),create:p.input(s.object({collectionId:s.string(),data:yt})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:p.input(s.object({id:s.string(),data:ht})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:p.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})});function ni({env:i}={}){const e=i??ve(),t=be(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),n=Ne(e),r=Z.fromEnv(e),c=new Le(new Be(t),{email:r,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),f=new ot(t),m=new ct(f,n),A=new vt(new gt(t),new wt(t),m),N=new tt(new Ve(t)),x={health:new Ae(t),users:c,organization:N,media:m,collections:A};return{env:e,db:t,storage:n,services:x}}const si=b({health:Wt,auth:He,users:Fe,apiTokens:We,organization:it,media:lt,collections:St});export{ce as ALLOWED_MIME,Pe as CannotRemoveSelfError,G as CollectionNotFoundError,vt as CollectionsService,gt as DefinitionRepository,ae as DeployFailedError,et as DeployHookMissingError,Q as DomainError,Et as DuplicateSlugError,Z as EmailService,J as EntryNotFoundError,wt as EntryRepository,pe as FIELD_TYPES,Ae as HealthService,ft as InvalidEntryDataError,je as InvitationInvalidError,Y as MediaNotFoundError,ot as MediaRepository,ct as MediaService,Xe as OrganizationAlreadyInitializedError,Ze as OrganizationNotInitializedError,Ve as OrganizationRepository,tt as OrganizationService,ee as PUBLICATION_STATUSES,Oe as S3Storage,$e as SessionNotFoundError,ze as TooManyAttemptsError,de as UnsupportedMimeError,at as UploadIncompleteError,re as UserNotFoundError,Be as UsersRepository,Le as UsersService,ke as acceptInvitationDto,Se as addressSchema,Ce as apiTokenCreateDto,y as apiTokens,We as apiTokensRouter,si as appRouter,He as authRouter,me as buildDataSchema,h as collectionDefinitions,St as collectionsRouter,be as connectDb,ni as createCore,Ne as createStorage,g as createTypedError,ut as definitionCreateDto,pt as definitionUpdateDto,d as entries,yt as entryCreateDto,ht as entryUpdateDto,K as fieldDefinitionSchema,v as invitations,xe as inviteDto,Me as loginDto,E as media,st as mediaFinalizeDto,nt as mediaRequestUploadDto,lt as mediaRouter,rt as mediaUpdateDto,U as organization,Ge as organizationInitDto,it as organizationRouter,Je as organizationUpdateDto,ve as parseEnv,Te as requestPasswordResetDto,l as sessions,T as toPublicUser,Re as userUpdateDto,u as users,Fe as usersRouter};
1
+ import{homedir as Rt}from"node:os";import{join as K}from"node:path";import{z as s}from"zod";import{Database as Ct}from"bun:sqlite";import{mkdirSync as $t,existsSync as Bt}from"node:fs";import{drizzle as jt}from"drizzle-orm/bun-sqlite";import{migrate as Pt}from"drizzle-orm/bun-sqlite/migrator";import{sqliteTable as D,text as o,integer as ye,uniqueIndex as qt}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as $,FIELD_TYPES as fe}from"./domains/collections/constants.mjs";import{fieldDefinitionSchema as L,fieldReadSchema as zt,buildDataSchema as ge}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS}from"./domains/collections/utils.mjs";import{sql as B,eq as c,and as U,isNull as H,gt as ie,desc as M,or as ne,lt as we,isNotNull as be,inArray as se,like as Ee,asc as _e}from"drizzle-orm";import{S3Client as Kt,PutObjectCommand as ve,HeadObjectCommand as Lt,DeleteObjectsCommand as Ht,GetObjectCommand as Ft}from"@aws-sdk/client-s3";import{getSignedUrl as Se}from"@aws-sdk/s3-request-presigner";import{initTRPC as Wt,TRPCError as F}from"@trpc/server";import{randomBytes as re,createHash as Qt}from"node:crypto";import{SignJWT as Yt,jwtVerify as Gt}from"jose";import{consola as Ae}from"consola";import{createInsertSchema as oe,createUpdateSchema as W,createSelectSchema as Ue}from"drizzle-zod";import{nanoid as Oe}from"nanoid";const j=s.string().min(1),Jt=s.object({COMMUN_DATA_DIR:s.string().default(K(Rt(),".commun")),COMMUN_MIGRATIONS_DIR:s.string().optional(),COMMUN_S3_ENDPOINT:s.string().optional(),COMMUN_S3_REGION:s.string().default("fr-par"),COMMUN_S3_BUCKET:j,COMMUN_S3_ACCESS_KEY:j,COMMUN_S3_SECRET_KEY:j,COMMUN_EMAIL_WEBHOOK_URL:j,COMMUN_EMAIL_WEBHOOK_TOKEN:s.string().optional(),COMMUN_ADMIN_URL:s.string().optional(),COMMUN_JWT_SECRET:j});function Ie(i=process.env){return Jt.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})}const x=()=>o("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),k=()=>o("created_at").notNull().$defaultFn(()=>new Date().toISOString()),P=()=>o("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),Q=()=>o("legacy_extra",{mode:"json"}).$type(),Vt=()=>o("status",{enum:$}).notNull().default("draft"),Zt=()=>o("published_at"),Ne=s.object({street:s.string().optional(),postalCode:s.string().optional(),city:s.string().optional()}),O=D("organization",{id:ye("id").primaryKey().default(1),name:o("name").notNull(),type:o("type",{enum:["commune","intercommunality","syndicate","other"]}).notNull().default("commune"),slug:o("slug").notNull(),description:o("description"),address:o("address",{mode:"json"}).$type(),deployment:o("deployment",{mode:"json"}).$type(),settings:o("settings",{mode:"json"}).$type(),updatedBy:o("updated_by"),legacyExtra:Q(),createdAt:k(),updatedAt:P()}),h=D("users",{id:x(),email:o("email").notNull().unique(),name:o("name").notNull(),passwordHash:o("password_hash"),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),createdAt:k(),updatedAt:P()}),m=D("sessions",{id:x(),userId:o("user_id").notNull().references(()=>h.id,{onDelete:"cascade"}),expiresAt:o("expires_at").notNull(),revokedAt:o("revoked_at"),ua:o("ua"),ip:o("ip"),createdAt:k()}),_=D("invitations",{id:x(),email:o("email").notNull(),tokenHash:o("token_hash").notNull().unique(),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),expiresAt:o("expires_at").notNull(),usedAt:o("used_at"),createdAt:k()}),g=D("api_tokens",{id:x(),name:o("name").notNull(),tokenHash:o("token_hash").notNull().unique(),lastUsedAt:o("last_used_at"),revokedAt:o("revoked_at"),createdAt:k()}),b=D("media",{id:x(),filename:o("filename").notNull(),mime:o("mime").notNull(),size:ye("size").notNull(),alt:o("alt"),caption:o("caption"),objects:o("objects",{mode:"json"}).$type().notNull(),metaData:o("meta_data",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:Q(),createdAt:k(),updatedAt:P()}),y=D("collection_definitions",{id:x(),name:o("name").notNull(),slug:o("slug").notNull().unique(),description:o("description"),fields:o("fields",{mode:"json"}).$type().notNull(),editor:o("editor",{mode:"json"}).$type(),display:o("display",{mode:"json"}).$type(),headings:o("headings",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:Q(),createdAt:k(),updatedAt:P()}),a=D("entries",{id:x(),collectionId:o("collection_id").notNull().references(()=>y.id,{onDelete:"cascade"}),title:o("title").notNull(),slug:o("slug").notNull(),data:o("data",{mode:"json"}).$type().notNull(),related:o("related",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),status:Vt(),publishedAt:Zt(),legacyExtra:Q(),createdAt:k(),updatedAt:P()},i=>[qt("entries_slug_unique").on(i.collectionId,i.slug)]),Xt={__proto__:null,FIELD_TYPES:fe,PUBLICATION_STATUSES:$,addressSchema:Ne,apiTokens:g,collectionDefinitions:y,entries:a,fieldDefinitionSchema:L,invitations:_,media:b,organization:O,sessions:m,users:h};function ei(){const i=import.meta.dir;return i?K(i,"..","..","..","drizzle"):void 0}function De(i,e){const t=e??ei();$t(i,{recursive:!0});const n=new Ct(K(i,"commun.db"));n.exec("PRAGMA journal_mode=WAL"),n.exec("PRAGMA foreign_keys=ON"),n.exec("PRAGMA busy_timeout=5000");const r=jt({client:n,schema:Xt});return t&&Bt(K(t,"meta","_journal.json"))&&Pt(r,{migrationsFolder:t}),r}class ee{constructor(e){this.config=e}static fromEnv(e){return new ee({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 ke{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(B`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Me=168*3600,ti="medias/";class xe{constructor(e){this.config=e,this.client=new Kt({region:e.region,...e.endpoint?{endpoint:e.endpoint,forcePathStyle:!0}:{},credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,n){return Se(this.client,new ve({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:n}),{expiresIn:Me})}async put(e,t,n){await this.client.send(new ve({Bucket:this.config.bucket,Key:e,Body:t,ContentType:n}))}async head(e){try{return{size:(await this.client.send(new Lt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Ht({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(ti)?Promise.resolve(this.publicUrl(e)):Se(this.client,new Ft({Bucket:this.config.bucket,Key:e}),{expiresIn:Me})}publicUrl(e){const t=(this.config.endpoint??`https://s3.${this.config.region}.scw.cloud`).replace(/\/+$/,""),n=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${n}`}}function Te(i){return new xe({endpoint:i.COMMUN_S3_ENDPOINT||void 0,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const w={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class Y extends Error{}function f(i,e){return class extends Y{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const ae=Wt.context().meta().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof Y?{type:t.type}:{}}}}}),S=ae.router,ii=ae.procedure,Re=ae.middleware,ni=Re(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof Y)throw new F({code:t.trpcCode,message:t.message,cause:t})}return e}),C=ii.use(ni),Ce=i=>Re(({ctx:e,next:t})=>{if(!e.session)throw new F({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new F({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),u=C.use(Ce()),E=C.use(Ce("admin")),si=S({ping:C.query(({ctx:i})=>i.services.health.check())}),$e=s.object({email:s.email(),password:s.string().min(1)}),Be=s.object({token:s.string().min(1),name:s.string().min(1).optional(),password:s.string().min(10)}),je=s.object({email:s.email()}),Pe=s.object({email:s.email(),role:s.enum(["admin","redacteur"])}),qe=s.object({id:s.string(),data:s.object({name:s.string().min(1).optional(),role:s.enum(["admin","redacteur"]).optional(),email:s.email().optional()})}),T=({id:i,email:e,name:t,role:n})=>({id:i,email:e,name:t,role:n}),ze=s.object({name:s.string().min(1)});class Ke{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(m).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:m,user:h}).from(m).innerJoin(h,c(h.id,m.userId)).where(U(c(m.id,e),H(m.revokedAt),ie(m.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(m).set({revokedAt:t}).where(c(m.id,e)).run()}async findSessionById(e){return this.db.select().from(m).where(c(m.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(m).where(U(c(m.userId,e),H(m.revokedAt),ie(m.expiresAt,t))).orderBy(M(m.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(_).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(_).where(U(c(_.tokenHash,e),H(_.usedAt),ie(_.expiresAt,t))).get()}async markInvitationUsed(e,t){this.db.update(_).set({usedAt:t}).where(c(_.id,e)).run()}async insertApiToken(e){return this.db.insert(g).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(g).where(U(c(g.tokenHash,e),H(g.revokedAt))).get()}async touchApiToken(e,t){this.db.update(g).set({lastUsedAt:t}).where(c(g.id,e)).run()}async revokeApiToken(e,t){this.db.update(g).set({revokedAt:t}).where(c(g.id,e)).run()}async listApiTokens(){return this.db.select({id:g.id,name:g.name,lastUsedAt:g.lastUsedAt,revokedAt:g.revokedAt,createdAt:g.createdAt}).from(g).orderBy(M(g.createdAt)).all()}async purgeExpired(e){this.db.delete(m).where(ne(we(m.expiresAt,e),be(m.revokedAt))).run(),this.db.delete(_).where(ne(we(_.expiresAt,e),be(_.usedAt))).run()}}const ce=f("user-not-found-error",w.NOT_FOUND),Le=f("session-not-found-error",w.NOT_FOUND),He=f("invitation-invalid-error",w.BAD_REQUEST),Fe=f("cannot-remove-self-error",w.BAD_REQUEST),We=f("too-many-attempts-error",w.TOO_MANY_REQUESTS),q=i=>Qt("sha256").update(i).digest("hex"),I=()=>new Date().toISOString(),ri=720*3600*1e3,Qe=168*3600*1e3,oi=Bun.password.hashSync("commun-dummy-password-for-timing"),ai=5*6e4,ci=10,z=new Map,Ye=i=>{const e=Date.now(),t=(z.get(i)??[]).filter(n=>e-n<ai);return t.length?z.set(i,t):z.delete(i),t},di=i=>Ye(i).length>=ci,li=i=>{z.set(i,[...Ye(i),Date.now()])},ui=i=>z.delete(i);class Ge{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){Ae.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,n){const r=e.toLowerCase();if(di(r))throw new We;const d=await this.repository.findUserByEmail(r),l=await this.verifyPassword(t,d?.passwordHash??oi);return!d?.passwordHash||!l?(li(r),null):(ui(r),this.createSession(d,n))}async createSession(e,t){const n=new Date(Date.now()+ri).toISOString(),r=await this.repository.insertSession({userId:e.id,expiresAt:n,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Yt({session:r.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(n)).sign(this.jwtKey()),session:{sessionId:r.id,user:e,expiresAt:n}}}async verifySession(e){let t;try{const{payload:r}=await Gt(e,this.jwtKey());if(typeof r.session!="string")return null;t=r.session}catch{return null}const n=await this.repository.findActiveSessionWithUser(t,I());return n?{sessionId:n.session.id,user:n.user,expiresAt:n.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,I())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,I())).map(n=>({id:n.id,createdAt:n.createdAt,expiresAt:n.expiresAt,ua:n.ua,ip:n.ip,current:n.id===t}))}async revokeOwnSession(e,t){const n=await this.repository.findSessionById(t);if(!n||n.userId!==e)throw new Le(`session not found: ${t}`);await this.repository.revokeSession(t,I())}async purgeExpired(){await this.repository.purgeExpired(I())}async createInvitation(e){const t=re(32).toString("base64url"),n=new Date(Date.now()+Qe).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:q(t),expiresAt:n}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:n}}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const n=re(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:q(n),expiresAt:new Date(Date.now()+Qe).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${n}`}})}async acceptInvitation(e,t){const n=await this.repository.findValidInvitation(q(e),I());if(!n)throw new He;const r=await this.repository.findUserByEmail(n.email),d=t.name?.trim()||r?.name||n.email.split("@")[0]||"Membre",l=await this.repository.activateUser({email:n.email,name:d,passwordHash:await this.hashPassword(t.password),role:n.role});return await this.repository.markInvitationUsed(n.id,I()),l}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new ce(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new Fe;await this.repository.deleteUser(t)}async updateUser(e,t){const n=await this.repository.updateUser(e,t);if(!n)throw new ce(`user not found: ${e}`);return n}async createApiToken(e){const t=`commun_${re(24).toString("base64url")}`,n=await this.repository.insertApiToken({name:e,tokenHash:q(t)});return{token:t,record:n}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(q(e));return t?(await this.repository.touchApiToken(t.id,I()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,I())}async listApiTokens(){return this.repository.listApiTokens()}}const Je=S({login:C.input($e).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new F({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:T(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:T(i.session.user)})),sessions:S({list:u.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:u.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:C.input(Be).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:T(t)}}),requestPasswordReset:C.input(je).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Ve=S({list:E.query(async({ctx:i})=>(await i.services.users.listUsers()).map(T)),directory:u.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:E.input(s.object({id:s.string()})).query(async({ctx:i,input:e})=>T(await i.services.users.getUser(e.id))),invite:E.input(Pe).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:E.input(qe).mutation(async({ctx:i,input:e})=>T(await i.services.users.updateUser(e.id,e.data))),remove:E.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),Ze=S({list:E.query(({ctx:i})=>i.services.users.listApiTokens()),create:E.input(ze).mutation(async({ctx:i,input:e})=>{const{token:t,record:n}=await i.services.users.createApiToken(e.name);return{token:t,id:n.id,name:n.name}}),revoke:E.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),Xe={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},pi={createdBy:!0,updatedBy:!0},de={...Xe,...pi},et={...Xe,updatedBy:!0},tt=oe(O).omit(et),it=W(O).omit(et);class nt{constructor(e){this.db=e}async get(){return this.db.select().from(O).where(c(O.id,1)).get()}async insert(e){return this.db.insert(O).values({...e,id:1}).returning().get()}async update(e){return this.db.update(O).set(e).where(c(O.id,1)).returning().get()}}const st=f("organization-not-initialized-error",w.NOT_FOUND),rt=f("organization-already-initialized-error",w.BAD_REQUEST),ot=f("deploy-hook-missing-error",w.BAD_REQUEST),le=f("deploy-failed-error",w.INTERNAL_SERVER_ERROR),mi=3e4;class at{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 rt;return this.repository.insert(e)}async update(e,t){const n=await this.repository.update({...e,updatedBy:t??null});if(!n)throw new st;return n}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new ot;const t=this.options.fetchImpl??fetch;let n;try{n=await t(e,{signal:AbortSignal.timeout(mi)})}catch(r){throw new le(`deploy hook unreachable: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw new le(`deploy hook: ${n.status} ${n.statusText}`);return{status:n.status}}}const ct=S({get:u.query(({ctx:i})=>i.services.organization.get()),init:E.input(tt).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:E.input(it).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:u.mutation(({ctx:i})=>i.services.organization.deploy())}),dt=s.object({filename:s.string().min(1),mime:s.string().min(1),metaData:s.record(s.string(),s.string()).optional()}),lt=s.object({key:s.string().min(1),filename:s.string().min(1),mime:s.string().min(1),alt:s.string().optional(),metaData:s.record(s.string(),s.unknown()).optional()}),ut=W(b).pick({alt:!0,caption:!0,filename:!0});class pt{constructor(e){this.db=e}async insert(e){return this.db.insert(b).values(e).returning().get()}async findById(e){return this.db.select().from(b).where(c(b.id,e)).get()}async list(){return this.db.select().from(b).orderBy(M(b.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(b).where(B`json_extract(${b.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(b).set(t).where(c(b.id,e)).returning().get()}async delete(e){this.db.delete(b).where(c(b.id,e)).run()}}const G=f("media-not-found-error",w.NOT_FOUND),ue=f("unsupported-mime-error",w.BAD_REQUEST),mt=f("upload-incomplete-error",w.BAD_REQUEST),pe=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"]),hi=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],me=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",ht="medias/";class yt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,n){if(!pe.has(t))throw new ue(`unsupported mime type: ${t}`);const r=`${ht}${Oe(10)}/${me(e)}`;return{key:r,url:await this.storage.presignedPutUrl(r,t,n)}}async finalize(e,t){const n=await this.storage.head(e.key);if(!n)throw new mt(`object not found in storage: ${e.key}`);const r=await this.repository.insert({filename:me(e.filename),mime:e.mime,size:n.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Ae.info(`[media] resize \xE0 impl\xE9menter pour ${r.id} (${hi.join(", ")})`),r}async uploadDirect(e,t,n,r,d){if(!pe.has(t))throw new ue(`unsupported mime type: ${t}`);const l=`${ht}${Oe(10)}/${me(e)}`;return await this.storage.put(l,n,t),this.finalize({key:l,filename:e,mime:t,metaData:r},d)}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 G(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,n){const r=await this.repository.update(e,{...t,updatedBy:n??null});if(!r)throw new G(`media not found: ${e}`);return r}async remove(e){const t=await this.repository.findById(e);if(!t)throw new G(`media not found: ${e}`);const n=t.objects;await this.storage.remove([n.original,...Object.values(n.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,n={original:await this.storage.url(t.original)};for(const[r,d]of Object.entries(t.variants??{}))n[r]=await this.storage.url(d);return n}}const ft=S({requestUpload:u.input(dt).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:u.input(lt).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(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:u.input(s.object({id:s.string(),data:ut})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:u.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))}),gt=oe(y).omit(de).extend({fields:s.array(L).min(1),slug:s.string().optional()}),wt=W(y).omit(de).extend({fields:s.array(L).min(1).optional()}),bt=Ue(y,{fields:s.array(zt).describe("The fields every entry of the collection is made of")}),Et={...de,related:!0,collectionId:!0},_t=oe(a).omit(Et).extend({slug:s.string().optional()}),vt=W(a).omit(Et).extend({related:s.array(s.string()).optional()}),J=Ue(a,{collectionId:i=>i.describe("Id of the collection the entry belongs to"),slug:i=>i.describe("Route segment of the entry on the published site"),data:s.record(s.string(),s.unknown()).describe("Values of the collection\u2019s fields, keyed by field name"),related:s.array(s.string()).nullable().describe("Ids of the entries that reference this one"),status:i=>i.describe("Publication status; only `published` entries are on the public site")}),St=J.extend({collectionSlug:s.string().describe("Slug of the collection the entry belongs to")});class At{constructor(e){this.db=e}async list(){return this.db.select().from(y).all()}async findBySlug(e){return this.db.select().from(y).where(c(y.slug,e)).get()}async findById(e){return this.db.select().from(y).where(c(y.id,e)).get()}async findByLegacyId(e){return this.db.select().from(y).where(B`json_extract(${y.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(y).values(e).returning().get()}async update(e,t){return this.db.update(y).set(t).where(c(y.id,e)).returning().get()}async delete(e){return this.db.delete(y).where(c(y.id,e)).returning().get()}}class Ut{constructor(e){this.db=e}async list(e){return this.db.select().from(a).where(c(a.collectionId,e)).orderBy(M(a.updatedAt)).all()}narrowing(e){const t=[c(a.collectionId,e.collectionId)];return e.status?.length&&t.push(se(a.status,e.status)),e.search?.trim()&&t.push(this.matching(e.search)),U(...t)}matching(e){const t=`%${e.trim()}%`;return ne(Ee(a.title,t),Ee(a.data,t))}async search(e){const t=[this.matching(e.search)];return e.collectionIds?.length&&t.push(se(a.collectionId,e.collectionIds)),e.status?.length&&t.push(se(a.status,e.status)),this.db.select().from(a).where(U(...t)).orderBy(M(a.updatedAt)).limit(e.limit).all()}async countMatching(e){const[t]=this.db.select({total:B`count(*)`}).from(a).where(this.narrowing(e)).all();return t?.total??0}async listPaginated(e,t){const n={recent:M(a.updatedAt),oldest:_e(a.updatedAt),title:_e(a.title)};return this.db.select().from(a).where(this.narrowing({...t,collectionId:e})).orderBy(n[t.order??"recent"]).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(a).where(U(c(a.collectionId,e),c(a.status,"published"))).orderBy(M(a.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(a).where(U(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,n){return this.db.select().from(a).where(U(c(a.collectionId,e),B`json_extract(${a.data}, ${`$.${t}`}) = ${n}`)).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 V=f("collection-not-found-error",w.NOT_FOUND),Z=f("entry-not-found-error",w.NOT_FOUND),Ot=f("invalid-entry-data-error",w.BAD_REQUEST),It=f("duplicate-slug-error",w.BAD_REQUEST);function Nt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function X(i,e){const t=[];for(const n of i){if(n.type!=="relation")continue;const r=e[n.name];typeof r=="string"&&r?t.push(r):Array.isArray(r)&&t.push(...r.filter(d=>typeof d=="string"))}return[...new Set(t)]}class Dt{constructor(e,t,n){this.definitions=e,this.entries=t,this.media=n}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 V(`collection not found: ${e}`);return t}async createDefinition(e,t){return this.definitions.insert({...e,slug:e.slug||await this.uniqueDefinitionSlug(Nt(e.name)),createdBy:t??null,updatedBy:t??null})}async updateDefinition(e,t,n){const r=await this.definitions.update(e,{...t,updatedBy:n??null});if(!r)throw new V(`collection not found: ${e}`);return r}async removeDefinition(e){if(!await this.definitions.delete(e))throw new V(`collection not found: ${e}`)}validateData(e,t){const n=ge(e.fields).safeParse(t);if(!n.success)throw new Ot(`invalid data for collection ${e.slug}: ${n.error.message}`);return n.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 Z(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){const n=await this.getDefinition(e);return this.entries.listPaginated(n.id,{skip:t.skip??0,limit:t.limit??20,status:t.status,search:t.search,order:t.order})}async countEntries(e,t={}){const n=await this.getDefinition(e);return this.entries.countMatching({collectionId:n.id,status:t.status,search:t.search})}async searchEntries(e){const t=e.collections?.length?await Promise.all(e.collections.map(r=>this.getDefinition(r))):await this.definitions.list(),n=new Map(t.map(r=>[r.id,r.slug]));return(await this.entries.search({search:e.query,collectionIds:e.collections?.length?[...n.keys()]:void 0,status:e.status,limit:e.limit??20})).map(r=>({...r,collectionSlug:n.get(r.collectionId)??""}))}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,n){const r=await this.getDefinition(e),d=this.validateData(r,t.data),l=await this.uniqueEntrySlug(r.id,t.slug||Nt(t.title)),p=await this.entries.insert({...t,slug:l,data:d,collectionId:r.id,createdBy:n??null,updatedBy:n??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(r,p.id,[],X(r.fields,d)),p}async updateEntry(e,t,n){const r=await this.entries.findById(e);if(!r)throw new Z(`entry not found: ${e}`);const d=await this.getDefinition(r.collectionId),l=new Set(d.fields.map(v=>v.name)),p=Object.fromEntries(Object.entries(r.data??{}).filter(([v])=>!l.has(v))),A=t.data?{...r.data,...t.data}:r.data,N=Object.fromEntries(Object.entries(A).filter(([v])=>l.has(v)||v in(t.data??{}))),R=t.data?{...p,...this.validateData(d,N)}:void 0,te={...t,updatedBy:n??null};R&&(te.data=R),t.status==="published"&&!t.publishedAt&&(te.publishedAt=new Date().toISOString());try{const v=await this.entries.update(e,te);return R&&await this.linkRelations(d,e,X(d.fields,r.data),X(d.fields,R)),t.related&&await this.linkRelations(d,e,r.related??[],t.related),v}catch(v){throw this.mapSlugConflict(v,d.slug,t.slug??r.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new Z(`entry not found: ${e}`);const n=await this.getDefinition(t.collectionId);await this.linkRelations(n,e,X(n.fields,t.data),[]),await this.entries.delete(e)}mapSlugConflict(e,t,n){return e instanceof Error&&e.message.includes("UNIQUE constraint failed")&&e.message.includes("entries.slug")?new It(`le slug "${n}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let n=t;for(let r=1;await this.entries.findBySlug(e,n);r++)n=`${t}-${r}`;return n}async uniqueDefinitionSlug(e){let t=e;for(let n=1;await this.definitions.findBySlug(t);n++)t=`${e}-${n}`;return t}async linkRelations(e,t,n,r){const d=r.filter(p=>!n.includes(p)),l=n.filter(p=>!r.includes(p));for(const p of d){const A=await this.entries.findById(p);if(!A)continue;const N=new Set(A.related??[]);N.add(t),await this.entries.update(p,{related:[...N]})}for(const p of l){const A=await this.entries.findById(p);A&&await this.entries.update(p,{related:(A.related??[]).filter(N=>N!==t)})}}}const he=s.string().describe("Id or slug of the collection"),kt=s.array(s.enum($)).optional().describe("Keep only entries in these publication statuses"),Mt=S({list:u.query(({ctx:i})=>i.services.collections.listDefinitions()),get:u.meta({agent:{name:"collections_describe",title:"Describe a collection",description:"Returns a collection and the fields its entries are made of. Call it before reading or searching entries of a collection whose fields you do not know yet.",annotations:{readOnlyHint:!0}}}).input(s.object({idOrSlug:he})).output(bt).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:E.input(gt).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:E.input(s.object({id:s.string(),data:wt})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:E.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:S({get:u.meta({agent:{name:"entries_get",title:"Read an entry",description:"Returns one entry with all its field values, whatever its publication status.",annotations:{readOnlyHint:!0}}}).input(s.object({id:s.string().describe("Id of the entry")})).output(J).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),search:u.meta({agent:{name:"entries_search",title:"Search entries",description:"Finds entries whose title or field values contain the query, across every collection or within the ones named. Most recently updated first. Matches words literally: try a shorter word or a variant when nothing comes back.",annotations:{readOnlyHint:!0}}}).input(s.object({query:s.string().trim().min(1).max(200).describe("Text to look for"),collections:s.array(he).optional().describe("Search only these collections (ids or slugs); all of them when omitted"),status:kt,limit:s.number().int().min(1).max(50).optional().describe("Maximum number of entries returned, 20 by default")})).output(s.array(St)).query(({ctx:i,input:e})=>i.services.collections.searchEntries(e)),list:u.meta({agent:{name:"entries_list",title:"List the entries of a collection",description:"Lists the entries of one collection, 20 at a time by default, optionally narrowed by status or by a text match. Use `skip` to page.",annotations:{readOnlyHint:!0}}}).input(s.object({collectionId:he,status:kt,search:s.string().max(200).optional().describe("Keep only entries whose title or field values contain this text"),order:s.enum(["recent","oldest","title"]).optional().describe("recent (last updated first, the default), oldest, or title"),skip:s.number().int().min(0).optional().describe("Entries to skip, for paging"),limit:s.number().int().min(1).max(100).optional().describe("Maximum number of entries returned, 20 by default")})).output(s.array(J)).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),count:u.input(s.object({collectionId:s.string(),status:s.array(s.enum($)).optional(),search:s.string().max(200).optional()})).query(({ctx:i,input:e})=>i.services.collections.countEntries(e.collectionId,e)),create:u.input(s.object({collectionId:s.string(),data:_t})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:u.input(s.object({id:s.string(),data:vt})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:u.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})}),xt=f("agent-tool-not-found-error",w.NOT_FOUND);function Tt(i){const e=i._def.procedures;return Object.entries(e).flatMap(([t,n])=>{const r=n._def.meta?.agent;if(!r)return[];const d=n._def.inputs[0]??s.object({}),l=n._def.output;return[{...r,path:t,input:d,...l&&{output:l instanceof s.ZodArray?s.object({result:l}):l}}]})}async function yi(i,e,t,n){const r=Tt(i).find(p=>p.name===t);if(!r)throw new xt(`unknown agent tool: ${t}`);let d=i.createCaller(e);for(const p of r.path.split("."))d=d[p];const l=await d(n??{});return Array.isArray(l)?{result:l}:l}function fi({env:i}={}){const e=i??Ie(),t=De(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),n=Te(e),r=ee.fromEnv(e),d=new Ge(new Ke(t),{email:r,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),l=new pt(t),p=new yt(l,n),A=new Dt(new At(t),new Ut(t),p),N=new at(new nt(t)),R={health:new ke(t),users:d,organization:N,media:p,collections:A};return{env:e,db:t,storage:n,services:R}}const gi=S({health:si,auth:Je,users:Ve,apiTokens:Ze,organization:ct,media:ft,collections:Mt});export{pe as ALLOWED_MIME,xt as AgentToolNotFoundError,Fe as CannotRemoveSelfError,V as CollectionNotFoundError,Dt as CollectionsService,At as DefinitionRepository,le as DeployFailedError,ot as DeployHookMissingError,Y as DomainError,It as DuplicateSlugError,ee as EmailService,Z as EntryNotFoundError,Ut as EntryRepository,fe as FIELD_TYPES,ke as HealthService,Ot as InvalidEntryDataError,He as InvitationInvalidError,G as MediaNotFoundError,pt as MediaRepository,yt as MediaService,rt as OrganizationAlreadyInitializedError,st as OrganizationNotInitializedError,nt as OrganizationRepository,at as OrganizationService,$ as PUBLICATION_STATUSES,xe as S3Storage,Le as SessionNotFoundError,We as TooManyAttemptsError,ue as UnsupportedMimeError,mt as UploadIncompleteError,ce as UserNotFoundError,Ke as UsersRepository,Ge as UsersService,Be as acceptInvitationDto,Ne as addressSchema,Tt as agentTools,ze as apiTokenCreateDto,g as apiTokens,Ze as apiTokensRouter,gi as appRouter,Je as authRouter,ge as buildDataSchema,yi as callTool,y as collectionDefinitions,Mt as collectionsRouter,De as connectDb,fi as createCore,Te as createStorage,f as createTypedError,gt as definitionCreateDto,bt as definitionDto,wt as definitionUpdateDto,a as entries,_t as entryCreateDto,J as entryDto,St as entrySearchHitDto,vt as entryUpdateDto,L as fieldDefinitionSchema,_ as invitations,Pe as inviteDto,$e as loginDto,b as media,lt as mediaFinalizeDto,dt as mediaRequestUploadDto,ft as mediaRouter,ut as mediaUpdateDto,O as organization,tt as organizationInitDto,ct as organizationRouter,it as organizationUpdateDto,Ie as parseEnv,je as requestPasswordResetDto,m as sessions,T as toPublicUser,qe as userUpdateDto,h as users,Ve as usersRouter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-commune/core",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "description": "Business domains, database schema and tRPC router. Holds the logic; knows nothing of transport.",
6
6
  "main": "./dist/index.mjs",