@open-commune/core 0.2.20 → 0.2.22
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 +287 -68
- package/dist/index.d.ts +287 -68
- package/dist/index.mjs +3 -3
- package/dist/shared/{core.gEnNgWB8.d.ts → core.BLcc-Hxe.d.ts} +42 -11
- package/dist/shared/{core.CUIVeC31.d.mts → core.C-cdTqDU.d.mts} +42 -11
- package/dist/shared/core.W03pfXvx.mjs +1 -0
- package/drizzle/0001_entries-fts.sql +63 -0
- package/drizzle/meta/0001_snapshot.json +718 -0
- package/drizzle/meta/_journal.json +8 -1
- package/package.json +1 -1
- package/dist/shared/core.BR6-3c3l.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{homedir as Dt}from"node:os";import{join as K}from"node:path";import{z as r}from"zod";import{Database as Tt}from"bun:sqlite";import{mkdirSync as Rt,existsSync as Ct}from"node:fs";import{drizzle as kt}from"drizzle-orm/bun-sqlite";import{migrate as xt}from"drizzle-orm/bun-sqlite/migrator";import{z as $t,B as h,C as p,D as y,F as v,E as w,u as Z,a as X,v as C,w as ee,o as we,x as fe,y as ge,m as te,b as Ee,G as k,t as ve,s as _e,H as N,r as Oe,p as Ue,q as Ie,I,J as a,l as be,i as Ne,j as q,k as Se,h as Ae,f as Me,g as De,e as Te,c as Re}from"./shared/core.BR6-3c3l.mjs";export{A as AUDIENCE_PERIODS,K as addressSchema,d as audienceQuerySchema,n as isErrorType}from"./shared/core.BR6-3c3l.mjs";import{sql as m,eq as c,and as A,isNull as $,gt as z,desc as M,notExists as Bt,or as ie,lt as Ce,isNotNull as ke,inArray as se,like as xe,asc as ne}from"drizzle-orm";import{S3Client as Pt,PutObjectCommand as $e,HeadObjectCommand as jt,DeleteObjectsCommand as Lt,GetObjectCommand as Kt}from"@aws-sdk/client-s3";import{getSignedUrl as Be}from"@aws-sdk/s3-request-presigner";import{initTRPC as qt,TRPCError as F}from"@trpc/server";import{randomBytes as re,createHash as zt}from"node:crypto";import{SignJWT as Ft,jwtVerify as Ht}from"jose";import{consola as B}from"consola";import{nanoid as Pe}from"nanoid";import{buildDataSchema as je}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS,fieldDefinitionSchema}from"./domains/collections/utils.mjs";import{PUBLICATION_STATUSES as Le}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),Yt=r.object({COMMUN_DATA_DIR:r.string().default(K(Dt(),".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 Ke(i=process.env){return Yt.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 Wt(){const i=import.meta.dir;return i?K(i,"..","..","..","drizzle"):void 0}function qe(i,e){const t=e??Wt();Rt(i,{recursive:!0});const s=new Tt(K(i,"commun.db"));s.exec("PRAGMA journal_mode=WAL"),s.exec("PRAGMA foreign_keys=ON"),s.exec("PRAGMA busy_timeout=5000");const n=kt({client:s,schema:$t});return t&&Ct(K(t,"meta","_journal.json"))&&xt(n,{migrationsFolder:t}),n}class J{constructor(e){this.config=e}static fromEnv(e){return new J({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 ze{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 Fe=168*3600,Gt="medias/";class He{constructor(e){this.config=e,this.client=new Pt({region:e.region,endpoint:e.endpoint,forcePathStyle:!0,credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,s){return Be(this.client,new $e({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:s}),{expiresIn:Fe})}async put(e,t,s){await this.client.send(new $e({Bucket:this.config.bucket,Key:e,Body:t,ContentType:s}))}async head(e){try{return{size:(await this.client.send(new jt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Lt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Gt)?Promise.resolve(this.publicUrl(e)):Be(this.client,new Kt({Bucket:this.config.bucket,Key:e}),{expiresIn:Fe})}publicUrl(e){const t=this.config.endpoint.replace(/\/+$/,""),s=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${s}`}}function Ye(i){return new He({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 g={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class H extends Error{}function f(i,e){return class extends H{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const oe=(i,e)=>i instanceof Error&&i.message.includes("UNIQUE constraint failed")&&i.message.includes(e),Y=qt.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof H?{type:t.type}:{}}}}}),b=Y.router,Vt=Y.mergeRouters,We=Y.procedure,ae=Y.middleware,Qt=ae(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof H)throw new F({code:t.trpcCode,message:t.message,cause:t})}return e}),T=We.use(Qt),Ge=i=>ae(({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}})}),l=T.use(Ge()),E=T.use(Ge("admin")),Jt=b({ping:T.query(({ctx:i})=>i.services.health.check())});class Ve{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(A(c(p.id,e),$(p.revokedAt),z(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(A(c(p.userId,e),$(p.revokedAt),z(p.expiresAt,t))).orderBy(M(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(A(c(y.tokenHash,e),$(y.usedAt),z(y.expiresAt,t))).get()}async listPendingInvitations(e){return this.db.select().from(y).where(A($(y.usedAt),z(y.expiresAt,e),Bt(this.db.select({one:m`1`}).from(h).where(c(h.email,y.email))))).orderBy(M(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(A(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(M(v.createdAt)).all()}async purgeExpired(e){this.db.delete(p).where(ie(Ce(p.expiresAt,e),ke(p.revokedAt))).run(),this.db.delete(y).where(ie(Ce(y.expiresAt,e),ke(y.usedAt))).run()}}const ce=f(w.USER_NOT_FOUND,g.NOT_FOUND),Qe=f(w.SESSION_NOT_FOUND,g.NOT_FOUND),le=f(w.INVITATION_INVALID,g.BAD_REQUEST),Je=f(w.CANNOT_REMOVE_SELF,g.BAD_REQUEST),Ze=f(w.TOO_MANY_ATTEMPTS,g.TOO_MANY_REQUESTS),P=i=>zt("sha256").update(i).digest("hex"),D=()=>new Date().toISOString(),Zt=720*3600*1e3,Xe=168*3600*1e3,Xt=Bun.password.hashSync("commun-dummy-password-for-timing"),ei=5*6e4,ti=10,j=new Map,et=i=>{const e=Date.now(),t=(j.get(i)??[]).filter(s=>e-s<ei);return t.length?j.set(i,t):j.delete(i),t},ii=i=>et(i).length>=ti,si=i=>{j.set(i,[...et(i),Date.now()])},ni=i=>j.delete(i);class tt{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){B.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(ii(n))throw new Ze;const o=await this.repository.findUserByEmail(n),u=await this.verifyPassword(t,o?.passwordHash??Xt);return!o?.passwordHash||!u?(si(n),null):(ni(n),this.createSession(o,s))}async createSession(e,t){const s=new Date(Date.now()+Zt).toISOString(),n=await this.repository.insertSession({userId:e.id,expiresAt:s,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Ft({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 Ht(e,this.jwtKey());if(typeof n.session!="string")return null;t=n.session}catch{return null}const s=await this.repository.findActiveSessionWithUser(t,D());return s?{sessionId:s.session.id,user:s.user,expiresAt:s.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,D())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,D())).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 Qe(`session not found: ${t}`);await this.repository.revokeSession(t,D())}async purgeExpired(){await this.repository.purgeExpired(D())}async createInvitation(e){const t=re(32).toString("base64url"),s=new Date(Date.now()+Xe).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:P(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(D())).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 le}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const s=re(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:P(s),expiresAt:new Date(Date.now()+Xe).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(P(e),D());if(!s)throw new le;const n=await this.repository.findUserByEmail(s.email),o=t.name?.trim()||n?.name||s.email.split("@")[0]||"Membre",u=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,D()),u}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 Je;await this.repository.deleteUser(t)}async updateUser(e,t){const s=await this.repository.updateUser(e,t);if(!s)throw new ce(`user not found: ${e}`);return s}async createApiToken(e){const t=`commun_${re(24).toString("base64url")}`,s=await this.repository.insertApiToken({name:e,tokenHash:P(t)});return{token:t,record:s}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(P(e));return t?(await this.repository.touchApiToken(t.id,D()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,D())}async listApiTokens(){return this.repository.listApiTokens()}}const it=b({login:T.input(we).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:ee(t.session.user,{audience:i.services.audience.visibleTo(t.session.user.email)})}}),logout:l.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:l.query(({ctx:i})=>({user:ee(i.session.user,{audience:i.services.audience.visibleTo(i.session.user.email)})})),sessions:b({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(X).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:C(t)}}),requestPasswordReset:T.input(Z).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),st=b({list:E.query(async({ctx:i})=>(await i.services.users.listUsers()).map(C)),directory:l.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:E.input(r.object({id:r.string()})).query(async({ctx:i,input:e})=>C(await i.services.users.getUser(e.id))),invite:E.input(te).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:E.input(ge).mutation(async({ctx:i,input:e})=>C(await i.services.users.updateUser(e.id,e.data))),updateOwnProfile:l.input(fe).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.updateUser(i.session.user.id,e);return{user:C(t)}}),remove:E.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}))}),nt=b({list:E.query(({ctx:i})=>i.services.users.listApiTokens()),create:E.input(Ee).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:E.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),rt=b({create:E.input(te).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),list:E.query(({ctx:i})=>i.services.users.listPendingInvitations()),revoke:E.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(X).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:C(t)}}),requestPasswordReset:T.input(Z).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))});class ot{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 at=f(w.ORGANIZATION_NOT_INITIALIZED,g.NOT_FOUND),ct=f(w.ORGANIZATION_ALREADY_INITIALIZED,g.BAD_REQUEST),lt=f(w.DEPLOY_HOOK_MISSING,g.BAD_REQUEST),ue=f(w.DEPLOY_FAILED,g.INTERNAL_SERVER_ERROR),ri=3e4;class ut{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 ct;return this.repository.insert(e)}async update(e,t){const s=await this.repository.update({...e,updatedBy:t??null});if(!s)throw new at;return s}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new lt;const t=this.options.fetchImpl??fetch;let s;try{s=await t(e,{signal:AbortSignal.timeout(ri)})}catch(n){throw new ue(`deploy hook unreachable: ${n instanceof Error?n.message:String(n)}`)}if(!s.ok)throw new ue(`deploy hook: ${s.status} ${s.statusText}`);return{status:s.status}}}const dt=b({get:l.query(({ctx:i})=>i.services.organization.get()),init:E.input(_e).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:E.input(ve).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:l.mutation(({ctx:i})=>i.services.organization.deploy())});class ht{constructor(e){this.db=e}async insert(e){return this.db.insert(N).values(e).returning().get()}async findById(e){return this.db.select().from(N).where(c(N.id,e)).get()}async list(){return this.db.select().from(N).orderBy(M(N.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(N).where(m`json_extract(${N.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(N).set(t).where(c(N.id,e)).returning().get()}async delete(e){this.db.delete(N).where(c(N.id,e)).run()}}const W=f(w.MEDIA_NOT_FOUND,g.NOT_FOUND),de=f(w.UNSUPPORTED_MIME,g.BAD_REQUEST),pt=f(w.UPLOAD_INCOMPLETE,g.BAD_REQUEST),he=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"]),oi=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],pe=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",mt="medias/";class yt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,s){if(!he.has(t))throw new de(`unsupported mime type: ${t}`);const n=`${mt}${Pe(10)}/${pe(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 pt(`object not found in storage: ${e.key}`);const n=await this.repository.insert({filename:pe(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 B.info(`[media] resize \xE0 impl\xE9menter pour ${n.id} (${oi.join(", ")})`),n}async uploadDirect(e,t,s,n,o){if(!he.has(t))throw new de(`unsupported mime type: ${t}`);const u=`${mt}${Pe(10)}/${pe(e)}`;return await this.storage.put(u,s,t),this.finalize({key:u,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 W(`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 W(`media not found: ${e}`);return n}async remove(e){const t=await this.repository.findById(e);if(!t)throw new W(`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 wt=b({requestUpload:l.input(Ie).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:l.input(Ue).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:Oe})).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 ft{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 ai="[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*";class gt{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=[];if(e.collectionId&&t.push(c(a.collectionId,e.collectionId)),e.status?.length&&t.push(se(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?A(...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 ${
|
|
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?A(...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 ie(xe(a.title,t),xe(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(A(...t)).orderBy(M(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(M(a.updatedAt)).limit(e).all()}async listPaginated(e){const t=e.order??(e.date?"date_asc":"recent"),s=o=>{const u=this.dateKey(e.date,o);return[m`${u} is null`,o?M(u):ne(u)]},n={recent:()=>[M(a.updatedAt)],oldest:()=>[ne(a.updatedAt)],title:()=>[ne(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(A(c(a.collectionId,e),c(a.status,"published"))).orderBy(M(a.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(a).where(A(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(A(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 G=f(w.COLLECTION_NOT_FOUND,g.NOT_FOUND),V=f(w.ENTRY_NOT_FOUND,g.NOT_FOUND),Et=f(w.INVALID_ENTRY_DATA,g.BAD_REQUEST),me=f(w.DUPLICATE_SLUG,g.BAD_REQUEST);function vt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function Q(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 G(`collection not found: ${e}`);return t}async createDefinition(e,t){const s=e.slug||await this.uniqueDefinitionSlug(vt(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 G(`collection not found: ${e}`);return n}async removeDefinition(e){if(!await this.definitions.delete(e))throw new G(`collection not found: ${e}`)}validateData(e,t){const s=je(e.fields).safeParse(t);if(!s.success)throw new Et(`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 V(`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),u=await this.uniqueEntrySlug(n.id,t.slug||vt(t.title)),d=await this.entries.insert({...t,slug:u,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,d.id,[],Q(n.fields,o)),d}async updateEntry(e,t,s){const n=await this.entries.findById(e);if(!n)throw new V(`entry not found: ${e}`);const o=await this.getDefinition(n.collectionId),u=new Set(o.fields.map(O=>O.name)),d=Object.fromEntries(Object.entries(n.data??{}).filter(([O])=>!u.has(O))),U=t.data?{...n.data,...t.data}:n.data,S=Object.fromEntries(Object.entries(U).filter(([O])=>u.has(O)||O in(t.data??{}))),_=t.data?{...d,...this.validateData(o,S)}:void 0,R={...t,updatedBy:s??null};_&&(R.data=_),t.status==="published"&&!t.publishedAt&&(R.publishedAt=new Date().toISOString());try{const O=await this.entries.update(e,R);return _&&await this.linkRelations(o,e,Q(o.fields,n.data),Q(o.fields,_)),t.related&&await this.linkRelations(o,e,n.related??[],t.related),O}catch(O){throw this.entrySlugConflict(O,o.slug,t.slug??n.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new V(`entry not found: ${e}`);const s=await this.getDefinition(t.collectionId);await this.linkRelations(s,e,Q(s.fields,t.data),[]),await this.entries.delete(e)}definitionSlugConflict(e,t){return oe(e,"collection_definitions.slug")?new me(`le slug "${t}" est d\xE9j\xE0 celui d'une collection`):e}entrySlugConflict(e,t,s){return oe(e,"entries.slug")?new me(`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(d=>!s.includes(d)),u=s.filter(d=>!n.includes(d));for(const d of o){const U=await this.entries.findById(d);if(!U)continue;const S=new Set(U.related??[]);S.add(t),await this.entries.update(d,{related:[...S]})}for(const d of u){const U=await this.entries.findById(d);U&&await this.entries.update(d,{related:(U.related??[]).filter(S=>S!==t)})}}}const ye=r.string().describe("Id or slug of the collection"),Ot=r.array(r.enum(Le)).optional().describe("Keep only entries in these publication statuses"),Ut=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:ye.optional().describe("Id or slug of the collection; every collection of the site when omitted"),status:Ot,search:r.string().max(200).optional().describe("Keep only entries whose title or field values contain this text"),date:r.object({gte:Ut.optional().describe("From this date, included"),lte:Ut.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)")},bt=b({list:l.query(({ctx:i})=>i.services.collections.listDefinitions()),get:l.input(r.object({idOrSlug:ye})).output(De).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:E.input(Me).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:E.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:E.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:b({get:l.input(r.object({id:r.string().describe("Id of the entry")})).output(q).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(ye).optional().describe("Search only these collections (ids or slugs); all of them when omitted"),status:Ot,limit:r.number().int().min(1).max(50).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(Se)).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(q)).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(q)).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:Ne})).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:be})).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}))})}),L=f(w.AUDIENCE_UNAVAILABLE,g.NOT_FOUND),ci=6e4,Nt=10*6e4,li=8e3,ui=5,di=90;class St{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;sitePages;viewers;visibleTo(e){return this.config.url?!this.viewers.length||this.viewers.includes(e.trim().toLowerCase()):!1}async summary(e,t){if(!this.config.url)throw new L("no audience source");if(!this.visibleTo(t))throw new L("not among the viewers");const s=`${e.period}:${e.collection??""}:${e.entry??""}`,n=this.cache.get(s);if(n&&Date.now()-n.at<ci)return n.value;const o=e.entry?await this.entrySlug(e.entry):void 0;if(e.entry&&!o)throw new L(`unknown entry ${e.entry}`);const u=e.collection?await this.siteSegment(e.collection):void 0,d=await this.ask(this.config.url,new URLSearchParams({period:String(e.period),...u?{collection:u}:{},...o?{entry:o}:{}}));if(!d)throw new L("the source did not answer");const U=await this.knownNames(),S={...d,top:(d.top??[]).slice(0,ui).map(_=>{const R=_.path.split("/").filter(Boolean),O=U.entries.get(R.at(-1)??""),Mt=!O&&R.length===1&&_.collection?U.collections.get(_.collection):void 0;return{path:_.path,collection:_.collection??null,visits:_.views,title:_.path==="/"?"Accueil":O?.title??Mt??_.path,entryId:O?.id??null}})};return this.cache.set(s,{at:Date.now(),value:S}),S}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(li)});if(!n.ok)return B.warn(`[audience] the source answered ${n.status} to ${t}`),null;const o=Te.safeParse(await n.json());return o.success?o.data:(B.warn(`[audience] the source's answer to ${t} does not parse`,o.error.issues),null)}catch(n){return B.warn(`[audience] the source did not answer ${t}: ${String(n)}`),null}}async siteSegment(e){const t=await this.mostReadPaths();if(!t.length)return e;let s;try{s=new Set((await this.collections.listPublishedEntries(e)).map(n=>n.slug))}catch{return e}for(const n of t){const o=n.split("/").filter(Boolean),u=o.at(-1);if(o.length>=2&&u&&s.has(u))return o.at(-2)}return e}async mostReadPaths(){if(this.sitePages&&Date.now()-this.sitePages.at<Nt)return this.sitePages.paths;if(!this.config.url)return[];const e=await this.ask(this.config.url,new URLSearchParams({period:String(di)}));if(!e)return[];const t=(e.top??[]).map(s=>s.path);return this.sitePages={at:Date.now(),paths:t},t}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<Nt)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=b({summary:l.input(Re).query(({ctx:i,input:e})=>i.services.audience.summary(e,i.session.user.email))});function hi({env:i}={}){const e=i??Ke(),t=qe(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),s=Ye(e),n=J.fromEnv(e),o=new tt(new Ve(t),{email:n,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),u=new ht(t),d=new yt(u,s),U=new _t(new ft(t),new gt(t),d),S=new ut(new ot(t)),_=new St(U,{url:e.OPEN_COMMUNE_AUDIENCE_URL,token:e.OPEN_COMMUNE_AUDIENCE_TOKEN,viewers:e.OPEN_COMMUNE_AUDIENCE_VIEWERS}),R={health:new ze(t),users:o,organization:S,media:d,collections:U,audience:_};return{env:e,db:t,storage:s,services:R}}const pi=b({health:Jt,auth:it,users:st,invitations:rt,apiTokens:nt,organization:dt,media:wt,collections:bt,audience:At});export{he as ALLOWED_MIME,St as AudienceService,L as AudienceUnavailableError,Je as CannotRemoveSelfError,G as CollectionNotFoundError,_t as CollectionsService,ft as DefinitionRepository,ue as DeployFailedError,lt as DeployHookMissingError,H as DomainError,me as DuplicateSlugError,w as ERROR_TYPES,J as EmailService,V as EntryNotFoundError,gt as EntryRepository,ze as HealthService,Et as InvalidEntryDataError,le as InvitationInvalidError,W as MediaNotFoundError,ht as MediaRepository,yt as MediaService,ct as OrganizationAlreadyInitializedError,at as OrganizationNotInitializedError,ot as OrganizationRepository,ut as OrganizationService,Le as PUBLICATION_STATUSES,He as S3Storage,Qe as SessionNotFoundError,Ze as TooManyAttemptsError,de as UnsupportedMimeError,pt as UploadIncompleteError,ce as UserNotFoundError,Ve as UsersRepository,tt as UsersService,X as acceptInvitationDto,E as adminProcedure,Ee as apiTokenCreateDto,v as apiTokens,nt as apiTokensRouter,pi as appRouter,Re as audienceAskDto,At as audienceRouter,Te as audienceSummarySchema,it as authRouter,je as buildDataSchema,I as collectionDefinitions,bt as collectionsRouter,qe as connectDb,hi as createCore,Ye as createStorage,f as createTypedError,Me as definitionCreateDto,De as definitionDto,Ae as definitionUpdateDto,a as entries,Ne as entryCreateDto,q as entryDto,Se as entrySearchHitDto,be as entryUpdateDto,y as invitations,rt as invitationsRouter,te as inviteDto,oe as isUniqueViolation,we as loginDto,N as media,Ue as mediaFinalizeDto,Ie as mediaRequestUploadDto,wt as mediaRouter,Oe as mediaUpdateDto,Vt as mergeRouters,ae as middleware,k as organization,_e as organizationInitDto,dt as organizationRouter,ve as organizationUpdateDto,Ke as parseEnv,T as procedure,l as protectedProcedure,We as publicProcedure,Z as requestPasswordResetDto,b as router,p as sessions,C as toPublicUser,ee as toSessionUser,fe as updateOwnProfileDto,ge as userUpdateDto,h as users,st as usersRouter};
|
|
1
|
+
import{homedir as Ft}from"node:os";import{join as G}from"node:path";import{z as r}from"zod";import{Database as Ht}from"bun:sqlite";import{mkdirSync as Yt,existsSync as Wt}from"node:fs";import{drizzle as Vt}from"drizzle-orm/bun-sqlite";import{migrate as Gt}from"drizzle-orm/bun-sqlite/migrator";import{B as Qt,C as y,D as m,F as f,G as N,E as g,v as le,a as de,w as k,x as ue,p as Ue,y as Se,z as Ae,n as he,b as Me,H as B,u as De,t as xe,I as O,s as Te,q as Ce,r as Re,J as S,K as c,m as ke,i as $e,j as Q,k as Be,l as Pe,h as je,f as Le,g as qe,e as Ke,c as ze}from"./shared/core.W03pfXvx.mjs";export{A as AUDIENCE_PERIODS,L as addressSchema,d as audienceQuerySchema,o as isErrorType}from"./shared/core.W03pfXvx.mjs";import{sql as p,eq as a,and as D,isNull as j,gt as J,desc as T,notExists as Jt,or as Fe,lt as He,isNotNull as Ye,inArray as $,asc as L,getTableColumns as Zt}from"drizzle-orm";import{S3Client as Xt,PutObjectCommand as We,HeadObjectCommand as ei,DeleteObjectsCommand as ti,GetObjectCommand as ii}from"@aws-sdk/client-s3";import{getSignedUrl as Ve}from"@aws-sdk/s3-request-presigner";import{initTRPC as si,TRPCError as Z}from"@trpc/server";import{randomBytes as pe,createHash as ni}from"node:crypto";import{SignJWT as ri,jwtVerify as oi}from"jose";import{consola as q}from"consola";import{nanoid as Ge}from"nanoid";import{sqliteTable as ai,text as A,sqliteView as Qe,integer as Je}from"drizzle-orm/sqlite-core";import{buildDataSchema as Ze}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS,fieldDefinitionSchema}from"./domains/collections/utils.mjs";import{PUBLICATION_STATUSES as Xe}from"./domains/collections/constants.mjs";export{FIELD_TYPES}from"./domains/collections/constants.mjs";import"drizzle-zod";const P=r.string().min(1),ci=r.object({COMMUN_DATA_DIR:r.string().default(G(Ft(),".commun")),COMMUN_MIGRATIONS_DIR:r.string().optional(),COMMUN_S3_ENDPOINT:P,COMMUN_S3_REGION:r.string().default("fr-par"),COMMUN_S3_BUCKET:P,COMMUN_S3_ACCESS_KEY:P,COMMUN_S3_SECRET_KEY:P,COMMUN_EMAIL_WEBHOOK_URL:P,COMMUN_EMAIL_WEBHOOK_TOKEN:r.string().optional(),COMMUN_ADMIN_URL:r.string().optional(),COMMUN_JWT_SECRET:P,OPEN_COMMUNE_AUDIENCE_URL:r.url().optional(),OPEN_COMMUNE_AUDIENCE_TOKEN:r.string().optional(),OPEN_COMMUNE_AUDIENCE_VIEWERS:r.string().optional()});function et(i=process.env){return ci.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 li(){const i=import.meta.dir;return i?G(i,"..","..","..","drizzle"):void 0}function tt(i,e){const t=e??li();Yt(i,{recursive:!0});const s=new Ht(G(i,"commun.db"));s.exec("PRAGMA journal_mode=WAL"),s.exec("PRAGMA foreign_keys=ON"),s.exec("PRAGMA busy_timeout=5000");const n=Vt({client:s,schema:Qt});return t&&Wt(G(t,"meta","_journal.json"))&&Gt(n,{migrationsFolder:t}),n}class ae{constructor(e){this.config=e}static fromEnv(e){return new ae({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 it{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(p`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const st=168*3600,di="medias/";class nt{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 Ve(this.client,new We({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:s}),{expiresIn:st})}async put(e,t,s){await this.client.send(new We({Bucket:this.config.bucket,Key:e,Body:t,ContentType:s}))}async head(e){try{return{size:(await this.client.send(new ei({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new ti({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(di)?Promise.resolve(this.publicUrl(e)):Ve(this.client,new ii({Bucket:this.config.bucket,Key:e}),{expiresIn:st})}publicUrl(e){const t=this.config.endpoint.replace(/\/+$/,""),s=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${s}`}}function rt(i){return new nt({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 b={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class X extends Error{}function E(i,e){return class extends X{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const ye=(i,e)=>i instanceof Error&&i.message.includes("UNIQUE constraint failed")&&i.message.includes(e),ee=si.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof X?{type:t.type}:{}}}}}),M=ee.router,ui=ee.mergeRouters,ot=ee.procedure,me=ee.middleware,hi=me(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof X)throw new Z({code:t.trpcCode,message:t.message,cause:t})}return e}),R=ot.use(hi),at=i=>me(({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}})}),h=R.use(at()),_=R.use(at("admin")),pi=M({ping:R.query(({ctx:i})=>i.services.health.check())});class ct{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(y).where(a(y.email,e)).get()}async findUserById(e){return this.db.select().from(y).where(a(y.id,e)).get()}async listUsers(){return this.db.select().from(y).all()}async hasAnyUser(){return this.db.select({id:y.id}).from(y).limit(1).all().length>0}async deleteUser(e){this.db.delete(y).where(a(y.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(y).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(a(y.id,t.id)).returning().get():this.db.insert(y).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:y}).from(m).innerJoin(y,a(y.id,m.userId)).where(D(a(m.id,e),j(m.revokedAt),J(m.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(m).set({revokedAt:t}).where(a(m.id,e)).run()}async findSessionById(e){return this.db.select().from(m).where(a(m.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(m).where(D(a(m.userId,e),j(m.revokedAt),J(m.expiresAt,t))).orderBy(T(m.createdAt)).all()}async updateUser(e,t){return this.db.update(y).set(t).where(a(y.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(f).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(f).where(D(a(f.tokenHash,e),j(f.usedAt),J(f.expiresAt,t))).get()}async listPendingInvitations(e){return this.db.select().from(f).where(D(j(f.usedAt),J(f.expiresAt,e),Jt(this.db.select({one:p`1`}).from(y).where(a(y.email,f.email))))).orderBy(T(f.createdAt)).all()}async deleteInvitation(e){return!!this.db.delete(f).where(a(f.id,e)).returning().get()}async markInvitationUsed(e,t){this.db.update(f).set({usedAt:t}).where(a(f.id,e)).run()}async insertApiToken(e){return this.db.insert(N).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(N).where(D(a(N.tokenHash,e),j(N.revokedAt))).get()}async touchApiToken(e,t){this.db.update(N).set({lastUsedAt:t}).where(a(N.id,e)).run()}async revokeApiToken(e,t){this.db.update(N).set({revokedAt:t}).where(a(N.id,e)).run()}async listApiTokens(){return this.db.select({id:N.id,name:N.name,lastUsedAt:N.lastUsedAt,revokedAt:N.revokedAt,createdAt:N.createdAt}).from(N).orderBy(T(N.createdAt)).all()}async purgeExpired(e){this.db.delete(m).where(Fe(He(m.expiresAt,e),Ye(m.revokedAt))).run(),this.db.delete(f).where(Fe(He(f.expiresAt,e),Ye(f.usedAt))).run()}}const we=E(g.USER_NOT_FOUND,b.NOT_FOUND),lt=E(g.SESSION_NOT_FOUND,b.NOT_FOUND),fe=E(g.INVITATION_INVALID,b.BAD_REQUEST),dt=E(g.CANNOT_REMOVE_SELF,b.BAD_REQUEST),ut=E(g.TOO_MANY_ATTEMPTS,b.TOO_MANY_REQUESTS),K=i=>ni("sha256").update(i).digest("hex"),C=()=>new Date().toISOString(),yi=720*3600*1e3,ht=168*3600*1e3,mi=Bun.password.hashSync("commun-dummy-password-for-timing"),wi=5*6e4,fi=10,z=new Map,pt=i=>{const e=Date.now(),t=(z.get(i)??[]).filter(s=>e-s<wi);return t.length?z.set(i,t):z.delete(i),t},gi=i=>pt(i).length>=fi,Ei=i=>{z.set(i,[...pt(i),Date.now()])},vi=i=>z.delete(i);class yt{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){q.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(gi(n))throw new ut;const o=await this.repository.findUserByEmail(n),l=await this.verifyPassword(t,o?.passwordHash??mi);return!o?.passwordHash||!l?(Ei(n),null):(vi(n),this.createSession(o,s))}async createSession(e,t){const s=new Date(Date.now()+yi).toISOString(),n=await this.repository.insertSession({userId:e.id,expiresAt:s,ua:t?.ua??null,ip:t?.ip??null});return{token:await new ri({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 oi(e,this.jwtKey());if(typeof n.session!="string")return null;t=n.session}catch{return null}const s=await this.repository.findActiveSessionWithUser(t,C());return s?{sessionId:s.session.id,user:s.user,expiresAt:s.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,C())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,C())).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 lt(`session not found: ${t}`);await this.repository.revokeSession(t,C())}async purgeExpired(){await this.repository.purgeExpired(C())}async createInvitation(e){const t=pe(32).toString("base64url"),s=new Date(Date.now()+ht).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:K(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(C())).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 fe}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const s=pe(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:K(s),expiresAt:new Date(Date.now()+ht).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(K(e),C());if(!s)throw new fe;const n=await this.repository.findUserByEmail(s.email),o=t.name?.trim()||n?.name||s.email.split("@")[0]||"Membre",l=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,C()),l}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new we(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new dt;await this.repository.deleteUser(t)}async updateUser(e,t){const s=await this.repository.updateUser(e,t);if(!s)throw new we(`user not found: ${e}`);return s}async createApiToken(e){const t=`commun_${pe(24).toString("base64url")}`,s=await this.repository.insertApiToken({name:e,tokenHash:K(t)});return{token:t,record:s}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(K(e));return t?(await this.repository.touchApiToken(t.id,C()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,C())}async listApiTokens(){return this.repository.listApiTokens()}}const mt=M({login:R.input(Ue).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:ue(t.session.user,{audience:i.services.audience.visibleTo(t.session.user.email)})}}),logout:h.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:h.query(({ctx:i})=>({user:ue(i.session.user,{audience:i.services.audience.visibleTo(i.session.user.email)})})),sessions:M({list:h.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:h.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:R.input(de).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:k(t)}}),requestPasswordReset:R.input(le).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),wt=M({list:_.query(async({ctx:i})=>(await i.services.users.listUsers()).map(k)),directory:h.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})=>k(await i.services.users.getUser(e.id))),invite:_.input(he).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:_.input(Ae).mutation(async({ctx:i,input:e})=>k(await i.services.users.updateUser(e.id,e.data))),updateOwnProfile:h.input(Se).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.updateUser(i.session.user.id,e);return{user:k(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}))}),ft=M({list:_.query(({ctx:i})=>i.services.users.listApiTokens()),create:_.input(Me).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}))}),gt=M({create:_.input(he).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:R.input(de).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:k(t)}}),requestPasswordReset:R.input(le).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))});class Et{constructor(e){this.db=e}async get(){return this.db.select().from(B).where(a(B.id,1)).get()}async insert(e){return this.db.insert(B).values({...e,id:1}).returning().get()}async update(e){return this.db.update(B).set(e).where(a(B.id,1)).returning().get()}}const vt=E(g.ORGANIZATION_NOT_INITIALIZED,b.NOT_FOUND),bt=E(g.ORGANIZATION_ALREADY_INITIALIZED,b.BAD_REQUEST),_t=E(g.DEPLOY_HOOK_MISSING,b.BAD_REQUEST),ge=E(g.DEPLOY_FAILED,b.INTERNAL_SERVER_ERROR),bi=3e4;class It{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 bt;return this.repository.insert(e)}async update(e,t){const s=await this.repository.update({...e,updatedBy:t??null});if(!s)throw new vt;return s}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new _t;const t=this.options.fetchImpl??fetch;let s;try{s=await t(e,{signal:AbortSignal.timeout(bi)})}catch(n){throw new ge(`deploy hook unreachable: ${n instanceof Error?n.message:String(n)}`)}if(!s.ok)throw new ge(`deploy hook: ${s.status} ${s.statusText}`);return{status:s.status}}}const Nt=M({get:h.query(({ctx:i})=>i.services.organization.get()),init:_.input(xe).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:_.input(De).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:h.mutation(({ctx:i})=>i.services.organization.deploy())});class Ot{constructor(e){this.db=e}async insert(e){return this.db.insert(O).values(e).returning().get()}async findById(e){return this.db.select().from(O).where(a(O.id,e)).get()}async findByIds(e){return e.length?this.db.select().from(O).where($(O.id,e)).all():[]}async list(){return this.db.select().from(O).orderBy(T(O.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(O).where(p`json_extract(${O.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(O).set(t).where(a(O.id,e)).returning().get()}async delete(e){this.db.delete(O).where(a(O.id,e)).run()}}const te=E(g.MEDIA_NOT_FOUND,b.NOT_FOUND),Ee=E(g.UNSUPPORTED_MIME,b.BAD_REQUEST),Ut=E(g.UPLOAD_INCOMPLETE,b.BAD_REQUEST),ve=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"]),_i=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],be=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",St="medias/";class At{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,s){if(!ve.has(t))throw new Ee(`unsupported mime type: ${t}`);const n=`${St}${Ge(10)}/${be(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 Ut(`object not found in storage: ${e.key}`);const n=await this.repository.insert({filename:be(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 q.info(`[media] resize \xE0 impl\xE9menter pour ${n.id} (${_i.join(", ")})`),n}async uploadDirect(e,t,s,n,o){if(!ve.has(t))throw new Ee(`unsupported mime type: ${t}`);const l=`${St}${Ge(10)}/${be(e)}`;return await this.storage.put(l,s,t),this.finalize({key:l,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 te(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async getMany(e){const t=await this.repository.findByIds([...new Set(e)]);return Promise.all(t.map(async s=>({...s,objects:await this.objectUrls(s)})))}async updateEditorial(e,t,s){const n=await this.repository.update(e,{...t,updatedBy:s??null});if(!n)throw new te(`media not found: ${e}`);return n}async remove(e){const t=await this.repository.findById(e);if(!t)throw new te(`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 Mt=M({requestUpload:h.input(Re).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:h.input(Ce).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:h.query(({ctx:i})=>i.services.media.listResolved()),get:h.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),getMany:h.input(r.object({ids:r.array(r.string()).min(1).max(100)})).query(({ctx:i,input:e})=>i.services.media.getMany(e.ids)),update:h.input(r.object({id:r.string(),data:Te})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:h.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))});class Ii{constructor(e){this.db=e}async list(){return this.db.select().from(S).all()}async findBySlug(e){return this.db.select().from(S).where(a(S.slug,e)).get()}async findById(e){return this.db.select().from(S).where(a(S.id,e)).get()}async findByLegacyId(e){return this.db.select().from(S).where(p`json_extract(${S.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(S).values(e).returning().get()}async update(e,t){return this.db.update(S).set(t).where(a(S.id,e)).returning().get()}async delete(e){return this.db.delete(S).where(a(S.id,e)).returning().get()}}const Dt=i=>i.replace(/œ/g,"oe").replace(/Œ/g,"OE").replace(/æ/g,"ae").replace(/Æ/g,"AE");function _e(i,e=!0){return Dt(i).split(/[\s\-–—'’]+/).map(t=>t.replace(/"/g,"")).filter(Boolean).slice(0,12).map(t=>`"${t}"*`).join(e?" ":" OR ")}const I=ai("entries_fts",{entryId:A("entry_id").notNull(),collectionId:A("collection_id").notNull(),title:A("title").notNull(),body:A("body").notNull(),extra:A("extra").notNull()}),Ie=Qe("entry_words",{entryId:A("entry_id").notNull(),position:Je("position").notNull(),field:A("field").notNull(),extra:Je("extra",{mode:"boolean"}).notNull(),word:A("word").notNull()}).existing(),ie=Qe("entries_search_text",{entryId:A("entry_id").notNull(),collectionId:A("collection_id").notNull(),title:A("title").notNull(),body:A("body").notNull(),extra:A("extra").notNull()}).existing(),F="",se="";class H{constructor(e){this.db=e}reindexEntry(e){this.db.delete(I).where(a(I.entryId,e)).run(),this.db.insert(I).select(this.db.select().from(ie).where(a(ie.entryId,e))).run()}reindexCollection(e){this.db.delete(I).where(a(I.collectionId,e)).run(),this.db.insert(I).select(this.db.select().from(ie).where(a(ie.collectionId,e))).run()}matching(e,t=!0){const s=_e(e,t);if(s)return this.db.select({entryId:I.entryId,rank:p`bm25(${I}, 0, 0, 10, 1, 0.5)`.as("rank")}).from(I).where(p`${I} MATCH ${s}`).as("fts")}marked(e,t){const s=_e(e);return!s||t.length===0?[]:this.db.select({entryId:I.entryId,title:p`highlight(${I}, 2, ${F}, ${se})`,body:p`snippet(${I}, 3, ${F}, ${se}, '…', 12)`,extra:p`snippet(${I}, 4, ${F}, ${se}, '…', 12)`}).from(I).where(D(p`${I} MATCH ${s}`,$(I.entryId,t))).all()}words(e){return e.length===0?[]:this.db.select().from(Ie).where($(Ie.entryId,e)).orderBy(L(Ie.position)).all()}}const Ni="[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*";class Oi{constructor(e){this.db=e,this.fullText=new H(e)}fullText;async list(e){return this.db.select().from(c).where(a(c.collectionId,e)).orderBy(T(c.updatedAt)).all()}narrowing(e){const t=[];if(e.collectionId&&t.push(a(c.collectionId,e.collectionId)),e.status?.length&&t.push($(c.status,e.status)),(e.date?.gte||e.date?.lte)&&t.push(p`exists (select 1 from ${this.spans()} where ${this.within(e.date)})`),e.references?.length){const s=p.join(e.references.map(n=>p`${n}`),p`, `);t.push(p`exists (select 1 from json_tree(${c.data}) where type = 'text' and value in (${s}))`)}return t.length>0?D(...t):void 0}spans(){return p`(select min(value) as span_start, max(value) as span_end from json_tree(${c.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(p`substr(span_end, 1, ${e.gte.length}) >= ${e.gte}`),e.lte&&t.push(p`substr(span_start, 1, ${e.lte.length}) <= ${e.lte}`),t.length>0?D(...t):p`1`}dateKey(e,t){const s=t?p`max(span_start)`:p`min(span_start)`;return p`(select ${s} from ${this.spans()} where ${this.within(e)})`}found(e,t=!0){const s=this.db.select(Zt(c)).from(c).$dynamic(),n=e?this.fullText.matching(e,t):void 0;return n?{query:s.innerJoin(n,a(n.entryId,c.id)),rank:L(n.rank)}:{query:s,rank:void 0}}async search(e){const t=[];e.collectionIds?.length&&t.push($(c.collectionId,e.collectionIds)),e.status?.length&&t.push($(c.status,e.status));const s=o=>{const{query:l,rank:d}=this.found(e.search,o);return l.where(D(...t)).orderBy(...d?[d]:[],T(c.updatedAt)).limit(e.limit).all()},n=s(!0);return n.length===0?s(!1):n}async countMatching(e){const t=e.search?this.fullText.matching(e.search):void 0,s=this.db.select({total:p`count(*)`}).from(c).$dynamic(),[n]=(t?s.innerJoin(t,a(t.entryId,c.id)):s).where(this.narrowing(e)).all();return n?.total??0}async listRecent(e){return this.db.select().from(c).orderBy(T(c.updatedAt)).limit(e).all()}async listPaginated(e){const t=e.order??(e.date?"date_asc":"recent"),s=d=>{const u=this.dateKey(e.date,d);return[p`${u} is null`,d?T(u):L(u)]},n={recent:()=>[T(c.updatedAt)],oldest:()=>[L(c.updatedAt)],title:()=>[L(c.title)],date_asc:()=>s(!1),date_desc:()=>s(!0)},{query:o,rank:l}=this.found(e.search);return o.where(this.narrowing(e)).orderBy(...l&&!e.order?[l]:[],...n[t]()).limit(e.limit).offset(e.skip).all()}async listPublished(e){return this.db.select().from(c).where(D(a(c.collectionId,e),a(c.status,"published"))).orderBy(T(c.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(c).where(D(a(c.collectionId,e),a(c.slug,t))).get()}async findById(e){return this.db.select().from(c).where(a(c.id,e)).get()}async findByIds(e){return e.length?this.db.select().from(c).where($(c.id,e)).all():[]}async findByDataField(e,t,s){return this.db.select().from(c).where(D(a(c.collectionId,e),p`json_extract(${c.data}, ${`$.${t}`}) = ${s}`)).get()}async insert(e){return this.db.insert(c).values(e).returning().get()}async update(e,t){return this.db.update(c).set(t).where(a(c.id,e)).returning().get()}async delete(e){return this.db.delete(c).where(a(c.id,e)).returning().get()}}function Y(i,e,t){let s;return i.transaction(()=>{s=e(),t()}),s}class xt extends Oi{index=new H(this.db);async insert(e){const t=e.id??crypto.randomUUID();return Y(this.db,()=>super.insert({...e,id:t}),()=>this.index.reindexEntry(t))}async update(e,t){return Y(this.db,()=>super.update(e,t),()=>this.index.reindexEntry(e))}async delete(e){return Y(this.db,()=>super.delete(e),()=>this.index.reindexEntry(e))}}class Tt extends Ii{index=new H(this.db);async update(e,t){return t.fields?Y(this.db,()=>super.update(e,t),()=>this.index.reindexCollection(e)):super.update(e,t)}async delete(e){return Y(this.db,()=>super.delete(e),()=>this.index.reindexCollection(e))}}const ne=E(g.COLLECTION_NOT_FOUND,b.NOT_FOUND),re=E(g.ENTRY_NOT_FOUND,b.NOT_FOUND),Ct=E(g.INVALID_ENTRY_DATA,b.BAD_REQUEST),Ne=E(g.DUPLICATE_SLUG,b.BAD_REQUEST);function Rt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}const kt=i=>Dt(i).normalize("NFD").replace(/\p{M}/gu,"").toLowerCase();function Ui(i,e,t){const s=!i.body.includes(F),n=(s?i.extra:i.body).split(F)[1]?.split(se)[0];if(!n)return;const o=kt(n),l=t.find(u=>u.extra===s&&kt(u.word).includes(o))?.field,d=e?.fields.find(u=>u.name===l);return d?d.label||d.name:l}function Si(i,e,t,s){const n=new Map(e.map(l=>[l.id,l])),o=new Map;for(const l of i){const d=n.get(l.entryId);if(!d)continue;const u=t.find(({id:ce})=>ce===d.collectionId),U=s.filter(({entryId:ce})=>ce===d.id),w=Ui(l,u,U),{title:x,body:v,extra:V}=l;o.set(d.id,w?{title:x,body:v,extra:V,field:w}:{title:x,body:v,extra:V})}return o}function oe(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,n){this.definitions=e,this.entries=t,this.media=s,this.fullText=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 ne(`collection not found: ${e}`);return t}async createDefinition(e,t){const s=e.slug||await this.uniqueDefinitionSlug(Rt(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 ne(`collection not found: ${e}`);return n}async removeDefinition(e){if(!await this.definitions.delete(e))throw new ne(`collection not found: ${e}`)}validateData(e,t){const s=Ze(e.fields).safeParse(t);if(!s.success)throw new Ct(`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 re(`entry not found: ${e}`);return t}async getEntries(e){return this.entries.findByIds([...new Set(e)])}async listEntriesPaginated(e,t={}){const s=e?await this.getDefinition(e):void 0,n=await this.entries.listPaginated({...t,collectionId:s?.id,skip:t.skip??0,limit:t.limit??20});if(!t.search)return n;const o=s?[s]:await this.definitions.list(),l=n.map(({id:u})=>u),d=Si(this.fullText.marked(t.search,l),n,o,this.fullText.words(l));return n.map(u=>({...u,found:d.get(u.id)}))}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),l=await this.uniqueEntrySlug(n.id,t.slug||Rt(t.title)),d=await this.entries.insert({...t,slug:l,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,d.id,[],oe(n.fields,o)),d}async updateEntry(e,t,s){const n=await this.entries.findById(e);if(!n)throw new re(`entry not found: ${e}`);const o=await this.getDefinition(n.collectionId),l=new Set(o.fields.map(v=>v.name)),d=Object.fromEntries(Object.entries(n.data??{}).filter(([v])=>!l.has(v))),u=t.data?{...n.data,...t.data}:n.data,U=Object.fromEntries(Object.entries(u).filter(([v])=>l.has(v)||v in(t.data??{}))),w=t.data?{...d,...this.validateData(o,U)}:void 0,x={...t,updatedBy:s??null};w&&(x.data=w),t.status==="published"&&!t.publishedAt&&(x.publishedAt=new Date().toISOString());try{const v=await this.entries.update(e,x);return w&&await this.linkRelations(o,e,oe(o.fields,n.data),oe(o.fields,w)),t.related&&await this.linkRelations(o,e,n.related??[],t.related),v}catch(v){throw this.entrySlugConflict(v,o.slug,t.slug??n.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new re(`entry not found: ${e}`);const s=await this.getDefinition(t.collectionId);await this.linkRelations(s,e,oe(s.fields,t.data),[]),await this.entries.delete(e)}definitionSlugConflict(e,t){return ye(e,"collection_definitions.slug")?new Ne(`le slug "${t}" est d\xE9j\xE0 celui d'une collection`):e}entrySlugConflict(e,t,s){return ye(e,"entries.slug")?new Ne(`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(d=>!s.includes(d)),l=s.filter(d=>!n.includes(d));for(const d of o){const u=await this.entries.findById(d);if(!u)continue;const U=new Set(u.related??[]);U.add(t),await this.entries.update(d,{related:[...U]})}for(const d of l){const u=await this.entries.findById(d);u&&await this.entries.update(d,{related:(u.related??[]).filter(U=>U!==t)})}}}const Oe=r.string().describe("Id or slug of the collection"),Bt=r.array(r.enum(Xe)).optional().describe("Keep only entries in these publication statuses"),Pt=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"),jt={collectionId:Oe.optional().describe("Id or slug of the collection; every collection of the site when omitted"),status:Bt,search:r.string().max(200).optional().describe("Keep only entries whose title or field values contain this text"),date:r.object({gte:Pt.optional().describe("From this date, included"),lte:Pt.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)")},Lt=M({list:h.query(({ctx:i})=>i.services.collections.listDefinitions()),get:h.input(r.object({idOrSlug:Oe})).output(qe).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:_.input(Le).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:_.input(r.object({id:r.string(),data:je})).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:M({get:h.input(r.object({id:r.string().describe("Id of the entry")})).output(Q).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),getMany:h.input(r.object({ids:r.array(r.string()).min(1).max(100).describe("Ids of the entries, 100 at most")})).output(r.array(Q)).query(({ctx:i,input:e})=>i.services.collections.getEntries(e.ids)),search:h.input(r.object({query:r.string().trim().min(1).max(200).describe("Text to look for"),collections:r.array(Oe).optional().describe("Search only these collections (ids or slugs); all of them when omitted"),status:Bt,limit:r.number().int().min(1).max(50).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(Pe)).query(({ctx:i,input:e})=>i.services.collections.searchEntries(e)),list:h.input(r.object({...jt,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(Be)).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),recent:h.input(r.object({limit:r.number().int().min(1).max(20).optional()}).optional()).output(r.array(Q)).query(({ctx:i,input:e})=>i.services.collections.listRecentEntries(e?.limit)),count:h.input(r.object(jt)).query(({ctx:i,input:e})=>i.services.collections.countEntries(e.collectionId,e)),create:h.input(r.object({collectionId:r.string(),data:$e})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:h.input(r.object({id:r.string(),data:ke})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:h.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})}),W=E(g.AUDIENCE_UNAVAILABLE,b.NOT_FOUND),Ai=6e4,qt=10*6e4,Mi=8e3,Di=5,xi=90;class Kt{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;sitePages;viewers;visibleTo(e){return this.config.url?!this.viewers.length||this.viewers.includes(e.trim().toLowerCase()):!1}async summary(e,t){if(!this.config.url)throw new W("no audience source");if(!this.visibleTo(t))throw new W("not among the viewers");const s=`${e.period}:${e.collection??""}:${e.entry??""}`,n=this.cache.get(s);if(n&&Date.now()-n.at<Ai)return n.value;const o=e.entry?await this.entrySlug(e.entry):void 0;if(e.entry&&!o)throw new W(`unknown entry ${e.entry}`);const l=e.collection?await this.siteSegment(e.collection):void 0,d=await this.ask(this.config.url,new URLSearchParams({period:String(e.period),...l?{collection:l}:{},...o?{entry:o}:{}}));if(!d)throw new W("the source did not answer");const u=await this.knownNames(),U={...d,top:(d.top??[]).slice(0,Di).map(w=>{const x=w.path.split("/").filter(Boolean),v=u.entries.get(x.at(-1)??""),V=!v&&x.length===1&&w.collection?u.collections.get(w.collection):void 0;return{path:w.path,collection:w.collection??null,visits:w.views,title:w.path==="/"?"Accueil":v?.title??V??w.path,entryId:v?.id??null}})};return this.cache.set(s,{at:Date.now(),value:U}),U}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(Mi)});if(!n.ok)return q.warn(`[audience] the source answered ${n.status} to ${t}`),null;const o=Ke.safeParse(await n.json());return o.success?o.data:(q.warn(`[audience] the source's answer to ${t} does not parse`,o.error.issues),null)}catch(n){return q.warn(`[audience] the source did not answer ${t}: ${String(n)}`),null}}async siteSegment(e){const t=await this.mostReadPaths();if(!t.length)return e;let s;try{s=new Set((await this.collections.listPublishedEntries(e)).map(n=>n.slug))}catch{return e}for(const n of t){const o=n.split("/").filter(Boolean),l=o.at(-1);if(o.length>=2&&l&&s.has(l))return o.at(-2)}return e}async mostReadPaths(){if(this.sitePages&&Date.now()-this.sitePages.at<qt)return this.sitePages.paths;if(!this.config.url)return[];const e=await this.ask(this.config.url,new URLSearchParams({period:String(xi)}));if(!e)return[];const t=(e.top??[]).map(s=>s.path);return this.sitePages={at:Date.now(),paths:t},t}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<qt)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 zt=M({summary:h.input(ze).query(({ctx:i,input:e})=>i.services.audience.summary(e,i.session.user.email))});function Ti({env:i}={}){const e=i??et(),t=tt(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),s=rt(e),n=ae.fromEnv(e),o=new yt(new ct(t),{email:n,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),l=new Ot(t),d=new At(l,s),u=new $t(new Tt(t),new xt(t),d,new H(t)),U=new It(new Et(t)),w=new Kt(u,{url:e.OPEN_COMMUNE_AUDIENCE_URL,token:e.OPEN_COMMUNE_AUDIENCE_TOKEN,viewers:e.OPEN_COMMUNE_AUDIENCE_VIEWERS}),x={health:new it(t),users:o,organization:U,media:d,collections:u,audience:w};return{env:e,db:t,storage:s,services:x}}const Ci=M({health:pi,auth:mt,users:wt,invitations:gt,apiTokens:ft,organization:Nt,media:Mt,collections:Lt,audience:zt});export{ve as ALLOWED_MIME,Kt as AudienceService,W as AudienceUnavailableError,dt as CannotRemoveSelfError,ne as CollectionNotFoundError,$t as CollectionsService,Tt as DefinitionRepository,ge as DeployFailedError,_t as DeployHookMissingError,X as DomainError,Ne as DuplicateSlugError,g as ERROR_TYPES,ae as EmailService,re as EntryNotFoundError,xt as EntryRepository,it as HealthService,Ct as InvalidEntryDataError,fe as InvitationInvalidError,te as MediaNotFoundError,Ot as MediaRepository,At as MediaService,bt as OrganizationAlreadyInitializedError,vt as OrganizationNotInitializedError,Et as OrganizationRepository,It as OrganizationService,Xe as PUBLICATION_STATUSES,nt as S3Storage,H as SearchRepository,lt as SessionNotFoundError,ut as TooManyAttemptsError,Ee as UnsupportedMimeError,Ut as UploadIncompleteError,we as UserNotFoundError,ct as UsersRepository,yt as UsersService,de as acceptInvitationDto,_ as adminProcedure,Me as apiTokenCreateDto,N as apiTokens,ft as apiTokensRouter,Ci as appRouter,ze as audienceAskDto,zt as audienceRouter,Ke as audienceSummarySchema,mt as authRouter,Ze as buildDataSchema,S as collectionDefinitions,Lt as collectionsRouter,tt as connectDb,Ti as createCore,rt as createStorage,E as createTypedError,Le as definitionCreateDto,qe as definitionDto,je as definitionUpdateDto,c as entries,$e as entryCreateDto,Q as entryDto,Be as entryListedDto,Pe as entrySearchHitDto,ke as entryUpdateDto,f as invitations,gt as invitationsRouter,he as inviteDto,ye as isUniqueViolation,Ue as loginDto,O as media,Ce as mediaFinalizeDto,Re as mediaRequestUploadDto,Mt as mediaRouter,Te as mediaUpdateDto,ui as mergeRouters,me as middleware,B as organization,xe as organizationInitDto,Nt as organizationRouter,De as organizationUpdateDto,et as parseEnv,R as procedure,h as protectedProcedure,ot as publicProcedure,le as requestPasswordResetDto,M as router,m as sessions,_e as toMatchQuery,k as toPublicUser,ue as toSessionUser,Se as updateOwnProfileDto,Ae as userUpdateDto,y as users,wt 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>;
|
|
@@ -655,6 +655,37 @@ declare const entryDto: drizzle_zod.BuildSchema<"select", {
|
|
|
655
655
|
published: "published";
|
|
656
656
|
}>;
|
|
657
657
|
}, undefined>;
|
|
658
|
+
/** A listed entry: under a search, where the search found it. */
|
|
659
|
+
declare const entryListedDto: z.ZodObject<{
|
|
660
|
+
id: z.ZodString;
|
|
661
|
+
collectionId: z.ZodString;
|
|
662
|
+
title: z.ZodString;
|
|
663
|
+
slug: z.ZodString;
|
|
664
|
+
data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
665
|
+
related: z.ZodNullable<z.ZodArray<z.ZodString>>;
|
|
666
|
+
createdBy: z.ZodNullable<z.ZodString>;
|
|
667
|
+
updatedBy: z.ZodNullable<z.ZodString>;
|
|
668
|
+
status: z.ZodEnum<{
|
|
669
|
+
draft: "draft";
|
|
670
|
+
waiting: "waiting";
|
|
671
|
+
ready: "ready";
|
|
672
|
+
scheduled: "scheduled";
|
|
673
|
+
published: "published";
|
|
674
|
+
}>;
|
|
675
|
+
publishedAt: z.ZodNullable<z.ZodString>;
|
|
676
|
+
legacyExtra: z.ZodNullable<z.ZodType<drizzle_zod.Json, unknown, z.core.$ZodTypeInternals<drizzle_zod.Json, unknown>>>;
|
|
677
|
+
createdAt: z.ZodString;
|
|
678
|
+
updatedAt: z.ZodString;
|
|
679
|
+
found: z.ZodOptional<z.ZodObject<{
|
|
680
|
+
title: z.ZodString;
|
|
681
|
+
body: z.ZodString;
|
|
682
|
+
extra: z.ZodString;
|
|
683
|
+
field: z.ZodOptional<z.ZodString>;
|
|
684
|
+
}, z.core.$strip>>;
|
|
685
|
+
}, {
|
|
686
|
+
out: {};
|
|
687
|
+
in: {};
|
|
688
|
+
}>;
|
|
658
689
|
/** A search hit: the entry, and which collection it comes from. */
|
|
659
690
|
declare const entrySearchHitDto: z.ZodObject<{
|
|
660
691
|
id: z.ZodString;
|
|
@@ -1945,7 +1976,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
|
|
|
1945
1976
|
data: {
|
|
1946
1977
|
name: string;
|
|
1947
1978
|
label: string;
|
|
1948
|
-
type: "number" | "boolean" | "
|
|
1979
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
1949
1980
|
required: boolean;
|
|
1950
1981
|
hidden: boolean;
|
|
1951
1982
|
options?: string[] | undefined;
|
|
@@ -1965,7 +1996,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
|
|
|
1965
1996
|
$type: {
|
|
1966
1997
|
name: string;
|
|
1967
1998
|
label: string;
|
|
1968
|
-
type: "number" | "boolean" | "
|
|
1999
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
1969
2000
|
required: boolean;
|
|
1970
2001
|
hidden: boolean;
|
|
1971
2002
|
options?: string[] | undefined;
|
|
@@ -2600,5 +2631,5 @@ type ErrorType = (typeof ERROR_TYPES)[keyof typeof ERROR_TYPES];
|
|
|
2600
2631
|
/** Narrows what a response carried to a type of the catalogue. */
|
|
2601
2632
|
declare const isErrorType: (value: unknown) => value is ErrorType;
|
|
2602
2633
|
|
|
2603
|
-
export { entryCreateDto as $, acceptInvitationDto as G, addressSchema as H, apiTokenCreateDto as J, apiTokens as K, audienceAskDto as Q, audienceQuerySchema as T, audienceSummarySchema as V, collectionDefinitions as W, definitionCreateDto as X, definitionDto as Y, definitionUpdateDto as Z, entries as _, entryDto as a0,
|
|
2634
|
+
export { entryCreateDto as $, acceptInvitationDto as G, addressSchema as H, apiTokenCreateDto as J, apiTokens as K, audienceAskDto as Q, audienceQuerySchema as T, audienceSummarySchema as V, collectionDefinitions as W, definitionCreateDto as X, definitionDto as Y, definitionUpdateDto as Z, entries as _, entryDto as a0, entryListedDto as a1, entrySearchHitDto as a2, entryUpdateDto as a3, invitations as a4, inviteDto as a5, isErrorType as a6, loginDto as a7, media as a8, mediaFinalizeDto as a9, mediaRequestUploadDto as aa, mediaUpdateDto as ab, organization as ac, organizationInitDto as ad, organizationUpdateDto as ae, requestPasswordResetDto as af, sessions as ag, toPublicUser as ah, toSessionUser as ai, updateOwnProfileDto as aj, userUpdateDto as ak, users as al, AUDIENCE_PERIODS as o, schema as s, ERROR_TYPES as v };
|
|
2604
2635
|
export type { ApiToken as A, UpdateOwnProfileDto as B, CollectionDefinition as C, DefinitionCreateDto as D, Entry as E, UserUpdateDto as F, 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, SessionUser 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>;
|
|
@@ -655,6 +655,37 @@ declare const entryDto: drizzle_zod.BuildSchema<"select", {
|
|
|
655
655
|
published: "published";
|
|
656
656
|
}>;
|
|
657
657
|
}, undefined>;
|
|
658
|
+
/** A listed entry: under a search, where the search found it. */
|
|
659
|
+
declare const entryListedDto: z.ZodObject<{
|
|
660
|
+
id: z.ZodString;
|
|
661
|
+
collectionId: z.ZodString;
|
|
662
|
+
title: z.ZodString;
|
|
663
|
+
slug: z.ZodString;
|
|
664
|
+
data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
665
|
+
related: z.ZodNullable<z.ZodArray<z.ZodString>>;
|
|
666
|
+
createdBy: z.ZodNullable<z.ZodString>;
|
|
667
|
+
updatedBy: z.ZodNullable<z.ZodString>;
|
|
668
|
+
status: z.ZodEnum<{
|
|
669
|
+
draft: "draft";
|
|
670
|
+
waiting: "waiting";
|
|
671
|
+
ready: "ready";
|
|
672
|
+
scheduled: "scheduled";
|
|
673
|
+
published: "published";
|
|
674
|
+
}>;
|
|
675
|
+
publishedAt: z.ZodNullable<z.ZodString>;
|
|
676
|
+
legacyExtra: z.ZodNullable<z.ZodType<drizzle_zod.Json, unknown, z.core.$ZodTypeInternals<drizzle_zod.Json, unknown>>>;
|
|
677
|
+
createdAt: z.ZodString;
|
|
678
|
+
updatedAt: z.ZodString;
|
|
679
|
+
found: z.ZodOptional<z.ZodObject<{
|
|
680
|
+
title: z.ZodString;
|
|
681
|
+
body: z.ZodString;
|
|
682
|
+
extra: z.ZodString;
|
|
683
|
+
field: z.ZodOptional<z.ZodString>;
|
|
684
|
+
}, z.core.$strip>>;
|
|
685
|
+
}, {
|
|
686
|
+
out: {};
|
|
687
|
+
in: {};
|
|
688
|
+
}>;
|
|
658
689
|
/** A search hit: the entry, and which collection it comes from. */
|
|
659
690
|
declare const entrySearchHitDto: z.ZodObject<{
|
|
660
691
|
id: z.ZodString;
|
|
@@ -1945,7 +1976,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
|
|
|
1945
1976
|
data: {
|
|
1946
1977
|
name: string;
|
|
1947
1978
|
label: string;
|
|
1948
|
-
type: "number" | "boolean" | "
|
|
1979
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
1949
1980
|
required: boolean;
|
|
1950
1981
|
hidden: boolean;
|
|
1951
1982
|
options?: string[] | undefined;
|
|
@@ -1965,7 +1996,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
|
|
|
1965
1996
|
$type: {
|
|
1966
1997
|
name: string;
|
|
1967
1998
|
label: string;
|
|
1968
|
-
type: "number" | "boolean" | "
|
|
1999
|
+
type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
|
|
1969
2000
|
required: boolean;
|
|
1970
2001
|
hidden: boolean;
|
|
1971
2002
|
options?: string[] | undefined;
|
|
@@ -2600,5 +2631,5 @@ type ErrorType = (typeof ERROR_TYPES)[keyof typeof ERROR_TYPES];
|
|
|
2600
2631
|
/** Narrows what a response carried to a type of the catalogue. */
|
|
2601
2632
|
declare const isErrorType: (value: unknown) => value is ErrorType;
|
|
2602
2633
|
|
|
2603
|
-
export { entryCreateDto as $, acceptInvitationDto as G, addressSchema as H, apiTokenCreateDto as J, apiTokens as K, audienceAskDto as Q, audienceQuerySchema as T, audienceSummarySchema as V, collectionDefinitions as W, definitionCreateDto as X, definitionDto as Y, definitionUpdateDto as Z, entries as _, entryDto as a0,
|
|
2634
|
+
export { entryCreateDto as $, acceptInvitationDto as G, addressSchema as H, apiTokenCreateDto as J, apiTokens as K, audienceAskDto as Q, audienceQuerySchema as T, audienceSummarySchema as V, collectionDefinitions as W, definitionCreateDto as X, definitionDto as Y, definitionUpdateDto as Z, entries as _, entryDto as a0, entryListedDto as a1, entrySearchHitDto as a2, entryUpdateDto as a3, invitations as a4, inviteDto as a5, isErrorType as a6, loginDto as a7, media as a8, mediaFinalizeDto as a9, mediaRequestUploadDto as aa, mediaUpdateDto as ab, organization as ac, organizationInitDto as ad, organizationUpdateDto as ae, requestPasswordResetDto as af, sessions as ag, toPublicUser as ah, toSessionUser as ai, updateOwnProfileDto as aj, userUpdateDto as ak, users as al, AUDIENCE_PERIODS as o, schema as s, ERROR_TYPES as v };
|
|
2604
2635
|
export type { ApiToken as A, UpdateOwnProfileDto as B, CollectionDefinition as C, DefinitionCreateDto as D, Entry as E, UserUpdateDto as F, 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, SessionUser as z };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createInsertSchema as y,createUpdateSchema as c,createSelectSchema as D}from"drizzle-zod";import{z as e}from"zod";import{fieldDefinitionSchema as g,fieldReadSchema as C}from"../domains/collections/utils.mjs";import{sqliteTable as o,text as t,integer as I,uniqueIndex as F}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as A,FIELD_TYPES as z}from"../domains/collections/constants.mjs";const S={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},B={createdBy:!0,updatedBy:!0},h={...S,...B},r=()=>t("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),i=()=>t("created_at").notNull().$defaultFn(()=>new Date().toISOString()),d=()=>t("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),u=()=>t("legacy_extra",{mode:"json"}).$type(),M=()=>t("status",{enum:A}).notNull().default("draft"),q=()=>t("published_at"),E=e.object({street:e.string().optional(),postalCode:e.string().optional(),city:e.string().optional()}),m=o("organization",{id:I("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:i(),updatedAt:d()}),f=o("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:i(),updatedAt:d()}),T=o("sessions",{id:r(),userId:t("user_id").notNull().references(()=>f.id,{onDelete:"cascade"}),expiresAt:t("expires_at").notNull(),revokedAt:t("revoked_at"),ua:t("ua"),ip:t("ip"),createdAt:i()}),O=o("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:i()}),j=o("api_tokens",{id:r(),name:t("name").notNull(),tokenHash:t("token_hash").notNull().unique(),lastUsedAt:t("last_used_at"),revokedAt:t("revoked_at"),createdAt:i()}),_=o("media",{id:r(),filename:t("filename").notNull(),mime:t("mime").notNull(),size:I("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:i(),updatedAt:d()}),s=o("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:i(),updatedAt:d()}),l=o("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:M(),publishedAt:q(),legacyExtra:u(),createdAt:i(),updatedAt:d()},n=>[F("entries_slug_unique").on(n.collectionId,n.slug)]),Y={__proto__:null,FIELD_TYPES:z,PUBLICATION_STATUSES:A,addressSchema:E,apiTokens:j,collectionDefinitions:s,entries:l,fieldDefinitionSchema:g,invitations:O,media:_,organization:m,sessions:T,users:f},V=y(s).omit(h).extend({fields:e.array(g).min(1),slug:e.string().optional()}),H=c(s).omit(h).extend({fields:e.array(g).min(1).optional()}),G=D(s,{fields:e.array(C).describe("The fields every entry of the collection is made of")}),U={...h,related:!0,collectionId:!0},K=y(l).omit(U).extend({slug:e.string().optional()}),Z=c(l).omit(U).extend({related:e.array(e.string()).optional()}),N=D(l,{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")}),W=N.extend({found:e.object({title:e.string().describe("The title as indexed, each word found between \\u0002 and \\u0003"),body:e.string().describe("A passage of what a reader may search, marked the same way"),extra:e.string().describe("A passage of what only the admin searches, marked the same way"),field:e.string().optional().describe("Label of the field holding the first word found outside the title")}).optional().describe("Where a search found the entry; absent when nothing was searched")}),J=N.extend({collectionSlug:e.string().describe("Slug of the collection the entry belongs to")}),Q=e.object({filename:e.string().min(1),mime:e.string().min(1),metaData:e.record(e.string(),e.string()).optional()}),X=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()}),ee=c(_).pick({alt:!0,caption:!0,filename:!0}),v={...S,updatedBy:!0},w={name:n=>n.trim().min(1)},te=y(m,w).omit(v),ne=c(m,w).omit(v),ae=e.object({email:e.email(),password:e.string().min(1)}),oe=e.object({token:e.string().min(1),name:e.string().min(1).optional(),password:e.string().min(10)}),ie=e.object({email:e.email()}),re=e.object({email:e.email(),role:e.enum(["admin","redacteur"])}),se=e.object({id:e.string(),data:e.object({name:e.string().min(1).optional(),role:e.enum(["admin","redacteur"]).optional(),email:e.email().optional()})}),de=e.strictObject({name:e.string().trim().min(1).max(120)}),L=({id:n,email:p,name:P,role:R})=>({id:n,email:p,name:P,role:R}),le=(n,p)=>({...L(n),audience:p.audience}),ce=e.object({name:e.string().min(1)}),k=[7,30,90],x=e.object({period:e.coerce.number().pipe(e.union(k.map(n=>e.literal(n)))),collection:e.string().min(1).optional(),entry:e.string().min(1).optional()}),b=e.object({name:e.string(),share:e.number()}),a=e.number().nonnegative(),ue=e.object({period:e.object({from:e.string(),to:e.string(),days:e.number()}),visits:a,visitsPrevious:a.nullish(),visitors:a.nullish(),readingMs:a.nullish(),viewsPerVisit:a.nullish(),rightNow:a.nullish(),daily:e.array(e.object({day:e.string(),visits:a})),top:e.array(e.object({path:e.string(),collection:e.string().nullish(),views:a})).optional(),sources:e.array(b).optional(),devices:e.array(b).optional(),places:e.array(b).optional(),campaigns:e.array(e.object({name:e.string(),visits:a})).optional(),depth:e.object({reached25:a,reached50:a,reachedEnd:a}).nullish()}),me=e.object({period:x.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"},pe=new Set(Object.values($)),ye=n=>typeof n=="string"&&pe.has(n);export{k as A,Y as B,f as C,T as D,$ as E,O as F,j as G,m as H,_ as I,s as J,l as K,E as L,oe as a,ce as b,me as c,x as d,ue as e,V as f,G as g,H as h,K as i,N as j,W as k,J as l,Z as m,re as n,ye as o,ae as p,X as q,Q as r,ee as s,te as t,ne as u,ie as v,L as w,le as x,de as y,se as z};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
-- Full-text index of the entries, every status: SQLite's own FTS5, whose
|
|
2
|
+
-- tokenizer ignores case and accents and cuts on hyphens. A base that ran an
|
|
3
|
+
-- earlier, unmerged version of it holds a table of another shape: dropped,
|
|
4
|
+
-- since it is filled again below.
|
|
5
|
+
DROP TABLE IF EXISTS `entries_fts`;
|
|
6
|
+
--> statement-breakpoint
|
|
7
|
+
CREATE VIRTUAL TABLE `entries_fts` USING fts5(
|
|
8
|
+
`entry_id` UNINDEXED,
|
|
9
|
+
`collection_id` UNINDEXED,
|
|
10
|
+
`title`,
|
|
11
|
+
`body`,
|
|
12
|
+
`extra`,
|
|
13
|
+
tokenize = 'unicode61 remove_diacritics 2'
|
|
14
|
+
);
|
|
15
|
+
--> statement-breakpoint
|
|
16
|
+
-- Every string of every entry that holds words, with the field it comes
|
|
17
|
+
-- from: a rich text gives its text nodes, not its structure (`type`, `href`…).
|
|
18
|
+
CREATE VIEW `entry_words` AS
|
|
19
|
+
SELECT
|
|
20
|
+
`entry`.`id` AS `entry_id`,
|
|
21
|
+
`field`.`key` AS `position`,
|
|
22
|
+
json_extract(`field`.`value`, '$.name') AS `field`,
|
|
23
|
+
(coalesce(json_extract(`field`.`value`, '$.hidden'), 0) OR json_extract(`field`.`value`, '$.type') = 'json') AS `extra`,
|
|
24
|
+
`node`.`value` AS `word`
|
|
25
|
+
FROM `entries` AS `entry`
|
|
26
|
+
JOIN `collection_definitions` AS `definition` ON `definition`.`id` = `entry`.`collection_id`
|
|
27
|
+
JOIN json_each(`definition`.`fields`) AS `field`
|
|
28
|
+
JOIN json_tree(`entry`.`data`, '$."' || json_extract(`field`.`value`, '$.name') || '"') AS `node`
|
|
29
|
+
WHERE `node`.`type` = 'text' AND CASE json_extract(`field`.`value`, '$.type')
|
|
30
|
+
WHEN 'text' THEN `node`.`parent` IS NULL
|
|
31
|
+
WHEN 'select' THEN `node`.`parent` IS NULL
|
|
32
|
+
WHEN 'rich-text' THEN `node`.`key` = 'text'
|
|
33
|
+
WHEN 'steps' THEN `node`.`key` = 'text' OR (`node`.`key` = 'title' AND `node`.`fullkey` GLOB '*[[][0-9]*[]].title')
|
|
34
|
+
WHEN 'json' THEN 1
|
|
35
|
+
ELSE 0
|
|
36
|
+
END;
|
|
37
|
+
--> statement-breakpoint
|
|
38
|
+
-- What each entry gives the index, read from its fields as its collection
|
|
39
|
+
-- defines them: the text of a text or a select, the text nodes of a rich text
|
|
40
|
+
-- (ProseMirror), the titles and text of steps, every string of a JSON field.
|
|
41
|
+
-- A hidden field or a JSON one goes to `extra`, which only the admin searches.
|
|
42
|
+
-- The ligatures are written out, which the tokenizer does not do: « vœux »
|
|
43
|
+
-- must be found by « voeux ». The index is filled from here, and kept from
|
|
44
|
+
-- here by the repositories (`search/indexed.ts`).
|
|
45
|
+
CREATE VIEW `entries_search_text` AS
|
|
46
|
+
SELECT
|
|
47
|
+
`entry_id`,
|
|
48
|
+
`collection_id`,
|
|
49
|
+
replace(replace(replace(replace(`title`, 'œ', 'oe'), 'Œ', 'OE'), 'æ', 'ae'), 'Æ', 'AE') AS `title`,
|
|
50
|
+
replace(replace(replace(replace(coalesce(`body`, ''), 'œ', 'oe'), 'Œ', 'OE'), 'æ', 'ae'), 'Æ', 'AE') AS `body`,
|
|
51
|
+
replace(replace(replace(replace(coalesce(`extra`, ''), 'œ', 'oe'), 'Œ', 'OE'), 'æ', 'ae'), 'Æ', 'AE') AS `extra`
|
|
52
|
+
FROM (
|
|
53
|
+
SELECT
|
|
54
|
+
`entry`.`id` AS `entry_id`,
|
|
55
|
+
`entry`.`collection_id` AS `collection_id`,
|
|
56
|
+
`entry`.`title` AS `title`,
|
|
57
|
+
(SELECT group_concat(`word`, ' ') FROM `entry_words` WHERE `entry_words`.`entry_id` = `entry`.`id` AND NOT `entry_words`.`extra`) AS `body`,
|
|
58
|
+
(SELECT group_concat(`word`, ' ') FROM `entry_words` WHERE `entry_words`.`entry_id` = `entry`.`id` AND `entry_words`.`extra`) AS `extra`
|
|
59
|
+
FROM `entries` AS `entry`
|
|
60
|
+
);
|
|
61
|
+
--> statement-breakpoint
|
|
62
|
+
INSERT INTO `entries_fts` (`entry_id`, `collection_id`, `title`, `body`, `extra`)
|
|
63
|
+
SELECT `entry_id`, `collection_id`, `title`, `body`, `extra` FROM `entries_search_text`;
|