@communecter/cocolight-api-client 1.0.118 → 1.0.120

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.
@@ -1,2 +1,2 @@
1
- import e from"bson-objectid";import*as t from"file-type";import*as n from"ajv";import*as r from"ajv-formats";import*as o from"ejson";import*as i from"pino";import{EventEmitter as s}from"events";import{AggregateAjvError as a}from"@segment/ajv-human-errors";import c from"axios";import p from"axios-retry";import{jwtDecode as d}from"jwt-decode";import*as m from"fs";import*as l from"os";import*as u from"path";class ApiError extends Error{name="ApiError";status;details;constructor(e,t,n){super(e),this.status=t,this.details=n}}class ApiClientError extends ApiError{name="ApiClientError";constructor(e,t,n){super(e,t,n)}}class ApiValidationError extends Error{name="ApiValidationError";status;messages;details;constructor(e,t,n,r=null){super(e),this.status=t,this.messages=n,this.details=r}}class CircuitBreakerError extends ApiError{name="CircuitBreakerError";constructor(e){super(e,503)}}class ApiResponseError extends Error{name="ApiResponseError";status;responseData;details;constructor(e,t,n,r=null){super(e),this.status=t,this.responseData=n,this.details=r}}class ApiAuthenticationError extends ApiError{name="ApiAuthenticationError";constructor(e,t,n){super(e,t,n)}}var h=Object.freeze({__proto__:null,ApiAuthenticationError:ApiAuthenticationError,ApiClientError:ApiClientError,ApiError:ApiError,ApiResponseError:ApiResponseError,ApiValidationError:ApiValidationError,CircuitBreakerError:CircuitBreakerError});const y=new Map;function f(e,t){y.set(e,t)}function g(e,t=null){if(!(n=e)||"object"!=typeof n||!("__entityTag"in n))return e;var n;let r=t;const o=e;if(o.parent&&"object"==typeof o.parent){const e=o.parent,n=e.serverData?.id||e.id;if(t&&"id"in t&&t.id===n)r=t;else{const e=g(o.parent,t);e&&"object"==typeof e&&"id"in e&&(r=e)}}let i=e.serverData?.collection;if(i||(i={User:"citoyens",Organization:"organizations",Project:"projects",Event:"events",Poi:"poi",News:"news",Badge:"badges",Comment:"comments",Answer:"answers"}[e.__entityTag]||null),!i)return e;const s=function(e,t){const n=y.get(t),r=t,o={EndpointApi:y.get("EndpointApi"),User:"User"===r?n:y.get("User"),Organization:"Organization"===r?n:y.get("Organization"),Project:"Project"===r?n:y.get("Project"),Event:"Event"===r?n:y.get("Event"),Poi:"Poi"===r?n:y.get("Poi"),Badge:"Badge"===r?n:y.get("Badge"),News:"News"===r?n:y.get("News"),Comment:"Comment"===r?n:y.get("Comment"),Answer:"Answer"===r?n:y.get("Answer")};return{citoyens:{entityClass:o.User,deps:o},organizations:{entityClass:o.Organization,deps:o},projects:{entityClass:o.Project,deps:o},events:{entityClass:o.Event,deps:{...o,Badge:void 0}},poi:{entityClass:o.Poi,deps:{...o,Badge:void 0,News:void 0,Comment:void 0}},news:{entityClass:o.News,deps:{...o}},badges:{entityClass:o.Badge,deps:{EndpointApi:o.EndpointApi,User:o.User,Organization:o.Organization,Project:o.Project}},comments:{entityClass:o.Comment,deps:{...o}},answers:{entityClass:o.Answer,deps:{...o}}}[e]||null}(i,e.__entityTag);if(!s)return e;if(!s.entityClass?.fromJSON)throw new Error(`Classe inconnue ou fromJSON manquant pour ${e.__entityTag}`);return s.entityClass.fromJSON(e,r,s.deps)}function w(e,t=null,n={}){const r={citoyens:{entityTag:"User",meta:e=>_(e,{remove:[]})},organizations:{entityTag:"Organization",meta:e=>_(e,{remove:[]})},projects:{entityTag:"Project",meta:e=>_(e,{remove:[]})},events:{entityTag:"Event",meta:e=>_(e,{remove:["Badge"]})},poi:{entityTag:"Poi",meta:e=>_(e,{remove:["Badge","News","Comments"]})},news:{entityTag:"News",meta:e=>_(e,{remove:[]})},badges:{entityTag:"Badge",meta:()=>function(e){const t=y.get(e),n={EndpointApi:y.get("EndpointApi"),User:y.get("User"),Organization:y.get("Organization"),Project:y.get("Project")};return n[e]=t,{entityClass:t,deps:n}}("Badge")},comments:{entityTag:"Comment",meta:e=>_(e,{remove:[]})},answers:{entityTag:"Answer",meta:e=>_(e,{remove:[]})}},o=r[e];if(!o)return console.warn(`Collection inconnue : '${e}'`),null;const{entityTag:i,meta:s}=o,{entityClass:a,deps:c}=s(i);if(!a)throw new Error(`EntityClass introuvable pour ${i}`);return new a(t,n,c)}function _(e,t){const n=y.get(e),r={EndpointApi:y.get("EndpointApi"),User:y.get("User"),Organization:y.get("Organization"),Project:y.get("Project"),Event:y.get("Event"),Poi:y.get("Poi"),Badge:y.get("Badge"),News:y.get("News"),Comment:y.get("Comment"),Answer:y.get("Answer")};return r[e]=n,t.remove.forEach((e=>delete r[e])),{entityClass:n,deps:r}}const E=e=>e&&e.default?e.default:e,T=E(n),A=E(r),b=E(i),v=E(o),S=[],P=new WeakMap,I=new WeakMap;let O=0;const C=new Set;function j(e){const t=()=>{try{S.push(t),e()}finally{S.pop()}};return t(),t}function k(e){O++;try{e()}finally{if(O--,0===O){const e=Array.from(C);C.clear();for(const t of e)t()}}}function D(e){let t=e;const n=new Set;return{get value(){const e=S[S.length-1];return e&&n.add(e),t},set value(e){t!==e&&(t=e,O>0?n.forEach((e=>C.add(e))):n.forEach((e=>e())))},subscribe:e=>(n.add(e),()=>n.delete(e)),__isSignal:!0}}function x(e){return e&&!0===e.__isSignal}function L(e,t=[]){if("object"!=typeof e||null===e)return e;if(Array.isArray(e))return function(e,t){return new Proxy(e,{get(e,n,r){if("string"==typeof n&&!isNaN(+n)){const r=e[+n];return M(r)?r:L(r,[...t,n])}return Reflect.get(e,n,r)},set(e,n,r){if("string"==typeof n&&!isNaN(+n)){const o=L(r,[...t,n]);e[+n]=o}return!0}})}(e,t);if(e.__isReactive)return e;if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return e;if("undefined"!=typeof File&&e instanceof File)return e;if("undefined"!=typeof Blob&&e instanceof Blob)return e;if(e&&"function"==typeof e.pipe&&"function"==typeof e.on)return e;if(e instanceof Date)return e;if(e.__entityTag)return e;const n=new Map,r=new Proxy(e,{get(e,r){if("__raw"===r)return e;if("__isReactive"===r)return!0;if(!n.has(r)){const o=D(L(e[r],[...t,String(r)]));n.set(r,o)}return n.get(r).value},set(e,r,o){const i=L(o,[...t,String(r)]);if(!n.has(r)){const e=D(i);n.set(r,e)}return n.get(r).value=i,e[r]=function(e){return x(e)?e.value:e}(i),!0},deleteProperty:(e,t)=>(n.delete(t),Reflect.deleteProperty(e,t))});return I.set(r,n),r}function N(e){return"object"!=typeof e||null===e||e.__isReactive?e:L(e)}function M(e){return null!==e&&"object"==typeof e&&!0===e.__isReactive}function B(e){if(P.has(e))return P.get(e);const t=D();return j((()=>t.value=e())),P.set(e,t),t}function $(e,t){let n;j((()=>{const r=e();r!==n&&(t(r,n),n=r)}))}function z(e){return M(e)?I.get(e):null}function R(e,t,n){const r=z(e);if(!r||!r.has(t))return()=>{};const o=r.get(t);return o?.subscribe?.((()=>n(o.value)))??(()=>{})}var q=Object.freeze({__proto__:null,batch:k,computed:B,effect:j,getSignals:z,isReactive:M,isSignal:x,reactive:N,subscribeTo:R,watch:$});const{fromBuffer:U}=t,F=e;class BaseEntity{__entityTag;deps;apiClient;parent;userContext;endpointApi;data;meta;_draftData={};_initialDraftData={};_serverData=N({});_calledFromSave=!1;_syncReactiveDraft=!1;_isDeleted=!1;_add;_update;_allowedFieldsCache;_allowedFieldsMetadata;static entityTag="BaseEntity";static entityType;static SCHEMA_CONSTANTS;static VIRTUAL_SCHEMAS;static CUSTOM_FIELD_HANDLERS;_checkNotDeleted(){if(this._isDeleted)throw new ApiError(`Cet objet ${this.__entityTag} a été supprimé et ne peut plus être utilisé.`,400)}constructor(e,t={},n={},r={}){this.__entityTag=r.entityTag||this.getEntityTag(this._getCtor().entityTag)||"BaseEntity",this.deps=n;if("ApiClient"===this.getEntityTag(e?.__entityTag))this.apiClient=e,this.parent=null,this.userContext=null;else{if(!e||!("apiClient"in e))throw new ApiError("Parent invalide ou ApiClient manquant.",400);{const t=e;this.apiClient=t.apiClient,this.parent=t,this.userContext="User"===this.getEntityTag(t?.__entityTag)?t:t.userContext||null}}if("function"==typeof n.EndpointApi)this.endpointApi=new n.EndpointApi(this.apiClient);else{if("object"!=typeof n.EndpointApi)throw new ApiError("deps.EndpointApi doit être une classe ou une instance valide.",500);this.endpointApi=n.EndpointApi}this._serverData=N({});const{draft:o,proxy:i,initial:s}=this._buildDraftAndProxy({data:{...t,...this.defaultFields},serverData:this._serverData,constant:this._getCtor().SCHEMA_CONSTANTS,apiClient:this.apiClient,transforms:this.transforms,removeFields:this.removeFields});this._initialDraftData=s,this._draftData=o,this.data=i}_getCtor(){return this.constructor}getEntityTag=e=>e?.replace(/^_/,"");get id(){return this._draftData.id||null}get slug(){return this._draftData.slug||null}_id(e){this._draftData.id=e}get isConnected(){return this.apiClient.isConnected}get userId(){return this.apiClient.userId}get draftData(){return this._draftData}get initialDraftData(){return this._initialDraftData}get serverData(){return this._serverData}get isMe(){return!!(this.isConnected&&this.userId&&this.userContext?.id&&"string"==typeof this.userId&&"string"==typeof this.userContext?.id&&this.userId===this.userContext?.id)}getEntityType(){return this._getCtor().entityType}hasChanges(){const e=this._toRawDeep(this._draftData),t=this._serialize(e),n=this._serialize(this._initialDraftData);return JSON.stringify(t)!==JSON.stringify(n)}async refresh(){if(!this.id)throw new ApiError("Impossible de rafraîchir sans ID.",400);return this.get()}async save(){if(this._checkNotDeleted(),!this.isConnected)throw new ApiError("Non connecté.",401);this._calledFromSave=!0;try{const e={...this._draftData};if(!this.id&&"function"==typeof this._add)return await this._add(e),this._resetInitialDraftData(),this.userContext&&await(this.userContext?.refresh()),await this.refresh();if("function"==typeof this._update){const t=await this._update(e);if(this._resetInitialDraftData(),t)return await this.refresh()}return this._serverData}finally{this._calledFromSave=!1}}static fromServerData(e,t,n){const r=new this(t,{},n);return r._setData(e),r}_transformServerData(e){return e}_setData(e,{forceInitialDraftReset:t=!1}={}){this.userContext&&this.userContext!==this&&this.apiClient._logger?.debug?.(`[${this.__entityTag}] Mise à jour liée à userContext : ${this.userContext.id}`);const n=this._transformServerData(e)??{};if(this._serverData&&M(this._serverData)){for(const e of Object.keys(this._serverData))e in n||delete this._serverData[e];for(const e of Object.keys(n))this._serverData[e]=n[e]}else this._serverData=N({...n});const r=this._draftData?this._toRawDeep(this._draftData):{},o={...e||{},...this.defaultFields,...r},{draft:i,proxy:s,initial:a}=this._buildDraftAndProxy({data:o,serverData:this._serverData,previousDraft:this._draftData,constant:this._getCtor().SCHEMA_CONSTANTS,apiClient:this.apiClient,transforms:this.transforms,removeFields:this.removeFields});t?this._initialDraftData=structuredClone(this._toRawDeep(i)):this._initialDraftData||(this._initialDraftData=a),M(this._draftData)?this._updateDraftPreservingUserChanges(i):this._draftData=N(i),this.data||(this.data=s)}_updateDraftPreservingUserChanges(e){for(const t of Object.keys(this._draftData||{}))t in e||delete this._draftData[t];for(const t of Object.keys(e)){const n=this._draftData?.[t],r=this._initialDraftData?.[t];void 0!==n&&void 0!==r&&this._serialize(this._toRawDeep(n))!==this._serialize(r)||(this._draftData[t]=e[t])}}_resetInitialDraftData(){const e=this._toRawDeep(this._draftData);this._initialDraftData=structuredClone(e)}_toRawDeep(e){if(!this||"function"!=typeof this._toRawDeep)throw new Error("`this._toRawDeep` is not bound correctly. Use a lambda to preserve context.");if(x(e))return this._toRawDeep(e.value);if(e&&"object"==typeof e&&e.__isReactive&&e.__raw)return this._toRawDeep(e.__raw);if(e instanceof Date)return e;if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return e;if("undefined"!=typeof File&&e instanceof File)return e;if("undefined"!=typeof Blob&&e instanceof Blob)return e;if(e&&"function"==typeof e.pipe&&"function"==typeof e.on)return e;if(Array.isArray(e))return e.map((e=>this._toRawDeep(e)));if("object"==typeof e&&null!==e){const t={};for(const n of Object.keys(e))t[n]=this._toRawDeep(e[n]);return t}return e}defaultFields={};removeFields=[];transforms={};toJSON(){const e={};return this.parent?.id&&(e.id=this.parent.id),"function"==typeof this.parent?.getEntityType&&(e.type=this.parent.getEntityType()),this.parent?.__entityTag&&(e.__entityTag=this.parent.__entityTag),this.parent?.slug&&(e.slug=this.parent.slug),this.parent?.serverData&&(e.serverData={id:this.parent.serverData.id,collection:this.parent.serverData.collection,slug:this.parent.serverData.slug,...this.parent.serverData.name&&{name:this.parent.serverData.name},...this.parent.serverData.parent&&{parent:this.parent.serverData.parent},...this.parent.serverData.organizer&&{organizer:this.parent.serverData.organizer},...this.parent.serverData.links&&{links:this.parent.serverData.links}}),{__entityTag:this.__entityTag,__isSerializedEntity:!0,serverData:this._serialize(this._serverData),parent:Object.keys(e).length>0?e:null}}_serialize(e){try{return JSON.parse(v.stringify(this._removeUnserializables(e)))}catch(e){const t=e;return this.apiClient?._logger?.error?.("Erreur de sérialisation EJSON:",{message:t?.message,stack:t?.stack,error:e}),null}}_removeUnserializables(e,t=new WeakSet){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return e;if(e instanceof RegExp)return e;if(e&&"object"==typeof e&&"_bsontype"in e&&"ObjectID"===e._bsontype)return e;if(e instanceof Uint8Array||ArrayBuffer.isView(e))return e;if(e instanceof BaseEntity)return e.toJSON();if(t.has(e))return null;if(t.add(e),e.__isReactive&&"object"==typeof e.__raw)return this._removeUnserializables(e.__raw,t);if(Array.isArray(e))return e.map((e=>this._removeUnserializables(e,t)));const n={};for(const r of Object.keys(e)){const o=e[r];if("function"!=typeof o&&"symbol"!=typeof o&&void 0!==o)try{n[r]=this._removeUnserializables(o,t)}catch{n[r]=null}}return n}static _revive(e,t){const n=v.fromJSONValue(e);return this._deserializeNestedEntities(n,t)}static _deserializeNestedEntities(e,t){if(null===e||"object"!=typeof e)return e;if(e instanceof Date||e instanceof RegExp)return e;if(Array.isArray(e))return e.map((e=>this._deserializeNestedEntities(e,t)));if(e.__isSerializedEntity&&e.__entityTag&&e.serverData)return g(e,t);const n={};for(const[r,o]of Object.entries(e))n[r]=this._deserializeNestedEntities(o,t);return n}static fromJSON(e,t,n){if(!e||"object"!=typeof e||!("serverData"in e))throw new Error("Invalid JSON format: missing serverData");const{serverData:r}=e;return this.fromServerData(this._revive(r,t),t,n||{})}async call(e,t={}){return this.apiClient.safeCall((async()=>{const n=await this.apiClient.callEndpoint(e,t);return this.apiClient.checkAndThrowApiResponseError(n),n.data}))}async callNoConnected(e,t={}){if(this.isConnected)throw new ApiAuthenticationError("Vous devez ne devez pas être connecté pour faire cette action.",403);return this.call(e,t)}async callIsConnected(e,t={}){if(!this.isConnected)throw new ApiAuthenticationError("Vous devez être connecté pour faire cette action.",401);return"function"==typeof e?await e():this.call(e,t)}async callIsMe(e,t={}){if(!this.isMe)throw new ApiAuthenticationError("Vous devez être vous-même pour faire cette action.",403);return"function"==typeof e?await e():await this.callIsConnected(e,t)}async _validateImage(e){return await this._validateUploadInput(e,{allowedMimeTypes:["image/jpeg","image/png","image/jpg"],expectedType:"image"})}async _validateFile(e){return await this._validateUploadInput(e,{allowedMimeTypes:["application/pdf","text/plain","text/csv"],expectedType:"file"})}async _validateUploadInput(e,{allowedMimeTypes:t=[],expectedType:n="any"}){if(!e)throw new ApiValidationError("Le fichier est requis.",400,["Le fichier est requis"]);const r="undefined"==typeof window&&"undefined"!=typeof process;let o=null,i="";if("undefined"!=typeof File&&e instanceof File){if(i=e.type,!t.includes(i))throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);o=e}else if("undefined"!=typeof Blob&&e instanceof Blob){if(i=e.type,!t.includes(i))throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);const n=i.split("/")[1]||"bin",r=`${Date.now()}.${n}`;o=new File([e],r,{type:i})}else if(r&&Buffer.isBuffer(e)){const r=await U(e);if(!r)throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);if(i=r.mime,!t.includes(i))throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);if("image"===n){const t=r.ext,n=`${Date.now()}.${t}`;o=await this._createReadStreamFromBuffer(e,n,i)}else o=e}else{if(!r||!(s=e)||"object"!=typeof s||"function"!=typeof s.pipe||"function"!=typeof s.on)throw new ApiValidationError("Type de fichier non reconnu.",400,["Type de fichier non reconnu."]);{const n=e,r=[],s=await this._passThrough(),a=await this._passThrough(),c=4100;let p=0;n.on("data",(e=>{p<c&&(r.push(e),p+=e.length)})),n.pipe(s).pipe(a),await new Promise((e=>setTimeout(e,10)));const d=Buffer.concat(r),m=await U(d);if(!m)throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);if(i=m.mime,!t.includes(i))throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);a.path=`${Date.now()}.${m.ext}`,a.mimeType=i,o=a}}var s;return o}async _createReadStreamFromBuffer(e,t="file.bin",n="application/octet-stream"){const r=await this._bufferToReadable(e);return r.path=t,r.mimeType=n,r}async _bufferToReadable(e){if("undefined"==typeof window){const{bufferToReadable:t}=await Promise.resolve().then((function(){return se}));return t(e)}throw new Error("bufferToReadable ne doit pas être appelé dans le navigateur")}async _passThrough(){if("undefined"==typeof window){const{createPassThrough:e}=await Promise.resolve().then((function(){return se}));return e()}throw new Error("passThrough ne doit pas être appelé dans le navigateur")}_omitProps(e,t){if(!e||"object"!=typeof e)return{};const n={...e};for(const e of t)delete n[e];return n}_pickProps(e,t,n={}){if(!e||"object"!=typeof e)return{};const r={};for(const o of t)if(o in e){const t=e[o];"function"==typeof n[o]?r[o]=n[o](t,e):r[o]=t}return r}_hasAtLeastOne(e,t=[]){return t.some((t=>t in e&&null!=e[t]))}_createFilteredProxy(e){return new Proxy(e,{get(e,t,n){const r=e.filter((e=>!e._isDeleted));if("length"===t)return r.length;if("string"==typeof t&&/^\d+$/.test(t))return r[Number(t)];const o=Reflect.get(r,t,n);return"function"==typeof o?o.bind(r):o}})}_newId(){return F().toHexString()}_getAllowedFieldsForCurrentState(){if(!this._allowedFieldsMetadata)return this._allowedFieldsCache||[];const{combinedSchema:e,removeFields:t}=this._allowedFieldsMetadata,n=this._toRawDeep(this._draftData),r={...this.defaultFields,...n};let o=this._extractWritableFields(e,r);return r.id&&!o.includes("id")&&o.push("id"),r.slug&&!o.includes("slug")&&o.push("slug"),o=o.filter((e=>!t.includes(e))),o}_createDraftProxy(e,t={},n={},r=[],o={},i={},s=this){return new Proxy({},{get:(e,r)=>{if("string"==typeof r||"symbol"==typeof r){if("string"==typeof r&&r in n){const e=n[r],t=o[r];return"function"==typeof t?t(e,n):e}if(t&&"object"==typeof t&&"string"==typeof r&&r in t){const e=t[r],n=o[r];return"function"==typeof n?n(e,t):e}}},set:(t,r,o)=>{if("string"!=typeof r)return!1;const a=s._getAllowedFieldsForCurrentState();if(!a.includes(r)){const t=`[DraftProxy] Le champ "${r}" n'est pas autorisé.`;if(i.throwOnError)throw new ApiValidationError(t,400,[t],{field:r,value:o,allowedFields:a});return e._logger?.warn?.(t),!1}const c=n[r];return c&&"object"==typeof c&&!0===c.__isSignal?c.value=o:n[r]=o,!0},deleteProperty:(e,t)=>{if("string"!=typeof t)return!1;return!!s._getAllowedFieldsForCurrentState().includes(t)&&(delete n[t],!0)},has:(e,r)=>"string"==typeof r&&(r in n||t&&"object"==typeof t&&r in t),ownKeys:()=>{const e=new Set([...Object.keys(t||{}),...Object.keys(n||{})]);return Array.from(e)},getOwnPropertyDescriptor:(e,r)=>{if("string"==typeof r)return r in n||t&&"object"==typeof t&&r in t?{enumerable:!0,configurable:!0}:void 0}})}_extractWritableFields(e={},t={},n={defs:{},visited:new Set}){if(!e||"object"!=typeof e)return[];if(e.$id&&n.visited.has(e.$id))return[];e.$id&&n.visited.add(e.$id),n.defs=e.$defs||e.definitions||n.defs;const r=[];if(e.$ref){const o=e.$ref.replace(/^#\/?(\$defs|definitions)\//,""),i=n.defs[o];i&&r.push(...this._extractWritableFields(i,t,n))}if(e.allOf&&e.allOf.forEach((e=>r.push(...this._extractWritableFields(e,t,n)))),e.if&&e.then){const o=e.if.properties;let i=!0;if(o)for(const e in o){const n=o[e]?.const;if(t[e]!==n){i=!1;break}}i&&e.then?r.push(...this._extractWritableFields(e.then,t,n)):!i&&e.else&&r.push(...this._extractWritableFields(e.else,t,n))}return e.properties&&r.push(...Object.entries(e.properties).filter((([e,t])=>!0!==t.readOnly&&void 0===t.const)).map((([e])=>e))),Array.from(new Set(r))}_buildDraftAndProxy({data:e={},serverData:t=null,previousDraft:n=null,constant:r,apiClient:o,transforms:i={},throwOnError:s=!0,removeFields:a=[]}){const c=Array.isArray(r)?r:[r],p={allOf:[],$defs:{}};for(const e of c){let t=o.getRequestSchema(e);const n=this._getCtor(),r=n.VIRTUAL_SCHEMAS?.[e];if(r&&(t=this._mergeSchemas(t,r)),!t)throw new ApiError(`Unable to find schema for ${e}.`,404);if(t.$defs)for(const[n,r]of Object.entries(t.$defs))p.$defs[n]?o._logger.warn(`Duplicate $defs key '${n}' from schema '${e}'`):p.$defs[n]=r;p.allOf.push(t)}let d=this._extractWritableFields(p,e);e.id&&-1===d.indexOf("id")&&d.push("id"),e.slug&&-1===d.indexOf("slug")&&d.push("slug"),d=d.filter((e=>!a.includes(e))),this._allowedFieldsCache=d,this._allowedFieldsMetadata={combinedSchema:p,transforms:i,removeFields:a};const m=Object.fromEntries(d.map((t=>{const n=e[t];return[t,"function"==typeof i[t]?i[t](n,e):n]})).filter((([e,t])=>void 0!==t))),l=structuredClone?structuredClone(m):JSON.parse(JSON.stringify(m)),u=n&&M(n)?Object.assign(n,m):N(m),h=M(t)?t:t&&"object"==typeof t?N(t):t;return{draft:u,proxy:this._createDraftProxy(o,h,u,d,i,{throwOnError:s}),initial:l}}async _invokeBlockMethod(e,t,n){const r=this[t];return await r.call(this,n)}_isUploadType(e){return!("undefined"==typeof Buffer||!Buffer.isBuffer(e))||("undefined"!=typeof File&&e instanceof File||("undefined"!=typeof Blob&&e instanceof Blob||!(!e||"function"!=typeof e.pipe||"function"!=typeof e.on)))}_compareValues(e,t){return this._isUploadType(e)||this._isUploadType(t)?e!==t:JSON.stringify(this._toRawDeep(e))!==JSON.stringify(this._toRawDeep(t))}_mergeSchemas(e,t){return e?t?{allOf:[e,t],$defs:{...e.$defs,...t.$defs}}:e:t}_hasFieldChanged(e){const t=this._draftData[e],n=this._initialDraftData[e];return this._compareValues(t,n)}async _invokeCustomFieldHandler(e,t,n){const r=this[e];if("function"!=typeof r)throw new ApiError(`Custom handler "${e}" not found for field "${n}"`,500);return await r.call(this,t)}_extractChangedFieldsFromSchema(e,t,n={},r,o=[]){const i=e.getRequestSchema(t);let s=this._extractWritableFields(i,n);const a={},c=r?.()||{};s=s.filter((e=>!o.includes(e)));for(const e of s){if(void 0===n[e])continue;const t=n[e],r=c[e];this._compareValues(t,r)&&(a[e]=t)}return Object.keys(a).length>0?a:null}_extractAllValidFieldsFromSchema(e,t,n={},r,o=[]){const i=e.getRequestSchema(t);let s=this._extractWritableFields(i,n);const a={},c={},p=r?.()||{};s=s.filter((e=>!o.includes(e)));for(const e of s){if(void 0===n[e])continue;const t=n[e],r=p[e];JSON.stringify(t)!==JSON.stringify(r)&&(a[e]=t),c[e]=t}return Object.keys(a).length>0?c:null}async _resolveId(e){if(!this.id&&this.slug)try{const t=await this.endpointApi.getElementsKey({pathParams:{slug:this.slug}});if(!t.contextId||t.contextType!==e)throw new ApiResponseError(`Le slug ${this.slug} ne correspond pas à un ${e}`,200,t);this._id(t.contextId)}catch(t){if(t instanceof ApiResponseError){throw t.responseData.contextType!==e?t:new ApiResponseError(`Impossible de récupérer l'identifiant pour le slug ${this.slug}`,t.status,t.responseData)}throw t}if(!this.id)throw new ApiError(`Impossible de résoudre l'identifiant pour le type ${e}.`,404);return this.id}async _getPublicProfile(){if(await this._resolveId(this.getEntityType()),!this.id)throw new ApiError("L'identifiant de l'entité n'est pas défini.",400);const e=this.getEntityType();if("news"===e||"comments"===e)throw new ApiError("getElementsAbout ne supporte pas le type 'news'.",400);return this.endpointApi.getElementsAbout({pathParams:{id:this.id,type:e},tpl:"ficheInfoElement"})}_getEntityMeta(e){const t=this.constructor,n=this.__entityTag,r={EndpointApi:this.deps.EndpointApi,User:"User"===n?t:this.deps.User,Organization:"Organization"===n?t:this.deps.Organization,Project:"Project"===n?t:this.deps.Project,Event:"Event"===n?t:this.deps.Event,Poi:"Poi"===n?t:this.deps.Poi,Badge:"Badge"===n?t:this.deps.Badge,News:"News"===n?t:this.deps.News,Comment:"Comment"===n?t:this.deps.Comment,Answer:"Answer"===n?t:this.deps.Answer};return{citoyens:{entityClass:r.User,deps:r},organizations:{entityClass:r.Organization,deps:r},projects:{entityClass:r.Project,deps:r},events:{entityClass:r.Event,deps:{...r,Badge:void 0}},poi:{entityClass:r.Poi,deps:{...r,Badge:void 0,News:void 0}},news:{entityClass:r.News,deps:{...r}},badges:{entityClass:r.Badge,deps:{EndpointApi:r.EndpointApi,User:r.User,Organization:r.Organization,Project:r.Project}},comments:{entityClass:r.Comment,deps:{...r}},answers:{entityClass:r.Answer,deps:{...r}}}[e]||null}_linkEntity(e,t){const n=this._getEntityMeta(e);return n?n.entityClass.fromServerData(t,this,n.deps):t}_linkNestedEntity(e){if(!e||"object"!=typeof e)return e;if(!e.id||!e.type)return e;try{return this._linkEntity(e.type,e)}catch(t){return this.apiClient._logger?.warn?.(`Impossible de lier l'entité imbriquée de type ${e.type}:`,t),e}}async _linkEntityById(e,t,n){const r=this._getEntityMeta(e);if(!r)return null;const o=new r.entityClass(this,{id:t},r.deps);return n?.skipGet||await o.get(),o}_linkEntities(e){return e.flatMap((e=>e?.collection?[this._linkEntity?.(e.collection,e)??e]:(this.apiClient._logger?.warn?.(`Objet ignoré car sans 'collection' : ${e?.id}`),[])))}async linkEntitiesFromServerData(e,t={},n={}){const r=n.key||e,o="function"==typeof n.mapFn?n.mapFn:null,i=e=>!0===e||"true"===e,s=e=>!1===e||"false"===e,a=this.serverData?.[r],c=[];if(a&&"object"==typeof a&&Object.keys(a).length>0)for(const n of Object.keys(a)){const r=a[n],p=Object.entries(t).every((([e,t])=>{const n=r[e];if("function"==typeof t)try{return t(n)}catch(t){return console.warn(`Erreur dans le filtre personnalisé pour ${e}`,t),!1}return t instanceof RegExp?"string"==typeof n&&t.test(n):"string"==typeof t&&"string"==typeof n?n.toLowerCase().includes(t.toLowerCase()):i(t)?i(n):s(t)?s(n):"string"!=typeof n||"string"!=typeof t||isNaN(Date.parse(n))||isNaN(Date.parse(t))?n===t:new Date(n).getTime()===new Date(t).getTime()}));if(p)try{const t=await this._linkEntityById(e,n);t&&(t.meta=r,c.push(o?o(t):t))}catch(t){this.apiClient._logger?.error?.(`Erreur lors de la récupération de l'entité ${e} (${n}) :`,t)}}return c}_entityInstanceData(e,t){const n=this._getEntityMeta(e);if(!n)throw new ApiError(`Type d'entité inconnu: ${e}`,400);const r=this.__entityTag,o=this.constructor;return new n.entityClass(this,t,{[r]:o,...n.deps})}async entity(e,t={}){try{const n=this._entityInstanceData(e,t),r={citoyens:["id","slug"],organizations:["id","slug"],projects:["id","slug"],events:["id","slug"],poi:["id","slug"],news:["id"],badges:["id"],comments:[],answers:["id"]}[e];return r&&this._hasAtLeastOne(t,r)&&await n.get(),n}catch(t){throw this.apiClient._logger.error(`[Api.${this.__entityTag}.${e}] Erreur lors de la création d'une instance ${e} :`,t.message),t}}async entityBySlug(e){if(!e)throw new ApiError("Le slug est requis.",400);try{const t=await this.endpointApi.getElementsKey({pathParams:{slug:e}});if(t.contextId&&t.contextType){const e=await this.entity(t.contextType,{id:t.contextId});return await this._fixEntityUserContext(e),e}throw new ApiResponseError(`Le slug ${e} n'est pas valide`,200,t)}catch(t){throw t instanceof ApiResponseError?new ApiResponseError(`Impossible de récupérer l'identifiant pour le slug ${e}`,t.status,t.responseData):t}}async _fixEntityUserContext(e){const t=e.getEntityType();if(!["events","projects","poi"].includes(t))return;const n=this._extractRealParent(e);if(!n)return;const r=await this._findOrCreateParent(n);r&&r!==e.parent&&(e.userContext=this._extractUserContext(r),e.parent=r)}_extractRealParent(e){const t=e.serverData;if("events"===e.getEntityType()){const e=t;if(e.organizer){const t=Object.entries(e.organizer),n=t.find((([e,t])=>"projects"===t.type));if(n)return{type:"projects",id:n[0]};const r=t.find((([e,t])=>"organizations"===t.type));if(r)return{type:"organizations",id:r[0]};const o=t.find((([e,t])=>"citoyens"===t.type));if(o)return{type:"citoyens",id:o[0]};const i=t[0];if(i&&i[1])return{type:i[1].type,id:i[0]}}}const n=t;if(n.parent){const e=Object.entries(n.parent)[0];if(e&&e[1])return{type:e[1].type,id:e[0]}}return null}async _findOrCreateParent(e){try{let t=this.parent;for(;t;){if(t.id===e.id&&t.getEntityType()===e.type)return t;t=t.parent}const n={citoyens:"citoyens",organizations:"organizations",projects:"projects"}[e.type];if(n){const t=this._entityInstanceData(n,{id:e.id});return await t.get(),t}return null}catch(e){return this.apiClient._logger?.warn?.("Impossible de créer le parent réel:",e),null}}_extractUserContext(e){return"User"===this.getEntityTag(e?.__entityTag)?e:e.userContext||null}_isAdminViaHierarchy(){const e=this.getEntityType(),t=this.serverData;let n;if("events"===e)n=t?.organizer;else{if("projects"!==e&&"poi"!==e)return!1;n=t?.parent}if(!n||"object"!=typeof n)return!1;for(const[e,t]of Object.entries(n)){if(!t||"object"!=typeof t)continue;const n=t.type;if(n&&this._isAdminOfParent(e,n))return!0}return!1}_isAdminOfParent(e,t){const n=this.userContext?.serverData?.links;if(!n)return!1;let r;if("citoyens"===t)return!1;if("organizations"===t)r="memberOf";else{if("projects"!==t)return!1;r="projects"}const o=n[r];if(!o)return!1;const i=o[e];return this._validateUserLink(i)&&!0===i?.isAdmin&&!i?.isAdminPending}_buildLinkFilters(e,{linkType:t,isAdmin:n,isAdminPending:r,isInviting:o,toBeValidated:i=!1,roles:s=[]}){if("string"!=typeof e||null===e)throw new TypeError("id doit être une chaîne non-nulle.");if("string"!=typeof t)throw new TypeError("linkType doit être une chaîne.");if(void 0!==n&&"boolean"!=typeof n)throw new TypeError("isAdmin doit être un booléen.");if(void 0!==r&&"boolean"!=typeof r)throw new TypeError("isAdminPending doit être un booléen.");if(void 0!==o&&"boolean"!=typeof o)throw new TypeError("isInviting doit être un booléen.");if(void 0!==i&&"boolean"!=typeof i)throw new TypeError("toBeValidated doit être un booléen.");if(!Array.isArray(s))throw new TypeError("roles doit être un tableau de chaînes.");const a=`links.${t}.${e}`,c={[`${a}`]:{$exists:!0}};return"boolean"==typeof i&&(c[`${a}.toBeValidated`]={$exists:i}),"boolean"==typeof o&&(c[`${a}.isInviting`]={$exists:o}),!0===n&&(c[`${a}.isAdmin`]={$exists:!0}),!0===r&&(c[`${a}.isAdminPending`]={$exists:!0}),s.length>0&&(c[`${a}.roles`]={$in:s}),c}_getLinkMeta(){const e=this.getEntityType(),t={organizations:{linkType:"memberOf",connectTypeConnect:"member",connectTypeDisconnect:"members"},projects:{linkType:"projects",connectTypeConnect:"contributor",connectTypeDisconnect:"contributors"},events:{linkType:"events",connectTypeConnect:"attendee",connectTypeDisconnect:"attendees"},citoyens:{linkType:"friends",connectTypeConnect:"friend",connectTypeDisconnect:"friends"}}[e];if(!t)throw new ApiError(`Aucune correspondance de lien définie pour le type d'entité "${e}"`,404);return t}_checkLinkableEntity(){try{this._getLinkMeta()}catch(e){if(e instanceof ApiError)throw new ApiError(`L'entité "${this.getEntityType()}" ne prend pas en charge les actions de lien.`,400);throw e}}_getLinkFromConnectedUser(){const{linkType:e}=this._getLinkMeta();if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);return this?.userContext?.serverData?.links?.[e]?.[this.id]||null}async _submitLinkRequest(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const{connectTypeConnect:e}=this._getLinkMeta(),t=this._getLinkFromConnectedUser();if(!t){this._assertNotEntityType("connect",["poi","badges","news"]);const t=this.getEntityType(),n={childId:this.userId,childType:"citoyens",parentType:t,parentId:this.id,connectType:e},r=await this.callIsMe((()=>this.endpointApi.connect(n)));return await(this.userContext?.refresh()),r}if(t.isInviting)return this._acceptLinkRequest();if(t.toBeValidated)throw new ApiError("Vous êtes déjà en attente de validation.",400);throw new ApiError("Vous êtes déjà connecté à cette entité.",400)}async _submitLinkRequestAdmin(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const e=this._getLinkFromConnectedUser();if(!e){this._assertNotEntityType("connect",["poi","badges","news"]);const e=this.getEntityType(),t={childId:this.userId,childType:"citoyens",parentType:e,parentId:this.id,connectType:"admin"},n=await this.callIsMe((()=>this.endpointApi.connect(t)));return await(this.userContext?.refresh()),n}if(e.isInviting||e.isAdminInviting)return this._acceptLinkRequest();if(e.toBeValidated&&e.isAdminPending)throw new ApiError("Vous êtes déjà en attente de validation pour devenir admin.",400);if(e.toBeValidated)throw new ApiError("Vous êtes déjà en attente de validation pour rejoindre cette entité.",400);throw new ApiError("Vous êtes déjà connecté à cette entité.",400)}async _acceptLinkRequest(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const e=this._getLinkFromConnectedUser();if(e&&(e.isInviting||e.isAdminInviting)){this._assertNotEntityType("linkValidate",["poi","badges","news"]);const e=this.getEntityType(),t={childId:this.userId,childType:"citoyens",parentType:e,parentId:this.id,linkOption:"isInviting"},n=await this.callIsMe((()=>this.endpointApi.linkValidate(t)));return await(this.userContext?.refresh()),n}throw new ApiError("Vous n'avez pas d'invitation à valider.",400)}async _leaveLinkRequest(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const{connectTypeDisconnect:e}=this._getLinkMeta();if(!this._getLinkFromConnectedUser())throw new ApiError("Vous n'êtes pas connecté à cette entité.",404);this._assertNotEntityType("disconnect",["poi","badges","news"]);const t=this.getEntityType(),n={childId:this.userId,childType:"citoyens",parentType:t,parentId:this.id,connectType:e},r=await this.callIsMe((()=>this.endpointApi.disconnect(n)));return await(this.userContext?.refresh()),r}async get(){return this.apiClient.safeCall((async()=>{const e=await this._getPublicProfile();return this._setData(e,{forceInitialDraftReset:!0}),e}))}async updateSettings(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateSettings",["poi","badges","news"]);const t=this.getEntityType(),{type:n,value:r}=e;if("string"!=typeof n)throw new ApiValidationError("Le champ 'type' est requis (string).",400,["type requis"]);const o={type:n,value:r,idEntity:this.id,typeEntity:t};return this.callIsConnected((()=>this.endpointApi.updateSettings(o)))}async updateDescription(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateDescription",["badges","news"]);const t=this.getEntityType(),n={block:"descriptions",id:this.id,typeElement:t,...e};return this.callIsConnected((()=>this.endpointApi.updateBlockDescription(n)))}async updateInfo(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateInfo",["badges","news"]);const t=this.getEntityType(),n={block:"info",id:this.id,typeElement:t,...e};return this.callIsConnected((()=>this.endpointApi.updateBlockInfo(n)))}async updateSocial(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateSocial",["badges","news","poi","events"]);const t=this.getEntityType(),n={block:"network",id:this.id,typeElement:t,...e};return this.callIsConnected((()=>this.endpointApi.updateBlockSocial(n)))}_isPostalAddress(e){return!!e&&"object"==typeof e&&"PostalAddress"===e["@type"]&&"string"==typeof e.addressCountry&&"string"==typeof e.addressLocality&&"string"==typeof e.level1&&"string"==typeof e.level1Name&&"string"==typeof e.codeInsee&&"string"==typeof e.localityId}_isGeo(e){return!(!e||"object"!=typeof e||"number"!=typeof e.latitude&&"string"!=typeof e.latitude||"number"!=typeof e.longitude&&"string"!=typeof e.longitude)}_isGeoPosition(e){return!!e&&"object"==typeof e&&"Point"===e.type&&Array.isArray(e.coordinates)&&2===e.coordinates.length&&("number"==typeof e.coordinates[0]||"string"==typeof e.coordinates[0])&&("number"==typeof e.coordinates[1]||"string"==typeof e.coordinates[1])&&!0===e.float}async updateLocality(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(this._assertNotEntityType("updateLocality",["badges","news","comments","answers"]),!("address"in e))throw new ApiValidationError("Le champ 'address' est requis.",400,["address requis"]);const t=e.address;if(""!==t&&!this._isPostalAddress(t))throw new ApiValidationError("Format de 'address' invalide.",400,["address invalide"]);const n=t,r=this.getEntityType(),o={block:"localities",id:this.id,typeElement:r,address:n,..."geo"in e&&this._isGeo(e.geo)?{geo:e.geo}:{},..."geoPosition"in e&&this._isGeoPosition(e.geoPosition)?{geoPosition:e.geoPosition}:{},..."locality"in e?{locality:e.locality}:{}};return this.callIsConnected((()=>this.endpointApi.updateBlockLocality(o)))}async updateSlug({slug:e}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateSlug",["badges","news","poi","comments"]);const t=this.getEntityType();try{await this.endpointApi.check({block:"info",type:t,id:this.id,slug:e})}catch(e){if(e instanceof ApiResponseError)throw new ApiResponseError("Erreur lors de la vérification du slug.",e.status,e.responseData);throw e}const n={block:"info",typeElement:t,id:this.id,slug:e};return this.callIsConnected((()=>this.endpointApi.updateBlockSlug(n)))}async updateImageProfil({profil_avatar:e}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateImageProfil",["badges","news","comments","answers"]);const t=this.getEntityType();e=await this._validateImage(e);const n={pathParams:{folder:t,ownerId:this.id},profil_avatar:e};return this.callIsConnected((()=>this.endpointApi.profilImage(n)))}async updateImageBanner({banner:e,cropW:t,cropH:n,cropX:r,cropY:o}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateImageBanner",["badges","news","comments","answers"]);const i=this.getEntityType();e=await this._validateImage(e);const s={pathParams:{folder:i,ownerId:this.id},parentType:i,parentId:this.id,formOrigin:"banner",cropW:t,cropH:n,cropX:r,cropY:o,banner:e};return this.callIsConnected((()=>this.endpointApi.profilBanner(s)))}async organization(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer une organisation.",403);return await this.entity("organizations",e)}async project(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isConnected)throw new ApiError("Vous devez être connecté pour créer un projet.",401);return await this.entity("projects",e)}async poi(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isConnected)throw new ApiError("Vous devez être connecté pour créer un POI.",401);return await this.entity("poi",e)}async event(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isConnected)throw new ApiError("Vous devez être connecté pour créer un événement.",401);return await this.entity("events",e)}async badge(e={}){if(!("id"in e)&&!this.isConnected)throw new ApiError("Vous devez être connecté pour créer un badge.",401);return await this.entity("badges",e)}async news(e={}){if(!e?.id&&!this.isConnected)throw new ApiError("Vous devez être connecté.",401);return await this.entity("news",e)}async getOrganizations(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_ORGANIZATIONS_NO_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getOrganizations",restoredState:t?.restoredState,finalizer:async e=>{this.isMe?e.pathParams={type:this.getEntityType(),id:this.id}:(delete e?.pathParams,e.filters={[`links.members.${this.id}`]:{$exists:!0},[`links.members.${this.id}.toBeValidated`]:{$exists:!1},[`links.members.${this.id}.isInviting`]:{$exists:!1}});return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getOrganizationsAdmin(e))):()=>this.endpointApi.getOrganizationsNoAdmin(e))()}}).next()}async getProjects(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_PROJECTS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getProjects",restoredState:t?.restoredState,finalizer:async e=>{this.isMe?e.pathParams={type:this.getEntityType(),id:this.id}:(delete e?.pathParams,e.filters={$or:{[`links.contributors.${this.id}`]:{$exists:!0},[`parent.${this.id}`]:{$exists:!0}},[`links.contributors.${this.id}`]:{$exists:!0}});return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getProjectsAdmin(e))):()=>this.endpointApi.getProjectsNoAdmin(e))()}}).next()}async getEvents(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_EVENTS","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getEvents",restoredState:t?.restoredState,finalizer:async e=>(delete e?.pathParams,e.filters={$or:{[`links.attendees.${this.id}`]:{$exists:!0},[`organizer.${this.id}`]:{$exists:!0}}},this.endpointApi.getEvents(e))}).next()}async getPois(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_POIS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getPois",restoredState:t?.restoredState,finalizer:async e=>{this.isMe?e.pathParams={type:this.getEntityType(),id:this.id}:(delete e?.pathParams,e.filters={[`parent.${this.id}`]:{$exists:!0}});return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getPoisAdmin(e))):()=>this.endpointApi.getPoisNoAdmin(e))()}}).next()}async getSubscribers(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_SUBSCRIBERS","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getSubscribers",restoredState:t?.restoredState,finalizer:async e=>(delete e?.pathParams,e.filters={[`links.follows.${this.id}`]:{$exists:!0},[`links.follows.${this.id}.toBeValidated`]:{$exists:!1},[`links.follows.${this.id}.isInviting`]:{$exists:!1}},this.endpointApi.getSubscribers(e))}).next()}async getBadgesIssuer(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_BADGES","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getBadgesIssuer",restoredState:t?.restoredState,finalizer:async e=>(delete e?.pathParams,e.filters=e.filters||{"preferences.private":!1},e.filters.$or={},e.filters.$or[`issuer.${this.id}`]={$exists:!0},this.endpointApi.getBadges(e))}).next()}async getNews(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("getNews",["badges","news","poi","events","comments","answers"]);const t=this.getEntityType(),n="dateLimit"in e&&"number"==typeof e.dateLimit?{dateLimit:e.dateLimit}:{dateLimit:0},r="indexStep"in e&&"number"==typeof e.indexStep?{indexStep:e.indexStep}:{indexStep:12},o="search"in e&&"object"==typeof e.search&&null!==e.search&&"name"in e.search&&"string"==typeof e.search.name?{search:{name:e.search.name}}:{},i={pathParams:{type:t,id:this.id,isLive:!0},...n,...r,...o},s=await this.endpointApi.getNews(i);if(!Array.isArray(s))throw new ApiResponseError("Erreur lors de la récupération des actualités.",500,s);const a=this._linkEntities(s);return this._createFilteredProxy(a)}async getGallery(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("getGallery",["badges","news","poi","events","comments","answers"]);const t={pathParams:{type:this.getEntityType(),id:this.id,docType:e.pathParams?.docType||"image"}};return await this.endpointApi.getGallery(t)}async searchMembers(e){const t=await this.endpointApi.searchMemberAutocomplete(e);if(!t||!Array.isArray(t))return[];this._assertNotEntityType("searchMembers",["badges","news","poi","comments"]),t.forEach((e=>{for(const t of Object.keys(e))["id","name","slug","profilThumbImageUrl","profilMarkerImageUrl","type","collection"].includes(t)||delete e[t]}));return this._linkEntities(t)}async requestToJoin(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);return this._checkLinkableEntity(),this._submitLinkRequest()}async requestToJoinAdmin(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);return this._checkLinkableEntity(),this._submitLinkRequestAdmin()}async requestPromoteToAdmin(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);if(this._checkLinkableEntity(),!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const e=this._getLinkFromConnectedUser();if(!e)throw new ApiError("vous n'êtes pas membre de cette entité.",400);if(e?.isAdmin&&(e?.isInviting||e?.isAdminInviting))throw new ApiError("Cet utilisateur est déjà en cours d'invitation en tant qu'admin.",400);if(e?.isAdmin&&!e?.isInviting&&!e?.isAdminInviting)throw new ApiError("Cet utilisateur est déjà admin.",400);const t=this.getEntityType(),n=["organizations","projects"];if(!n.includes(t))throw new ApiError(`L'entité doit être de type : ${n.join(", ")}, reçu : ${t}`,400);const r=t,o={childId:this.userId,childType:"citoyens",parentType:r,parentId:this.id,connectType:"admin"},i=await this.callIsMe((()=>this.endpointApi.connect(o)));return await(this.userContext?.refresh()),i}async acceptInvitation(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);return this._checkLinkableEntity(),this._acceptLinkRequest()}async leave(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);return this._checkLinkableEntity(),this._leaveLinkRequest()}async follow(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour suivre cette entité.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("Utilisateur non connecté.",401);this._assertNotEntityType("follow",["badges","news","poi","comments"]);const e=this.getEntityType();if(!(this.userContext?.serverData?.links?.follows?.[this.id]||null)){const t={childId:this.userId,childType:"citoyens",parentType:e,parentId:this.id},n=await this.callIsMe((()=>this.endpointApi.follow(t)));return await(this.userContext?.refresh()),n}throw new ApiError("Vous êtes déjà abonné à cette entité.",409)}async unfollow(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour vous désabonner.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("Utilisateur non connecté.",401);const e=this.userContext?.serverData?.links?.follows?.[this.id]||null;this._assertNotEntityType("unfollow",["badges","news","poi"]);const t=this.getEntityType();if(e){const e={childId:this.userId,childType:"citoyens",parentType:t,parentId:this.id,connectType:"followers"},n=await this.callIsMe((()=>this.endpointApi.disconnect(e)));return await(this.userContext?.refresh()),n}throw new ApiError("Vous n'êtes pas abonné à cette entité.",404)}_checkAccess(e="effectuer cette action"){if(!this.isMe)throw new ApiError(`Vous devez être connecté pour ${e}.`,401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404)}_validateUserLink(e){if(!e)return!1;const{toBeValidated:t,isInviting:n,isAdminInviting:r,isAdminPending:o}=e;return!(t||n||r||o)}_assertEntityType(...e){const t=Array.isArray(e[0])?e[0]:e;if(!t.includes(this.getEntityType()))throw new ApiError(`L'entité doit être de type : ${t.join(", ")}, reçu : ${this.getEntityType()}`,400)}_assertNotEntityType(e,...t){const n=Array.isArray(t[0])?t[0]:t,r=this.getEntityType();if(n.includes(r))throw new ApiError(`Le type d'entité "${r}" n'est pas supporté par ${e}.`,400)}_getValidatedUserLink(e,t,n){const r=n?.silent??!0;try{this._checkAccess(e),this._assertEntityType(...t)}catch(e){if(r)return null;throw e}return this._getLinkFromConnectedUser()}_isLinked(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t=this.userContext?.serverData?.links;return!!t&&!!t[e]?.[this.id]}isAuthor(e){const t=e?.silent??!0;try{if(this._checkAccess("vérifier l'auteur"),!this.serverData)throw new ApiError("Aucune donnée serveur disponible.",404);if(!this.userId)throw new ApiError("Utilisateur non connecté.",401)}catch(e){if(t)return!1;throw e}const n=this.serverData;return!!n.creator&&Boolean(this.userId&&"string"==typeof n.creator&&n.creator===this.userId)}isAdmin(e){const t=this._getValidatedUserLink("vérifier l'administrateur",["organizations","projects","events"],{silent:e?.silent});return!(!this._validateUserLink(t)||!0!==t?.isAdmin||t?.isAdminPending)||!!e?.checkHierarchy&&this._isAdminViaHierarchy()}isAuthorOrAdmin(e){return this.isAuthor()||this.isAdmin(e)}isMember(e){const t=this._getValidatedUserLink("vérifier le membre",["organizations"],{silent:e?.silent});return this._validateUserLink(t)}isContributor(e){const t=this._getValidatedUserLink("vérifier le contributeur",["projects"],{silent:e?.silent});return this._validateUserLink(t)}isAttendee(e){const t=this._getValidatedUserLink("vérifier le participant",["events"],{silent:e?.silent});return this._validateUserLink(t)}isFollower(e){return!!this._getValidatedUserLink("vérifier si il vous suit",["citoyens","organizations","projects","events","poi"],{silent:e?.silent})&&this._isLinked("followers")}isFollowing(e){return!!this._getValidatedUserLink("vérifier si vous le suivez",["citoyens","organizations","projects","events","poi"],{silent:e?.silent})&&this._isLinked("follows")}isToBeValidated(e){const t=this._getValidatedUserLink("vérifier si il est à valider",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.toBeValidated}isInviting(e){const t=this._getValidatedUserLink("vérifier si il est invité",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.isInviting}isInvitingAdmin(e){const t=this._getValidatedUserLink("vérifier si il est invité admin",["organizations","projects","events"],{silent:e?.silent});return!!t&&((!0===t.isAdminInviting||!0===t.isInviting)&&!0===t.isAdmin)}isAdminPending(e){const t=this._getValidatedUserLink("vérifier si il est en attente admin",["organizations","projects","events"],{silent:e?.silent});return!!t&&(!0===t.isAdmin&&!0===t.isAdminPending)}async getCostumJson(){if(!this.serverData)throw new ApiError("Aucune donnée serveur disponible.",404);const e=this.serverData;if(!e||"string"!=typeof e.slug||""===e.slug.trim())throw new ApiError("slug de l'entité non défini",400);const t={pathParams:{slug:e.slug}};return this.endpointApi.getCostumJson(t)}_generateRanges(e,t,n={}){const r={};for(const o of e){const e=n[o]||{indexMax:0};r[o]={indexMin:e.indexMax||0,indexMax:e.indexMax+t}}return r}_normalizeCount(e={}){return delete e.spam,e.total=Object.values(e).reduce(((e,t)=>e+("number"==typeof t?t:0)),0),e}_getDefaultFromEndpoint(e,t){const n=this.apiClient.getRequestSchema(e);if(n?.properties?.[t])return n.properties[t].default}_createPaginatorEngine({initialData:e,finalizer:t,methodName:n,restoredState:r}){const o=this,i=r?{...r}:{cursor:null,count:0,index:0,history:[],sizes:[]},s=e=>Boolean(e?.indexStep&&e.indexStep>0);async function a(r=!1){const c={...e};i.cursor&&(r||0!==i.history.length)||(i.count=0,i.index=0,i.history=[],i.sizes=[],c.countType=c.searchType,!c.searchBy&&s(c)?(c.ranges=o._generateRanges(c.searchType,c.indexStep),c.indexMin=c.indexMin??0,c.indexMax=c.indexMax??c.indexStep):"ALL"===c.searchBy&&s(c)&&(c.indexMin=c.indexMin??0,c.indexMax=c.indexMax??c.indexStep),i.cursor={...c});const p=i.cursor;r&&p&&(i.history.push({...p}),!p.searchBy&&s(p)?(p.ranges=o._generateRanges(p.searchType,p.indexStep,p.ranges),p.indexMin=p.indexMax??0,p.indexMax=(p.indexMax??0)+p.indexStep):"ALL"===p.searchBy&&s(p)&&(p.indexMin=p.indexMax??0,p.indexMax=(p.indexMax??0)+p.indexStep),i.cursor={...p});const d={...i.cursor||{}};if(!r){const e=d.searchType;if(!Array.isArray(e)||0===e.length)throw new Error("searchType non défini")}const m=await t(d);if(!Array.isArray(m.results))throw new Error("Les résultats doivent être un tableau");i.count+=m.results.length,i.sizes.push(m.results.length),r&&i.index++;const l=o._normalizeCount(m.count),u=o._linkEntities(m.results),h=s(d)&&i.count<l.total,y=i.history.length>0;return{count:l,results:u,pageIndex:i.index,pageNumber:i.index+1,hasNext:h,hasPrev:y,next:h?()=>a(!0):void 0,prev:y?async()=>{const e=i.history.pop(),t=i.sizes.pop()??0;return i.count-=t,i.index=Math.max(0,i.index-1),i.cursor={...e},a(!1)}:void 0,_initialData:{...e},_state:i,_entity:o,_methodName:n}}return{next:()=>a(!1)}}_withCostumContext(e){return async t=>{if(!this.serverData)throw new ApiError("Aucune donnée serveur disponible.",404);const n=this.serverData;if(!n||"string"!=typeof n.slug||""===n.slug.trim())throw new ApiError("slug de l'entité non défini",400);if(!n.id||"string"!=typeof n.id)throw new ApiError("id de l'entité non défini",400);const r=Array.isArray(t?.sourceKey)?t.sourceKey:[],o={...t||{},costumSlug:n.slug,contextId:n.id,contextType:this.getEntityType(),sourceKey:[...r,n.slug]};return e(o)}}async searchCostum(e={},t){return this._createPaginatorEngine({initialData:e,methodName:"searchCostum",restoredState:t?.restoredState,finalizer:this._withCostumContext((e=>this.endpointApi.globalAutocompleteCostum(e)))}).next()}async costumEventRequestActors(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e},n=this._withCostumContext((e=>this.endpointApi.costumEventRequestActors(e)));return await n(t)}async costumEventRequestSubevents(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestSubevents(e)))(t)}async costumEventRequestDates(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestDates(e)))(t)}async costumEventRequestElementEvent(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestElementEvent(e)))(t)}async costumEventRequestCategories(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestCategories(e)))(t)}async costumEventRequestEvent(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestEvent(e)))(t)}async costumEventRequestLinkTlToEvent(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!e.tl&&!e.event)throw new ApiError("Les paramètres 'tl' et 'event' sont requis.",400);if("string"!=typeof e.tl||"string"!=typeof e.event)throw new ApiError("Les paramètres 'tl' et 'event' doivent être des chaînes de caractères.",400);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestLinkTlToEvent(e)))(t)}async costumEventRequestLoadContextTag(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestLoadContextTag(e)))(t)}async coformAnswersSearch(e={},t){return this._createPaginatorEngine({initialData:e,methodName:"coformAnswersSearch",restoredState:t?.restoredState,finalizer:this._withCostumContext((e=>this.endpointApi.coformAnswersSearch(e)))}).next()}static restorePaginationFromJSON(e,t){const n=t instanceof BaseEntity?t:g(e._entity,t),r=e.results.map((e=>g(e,n))),o=e._methodName,i=e._initialData,s=e._state;return{results:r,count:e.count,hasNext:e.hasNext,hasPrev:e.hasPrev,pageIndex:e.pageIndex,pageNumber:e.pageNumber,next:e.hasNext?async()=>{const e=n[o];if("function"!=typeof e)throw new Error(`Méthode ${o} non trouvée sur l'entité`);const t=await e.call(n,i,{restoredState:s});return t.next?.()??t}:void 0,prev:e.hasPrev?async()=>{const e=n[o];if("function"!=typeof e)throw new Error(`Méthode ${o} non trouvée sur l'entité`);const t=await e.call(n,i,{restoredState:s});return t.prev?.()??t}:void 0,_initialData:i,_state:s,_entity:n,_methodName:o}}}class Answer extends BaseEntity{static entityType="answers";static entityTag="Answer";static SCHEMA_CONSTANTS=[];static ADD_BLOCKS=new Map([]);static UPDATE_BLOCKS=new Map([]);defaultFields={};removeFields=[];_transformServerData(e){return e.user&&"object"==typeof e.user&&"id"in e.user&&(e.user=this._linkNestedEntity({type:"citoyens",collection:"citoyens",...e.user})),e}async get(){if(!this.id)throw new ApiError("Impossible de rafraîchir sans ID.",400);const e=this.id,t=await this.endpointApi.coformAnswersById({answerId:e});if(t?.data?.id)return this._setData(t.data,{forceInitialDraftReset:!0}),this.serverData;throw new ApiError(`Aucune réponse trouvée pour l'ID ${this.id}`,404)}}class Badge extends BaseEntity{static entityType="badges";static entityTag="Badge";static SCHEMA_CONSTANTS=["ADD_BADGES"];static ADD_BLOCKS=new Map([["ADD_BADGES","addBadges"]]);static UPDATE_BLOCKS=new Map([]);defaultFields={};removeFields=[];_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Badge.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this[n](r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;for(const[n,r]of Array.from(Badge.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this[r](o),t=!0)}return t};async getOrganizations(){throw new ApiError(`getOrganizations n'existe pas dans ${this.constructor.name}`,501)}async getProjects(){throw new ApiError(`getProjects n'existe pas dans ${this.constructor.name}`,501)}async getEvents(){throw new ApiError(`getEvents n'existe pas dans ${this.constructor.name}`,501)}async getPois(){throw new ApiError(`getPois n'existe pas dans ${this.constructor.name}`,501)}async getBadgesIssuer(){throw new ApiError(`getBadgesIssuer n'existe pas dans ${this.constructor.name}`,501)}async getNews(){throw new ApiError(`getNews n'existe pas dans ${this.constructor.name}`,501)}async getSubscribers(){throw new ApiError(`getSubscribers n'existe pas dans ${this.constructor.name}`,501)}async project(){throw new ApiError(`project n'existe pas dans ${this.constructor.name}`,501)}async poi(){throw new ApiError(`poi n'existe pas dans ${this.constructor.name}`,501)}async event(){throw new ApiError(`event n'existe pas dans ${this.constructor.name}`,501)}async badge(){throw new ApiError(`badge n'existe pas dans ${this.constructor.name}`,501)}async news(){throw new ApiError(`news n'existe pas dans ${this.constructor.name}`,501)}}class Comment extends BaseEntity{static entityType="comments";static entityTag="Comment";static SCHEMA_CONSTANTS=["ADD_COMMENTS"];static ADD_BLOCKS=new Map([["ADD_COMMENTS","addComments"]]);static UPDATE_BLOCKS=new Map([["ADD_COMMENTS","updateComments"]]);defaultFields={};removeFields=["contextId","contextType","parentCommentId","argval"];_transformServerData(e){return e.author&&(e.author=this._linkNestedEntity(e.author)),Array.isArray(e.replies)&&(e.replies=e.replies.map((e=>(e&&"object"==typeof e&&!e.type&&(e.type="comments",e.collection="comments"),this._linkNestedEntity(e))))),e}async get(){throw new ApiError(`get n'existe pas dans ${this.constructor.name}`,501)}async save(){const e=this.refresh;this.refresh=async()=>this._serverData;try{return await super.save()}finally{this.refresh=e}}_add=async e=>{if(!this._calledFromSave)throw new Error("utilisation invalide de _add, utilisez save");if(!this.parent?.id)throw new Error("Le parent doit être défini pour ajouter un commentaire.");if(""===e.text&&(e.text=" "),"comments"===this.parent.getEntityType()){e.parentCommentId=this.parent.id;let t=this.parent.parent;for(;t&&t.getEntityType&&"comments"===t.getEntityType();)t=t.parent;if(!t)throw new Error("Impossible de trouver l'entité racine pour le commentaire.");e.contextId=t.id,e.contextType=t.getEntityType()}else e.parentCommentId=e.parentCommentId||"",e.contextId=this.parent.id,e.contextType=this.parent.getEntityType();for(const[t,n]of Array.from(Comment.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}),[]);if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Comment.ADD_BLOCKS,n,r),t=e?.object?.id||e?.id?.$id||e?.id;!this.id&&t&&(this._draftData.id=t,this._setData(e.newComment,{forceInitialDraftReset:!0}))}}};_update=async e=>{if(!this._calledFromSave)throw new Error("utilisation invalide de _update, utilisez save");if(!this.parent?.id)throw new Error("Le parent doit être défini pour ajouter un commentaire.");""===e?.text&&(e.text=" "),e.params={text:e.text},delete e.text;let t=!1;const n=await this.callIsConnected((()=>this.endpointApi.updateComments(e)));return n?.comment&&this._setData(n.comment,{forceInitialDraftReset:!0}),t=!0,true};async addComments(e={}){return this.callIsConnected((()=>this.endpointApi.addComments(e)))}async updateComments(e={}){return this.callIsConnected((()=>this.endpointApi.updateComments(e)))}async delete(){if(!this.id)throw new ApiError("Vous devez fournir un id pour supprimer un commentaire.",400);const e={pathParams:{id:this.id}};await this.callIsConnected((()=>this.endpointApi.deleteComments(e))),Object.keys(this._draftData).forEach((e=>delete this._draftData[e])),Object.keys(this._serverData).forEach((e=>delete this._serverData[e])),this._isDeleted=!0}async comment(e={}){if(!this.isConnected)throw new ApiError("Vous devez être connecté.",401);return await this.entity("comments",e)}async addVote(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={collection:"comments",id:this.id,action:"vote",details:{status:e}};return await this.callIsConnected((()=>this.endpointApi.addVote(t)))}async addReportAbuse({reason:e,comment:t}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const n={collection:"comments",id:this.id,action:"reportAbuse",details:{reason:e,comment:t}};return await this.callIsConnected((()=>this.endpointApi.addReportAbuse(n)))}}class EndpointApi{apiClient;constructor(e){this.apiClient=e}get isConnected(){return this.apiClient.isConnected}get userId(){return this.apiClient.userId}async call(e,t={}){return this.apiClient.safeCall((async()=>{const n=await this.apiClient.callEndpoint(e,t);return this.apiClient.checkAndThrowApiResponseError(n),n.data}))}async callNoConnected(e,t={}){if(this.isConnected)throw new ApiAuthenticationError("Vous ne devez pas être connecté pour faire cette action.",403);return this.call(e,t)}async callIsConnected(e,t={}){if(!this.isConnected)throw new ApiAuthenticationError("Vous devez être connecté pour effectuer cette action.",401);return this.call(e,t)}async personRegister(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callNoConnected("PERSON_REGISTER",e)}async authenticateUrl(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callNoConnected("AUTHENTICATE_URL",e)}async refreshTokenUrl(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("REFRESH_TOKEN_URL",e)}async meInfoUrl(){return this.callIsConnected("ME_INFO_URL")}async passwordRecovery(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callNoConnected("PASSWORD_RECOVERY",e)}async serverExchangeToken(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("SERVER_EXCHANGE_TOKEN",e)}async changePassword(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("CHANGE_PASSWORD",e)}async deleteAccount(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_ACCOUNT",e)}async updateSettings(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_SETTINGS",e)}async updateBlockDescription(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_DESCRIPTION",e)}async updateBlockInfo(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_INFO",e)}async updateBlockSocial(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_SOCIAL",e)}async updateBlockLocality(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_LOCALITY",e)}async updateBlockSlug(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_SLUG",e)}async check(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("CHECK",e)}async profilImage(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("PROFIL_IMAGE",e)}async profilBanner(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("PROFIL_BANNER",e)}async getElementsAbout(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_ELEMENTS_ABOUT",e)}async multiconnect(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("MULTICONNECT",e)}async getNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_NEWS",e)}async getNewsById(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_NEWS_BY_ID",e)}async addNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_NEWS",e)}async addImageNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_IMAGE_NEWS",e)}async addFileNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_FILE_NEWS",e)}async deleteNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_NEWS",e)}async updateNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_NEWS",e)}async shareNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("SHARE_NEWS",e)}async getComments(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_COMMENTS",e)}async addComments(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_COMMENTS",e)}async deleteComments(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_COMMENTS",e)}async updateComments(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_COMMENTS",e)}async searchTags(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("SEARCH_TAGS",e)}async showVote(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("SHOW_VOTE",e)}async globalAutocomplete(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GLOBAL_AUTOCOMPLETE",e)}async cityAutocomplete(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("CITY_AUTOCOMPLETE",e)}async cityAutocompleteByCountry(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("CITY_AUTOCOMPLETE_BY_COUNTRY",e)}async suggestionInput(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("SUGGESTION_INPUT",e)}async getProjectsNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_PROJECTS_NO_ADMIN",e)}async getProjectsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_PROJECTS_ADMIN",e)}async getPoisNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_POIS_NO_ADMIN",e)}async getPoisAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_POIS_ADMIN",e)}async getOrganizationsNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_ORGANIZATIONS_NO_ADMIN",e)}async getOrganizationsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_ORGANIZATIONS_ADMIN",e)}async getMembersNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_MEMBERS_NO_ADMIN",e)}async getMembersAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_MEMBERS_ADMIN",e)}async getFriendsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_FRIENDS_ADMIN",e)}async getSubscriptions(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_SUBSCRIPTIONS",e)}async getSubscriptionsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_SUBSCRIPTIONS_ADMIN",e)}async getSubscribers(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_SUBSCRIBERS",e)}async getSubscribersAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_SUBSCRIBERS_ADMIN",e)}async getContributorsNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_CONTRIBUTORS_NO_ADMIN",e)}async getContributorsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_CONTRIBUTORS_ADMIN",e)}async getBadges(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_BADGES",e)}async getBadgesFilters(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_BADGES_FILTERS",e)}async connect(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("CONNECT",e)}async disconnect(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DISCONNECT",e)}async getElementsKey(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_ELEMENTS_KEY",e)}async getFavoris(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_FAVORIS",e)}async deleteFavoris(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_FAVORIS",e)}async addFavoris(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_FAVORIS",e)}async addOrganization(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_ORGANIZATION",e)}async addProject(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_PROJECT",e)}async addPoi(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_POI",e)}async addEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_EVENT",e)}async deletePoi(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_POI",e)}async deleteEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_EVENT",e)}async deleteElement(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_ELEMENT",e)}async addImageElement(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_IMAGE_ELEMENT",e)}async linkValidate(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("LINK_VALIDATE",e)}async searchMemberAutocomplete(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("SEARCH_MEMBER_AUTOCOMPLETE",e)}async getNotifications(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_NOTIFICATIONS",e)}async getNotificationsCount(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_NOTIFICATIONS_COUNT",e)}async notificationUpdate(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("NOTIFICATION_UPDATE",e)}async removeAllNotifications(){return this.callIsConnected("REMOVE_ALL_NOTIFICATIONS")}async markNotificationAsRead(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("MARK_NOTIFICATION_AS_READ",e)}async activitypubSearch(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("ACTIVITYPUB_SEARCH",e)}async activitypubLink(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ACTIVITYPUB_LINK",e)}async activitypubGetCommunity(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("ACTIVITYPUB_GET_COMMUNITY",e)}async getBadge(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_BADGE",e)}async getEmetteurBadges(){return this.call("GET_EMETTEUR_BADGES")}async addBadges(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_BADGES",e)}async assignBadges(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ASSIGN_BADGES",e)}async getEvents(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_EVENTS",e)}async shareEvents(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("SHARE_EVENTS",e)}async inviteEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("INVITE_EVENT",e)}async follow(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("FOLLOW",e)}async getCostumJson(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_COSTUM_JSON",e)}async globalAutocompleteCostum(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GLOBAL_AUTOCOMPLETE_COSTUM",e)}async costumEventRequestActors(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_ACTORS",e)}async costumEventRequestSubevents(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_SUBEVENTS",e)}async costumEventRequestElementEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_ELEMENT_EVENT",e)}async costumEventRequestCategories(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_CATEGORIES",e)}async costumEventRequestDates(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_DATES",e)}async costumEventRequestEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_EVENT",e)}async costumEventRequestLinkTlToEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_LINK_TL_TO_EVENT",e)}async costumEventRequestLoadContextTag(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_LOAD_CONTEXT_TAG",e)}async getGallery(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_GALLERY",e)}async getAttendeesNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_ATTENDEES_NO_ADMIN",e)}async getAttendeesAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_ATTENDEES_ADMIN",e)}async coformAnswersSearch(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COFORM_ANSWERS_SEARCH",e)}async coformAnswersById(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COFORM_ANSWERS_BY_ID",e)}async addVote(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_VOTE",e)}async addReportAbuse(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_REPORT_ABUSE",e)}async updatePathValue(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_PATH_VALUE",e)}async deleteDocumentByContext(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_DOCUMENT_BY_CONTEXT",e)}async demoteAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DEMOTE_ADMIN",e)}}function V(e){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,{type:t?.type??"",name:t?.name}]))):{}}function G(e){return(t,n)=>n?.socialNetwork?.[e]}class Event extends BaseEntity{static entityType="events";static entityTag="Event";static SCHEMA_CONSTANTS=["ADD_EVENT","UPDATE_BLOCK_SLUG","PROFIL_IMAGE"];static ADD_BLOCKS=new Map([["ADD_EVENT","addEvent"],["PROFIL_IMAGE","updateImageProfil"]]);static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];transforms={parent:V,organizer:V};_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Event.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Event.ADD_BLOCKS,n,r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this.isAdmin({checkHierarchy:!0}))throw new ApiError("Vous n'avez pas les droits pour modifier cet événement",403);if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);let t=!1;const n=this._extractAllValidFieldsFromSchema(this.apiClient,"ADD_EVENT",{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);n&&Object.keys(n).length>0&&(await this.addEvent(n),t=!0),e.id&&delete e.id;for(const[n,r]of Array.from(Event.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(Event.UPDATE_BLOCKS,r,o),t=!0)}return t};async addEvent(e={}){return this.isMe||e.organizer||!this.parent||(e.organizer={},e.organizer[`${this.parent.id}`]={type:this.parent.getEntityType(),name:this.parent.name}),this.callIsConnected((()=>this.endpointApi.addEvent(e)))}async getOrganizations(){throw new ApiError(`getOrganizations n'existe pas dans ${this.constructor.name}`,501)}async getProjects(){throw new ApiError(`getProjects n'existe pas dans ${this.constructor.name}`,501)}async getEvents(){throw new ApiError(`getEvents - les sous-events ne sont pas encore implémentés dans ${this.constructor.name}`,501)}async getPois(){throw new ApiError(`getPois n'existe pas dans ${this.constructor.name}`,501)}async getBadgesIssuer(){throw new ApiError(`getBadgesIssuer n'existe pas dans ${this.constructor.name}`,501)}async getNews(e={}){return super.getNews(e)}async getSubscribers(e={}){return super.getSubscribers(e)}async getAttendees(e={},t={}){e.searchType=this._getDefaultFromEndpoint("GET_ATTENDEES_NO_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getAttendees",restoredState:t?.restoredState,finalizer:async e=>{const{toBeValidated:n,isAdmin:r,isInviting:o,isAdminPending:i,roles:s=[]}=t;this.isMe?(e.pathParams={id:this.id},e.filters=this._buildLinkFilters(this.id,{linkType:"events",toBeValidated:n,isAdmin:r,isAdminPending:i,isInviting:o,roles:s})):(delete e?.pathParams,e.filters=this._buildLinkFilters(this.id,{linkType:"events",toBeValidated:!1,isAdmin:r,isInviting:o,roles:s}));return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getAttendeesAdmin(e))):()=>this.endpointApi.getAttendeesNoAdmin(e))()}}).next()}async project(){throw new ApiError(`project n'existe pas dans ${this.constructor.name}`,501)}async poi(){throw new ApiError(`poi n'existe pas dans ${this.constructor.name}`,501)}async event(){throw new ApiError(`les sous-events ne sont pas encore implémentés dans ${this.constructor.name}`,501)}async badge(){throw new ApiError(`badge n'existe pas dans ${this.constructor.name}`,501)}async news(e={}){return super.news(e)}async requestToJoin(){return super.requestToJoin()}async acceptInvitation(){return super.acceptInvitation()}async leave(){return super.leave()}async follow(){return super.follow()}async unfollow(){return super.unfollow()}}class News extends BaseEntity{static entityType="news";static entityTag="News";static SCHEMA_CONSTANTS=["ADD_NEWS"];static ADD_BLOCKS=new Map([["ADD_NEWS","addNews"]]);static UPDATE_BLOCKS=new Map([["ADD_NEWS","updateNews"]]);defaultFields={};removeFields=["parentId","parentType"];transforms={scope:e=>e?.type,mentions:e=>Array.isArray(e)?e.map((e=>({...e,count:parseInt(e.count)}))):[],mediaImg:e=>{const t=e?.images?.map((e=>e.id)).filter(Boolean)||[];return t.length>0?{countImages:t.length,images:t}:{countImages:0,images:[]}},mediaFile:e=>{const t=e?.files?.map((e=>e.id)).filter(Boolean)||[];return t.length>0?{countFiles:t.length,files:t}:{countFiles:0,files:[]}}};_transformServerData(e){return e.author&&(e.author=this._linkNestedEntity(e.author)),e.target&&(e.target=this._linkNestedEntity(e.target)),e.lastAuthorShare&&(e.lastAuthorShare=this._linkNestedEntity(e.lastAuthorShare)),Array.isArray(e.sharedBy)&&(e.sharedBy=e.sharedBy.map((e=>this._linkNestedEntity(e)))),e}async get(){if(!this.id)throw new ApiError("Impossible de rafraîchir sans ID.",400);const e=this.id,t=await this.endpointApi.getNewsById({ids:[e]});if(t&&Array.isArray(t)&&1===t.length){const e=t[0];return this._setData(e,{forceInitialDraftReset:!0}),this.serverData}throw new ApiError(`Aucune actualité trouvée pour l'ID ${this.id}`,404)}_add=async e=>{if(!this._calledFromSave)throw new Error("utilisation invalide de _add, utilisez save");""===e.text&&(e.text=" "),this.parent&&(e.parentId=this.parent.id,e.parentType=this.parent.getEntityType());for(const[t,n]of Array.from(News.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}),[]);if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(News.ADD_BLOCKS,n,r);!this.id&&e?.object?.id&&(this._draftData.id=e.object.id)}}};_update=async e=>{if(!this._calledFromSave)throw new Error("utilisation invalide de _update, utilisez save");e.id&&delete e.id,""===e?.text&&(e.text=" "),this.parent&&(e.parentId=this.parent.id,e.parentType=this.parent.getEntityType()),e.idNews=this.id;let t=!1;return await this.callIsConnected((()=>this.endpointApi.updateNews(e))),t=!0,true};async addNews(e={}){return this.callIsConnected((()=>this.endpointApi.addNews(e)))}async updateNews(e={}){return this.callIsConnected((()=>this.endpointApi.updateNews(e)))}async addMention({slug:e,id:t}){try{if(!e&&!t)throw new ApiError("Vous devez fournir un slug ou un id pour ajouter une mention.",400);const n=await this.entity("citoyens",{id:t,slug:e}),r=n.serverData;if(this._draftData.mentions||(this._draftData.mentions=[]),this._draftData.mentions.find((e=>e.id===r.id)))return this._draftData.mentions=this._draftData.mentions.map((e=>(e.id===r.id&&(e.count+=1),e))),this._draftData.mentions;const o={id:r.id,slug:r.slug,type:n.getEntityType(),name:r.name,value:r.name,count:1};return this._draftData.mentions.push(o),this._draftData.mentions}catch(e){throw this.apiClient._logger.error("Erreur lors de l'ajout de la mention :",e),e}}async addImage(e){const t=await this._validateImage(e),n={pathParams:{folder:this.parent?.getEntityType(),ownerId:this.parent?.id},newsImage:t},r=await this.callIsConnected((()=>this.endpointApi.addImageNews(n)));return this._draftData.mediaImg?(this._draftData.mediaImg.countImages=this._draftData.mediaImg.countImages+1,this._draftData.mediaImg.images.push(r.id)):this._draftData.mediaImg={countImages:1,images:[r.id]},r}async addFile(e){const t=await this._validateFile(e),n={pathParams:{folder:this.parent?.getEntityType(),ownerId:this.parent?.id},newsFile:t},r=await this.callIsConnected((()=>this.endpointApi.addFileNews(n)));return this._draftData.mediaFile?(this._draftData.mediaFile.countFiles=this._draftData.mediaFile.countFiles+1,this._draftData.mediaFile.files.push(r.id)):this._draftData.mediaFile={countFiles:1,files:[r.id]},r}async delete(){if(!this.id)throw new ApiError("Vous devez fournir un id pour supprimer une news.",400);const e={pathParams:{id:this.id},isLive:!1};await this.callIsConnected((()=>this.endpointApi.deleteNews(e))),Object.keys(this._draftData).forEach((e=>delete this._draftData[e])),Object.keys(this._serverData).forEach((e=>delete this._serverData[e])),this._isDeleted=!0}async comment(e={}){if(!this.isConnected)throw new ApiError("Vous devez être connecté.",401);return await this.entity("comments",e)}async getComments(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const e={pathParams:{type:"news",id:this.id}},t=await this.endpointApi.getComments(e);if(!Array.isArray(t))throw new ApiResponseError("Erreur lors de la récupération des commentaires.",500,t);const n=this._linkEntities(t);return this._createFilteredProxy(n)}async addVote(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={collection:"news",id:this.id,action:"vote",details:{status:e}};return await this.callIsConnected((()=>this.endpointApi.addVote(t)))}async addReportAbuse({reason:e,comment:t}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const n={collection:"news",id:this.id,action:"reportAbuse",details:{reason:e,comment:t}};return await this.callIsConnected((()=>this.endpointApi.addReportAbuse(n)))}async shareNews({childId:e,childType:t,comment:n}={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);if(!this.parent?.id)throw new ApiError("Le parent doit être défini pour partager une news",400);const r=e??this.userId,o=t??"citoyens",i=["citoyens","projects","organizations"];if(!i.includes(o))throw new ApiError(`Le type de cible "${o}" n'est pas valide. Types autorisés: ${i.join(", ")}`,400);if(this.parent.id===this.userId&&r===this.userId)throw new ApiError("Vous ne pouvez pas partager votre propre news à vous-même",400);const s={parentId:this.id,parentType:"news",connectType:"share",childType:o,childId:r,comment:n};return await this.callIsConnected((()=>this.endpointApi.shareNews(s)))}isAuthor(e){const t=e?.silent??!0;try{if(!this.isMe)throw new ApiError("Vous devez être connecté pour vérifier l'auteur.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.serverData)throw new ApiError("Aucune donnée serveur disponible.",404);if(!this.userId)throw new ApiError("Utilisateur non connecté.",401)}catch(e){if(t)return!1;throw e}const n=this.serverData.author;if(!n)return!1;let r;return"serverData"in n&&n.serverData&&"object"==typeof n.serverData&&"id"in n.serverData?r=n.serverData.id:"id"in n&&(r=n.id),Boolean(r&&this.userId===r)}}class Organization extends BaseEntity{static entityType="organizations";static entityTag="Organization";static SCHEMA_CONSTANTS=["ADD_ORGANIZATION","UPDATE_BLOCK_DESCRIPTION","UPDATE_BLOCK_INFO","UPDATE_BLOCK_SOCIAL","UPDATE_BLOCK_LOCALITY","UPDATE_BLOCK_SLUG","PROFIL_IMAGE","VIRTUAL_OPENING_HOURS"];static VIRTUAL_SCHEMAS={VIRTUAL_OPENING_HOURS:{type:"object",properties:{openingHours:{type:"array",description:"Horaires d'ouverture (7 jours de la semaine)",minItems:7,maxItems:7,items:{oneOf:[{type:"string",const:""},{type:"object",properties:{dayOfWeek:{type:"string",enum:["Mo","Tu","We","Th","Fr","Sa","Su"],description:"Jour de la semaine"},hours:{type:"array",description:"Liste des créneaux horaires",items:{type:"object",properties:{opens:{type:"string",pattern:"^([01]\\d|2[0-3]):[0-5]\\d$",description:"Heure d'ouverture (HH:MM)"},closes:{type:"string",pattern:"^([01]\\d|2[0-3]):[0-5]\\d$",description:"Heure de fermeture (HH:MM)"}},required:["opens","closes"],additionalProperties:!1}}},required:["dayOfWeek","hours"],additionalProperties:!1}]}}}}};static CUSTOM_FIELD_HANDLERS=new Map([["openingHours",{updateMethod:"updateOpeningHours",schemaConstant:"VIRTUAL_OPENING_HOURS"}]]);static ADD_BLOCKS=new Map([["ADD_ORGANIZATION","addOrganization"],["PROFIL_IMAGE","updateImageProfil"]]);static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_DESCRIPTION","updateDescription"],["UPDATE_BLOCK_SOCIAL","updateSocial"],["UPDATE_BLOCK_LOCALITY","updateLocality"],["UPDATE_BLOCK_INFO","updateInfo"],["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];transforms={github:G("github"),gitlab:G("gitlab"),facebook:G("facebook"),twitter:G("twitter"),instagram:G("instagram"),diaspora:G("diaspora"),mastodon:G("mastodon"),telegram:G("telegram"),signal:G("signal")};_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Organization.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Organization.ADD_BLOCKS,n,r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour modifier cette organisation",403);if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;const n=Organization.CUSTOM_FIELD_HANDLERS;if(n){const r=new Set;for(const[o,i]of n)o in e&&this._hasFieldChanged(o)&&(await this._invokeCustomFieldHandler(i.updateMethod,e[o],o),r.add(o),t=!0);r.forEach((t=>delete e[t]))}for(const[n,r]of Array.from(Organization.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(Organization.UPDATE_BLOCKS,r,o),t=!0)}return t};async addOrganization(e){return this.callIsConnected((()=>this.endpointApi.addOrganization(e)))}async getOrganizations(){throw new ApiError("getOrganizations n'existe pas dans Organization",404)}async getProjects(e={}){return super.getProjects(e)}async getEvents(e={}){return super.getEvents(e)}async getPois(e={}){return super.getPois(e)}async getBadgesIssuer(e={}){return super.getBadgesIssuer(e)}async getNews(e={}){return super.getNews(e)}async getSubscribers(e={}){return super.getSubscribers(e)}async getMembers(e={},t={}){if(!this.id)throw new ApiError("L'organisation n'est pas définie, impossible de récupérer les membres",400);const n=this.id;e.searchType=this._getDefaultFromEndpoint("GET_MEMBERS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getMembers",restoredState:t?.restoredState,finalizer:async e=>{const{toBeValidated:r,isAdmin:o,isAdminPending:i,isInviting:s,roles:a=[]}=t;this.isMe?(e.pathParams={id:this.id},e.filters=this._buildLinkFilters(n,{linkType:"memberOf",toBeValidated:r,isAdmin:o,isAdminPending:i,isInviting:s,roles:a})):(delete e?.pathParams,e.filters=this._buildLinkFilters(n,{linkType:"memberOf",toBeValidated:!1,isAdmin:o,isInviting:s,roles:a}));return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getMembersAdmin(e))):()=>this.endpointApi.getMembersNoAdmin(e))()}}).next()}async getGallery(e={}){return super.getGallery(e)}async project(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un projet dans cette organisation",403);return super.project(e)}async poi(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un poi dans cette organisation",403);return super.poi(e)}async event(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un event dans cette organisation",403);return super.event(e)}async badge(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un badge dans cette organisation",403);return super.badge(e)}async news(e={}){return super.news(e)}async updateOpeningHours(e){if(!this.id)throw new ApiError("L'organisation n'a pas d'ID, impossible de mettre à jour les horaires d'ouverture.",400);return this.endpointApi.updatePathValue({id:this.id,collection:"organizations",path:"openingHours",value:e})}async requestToJoin(){return super.requestToJoin()}async requestToJoinAdmin(){return super.requestToJoinAdmin()}async acceptInvitation(){return super.acceptInvitation()}requestPromoteToAdmin(){return super.requestPromoteToAdmin()}async leave(){return super.leave()}async follow(){return super.follow()}async unfollow(){return super.unfollow()}async getCostumJson(){return super.getCostumJson()}async searchCostum(e){return super.searchCostum(e)}async coformAnswersSearch(e){return super.coformAnswersSearch(e)}}class Poi extends BaseEntity{static entityType="poi";static entityTag="Poi";static SCHEMA_CONSTANTS=["ADD_POI","UPDATE_BLOCK_DESCRIPTION","UPDATE_BLOCK_INFO","UPDATE_BLOCK_LOCALITY","UPDATE_BLOCK_SLUG","PROFIL_IMAGE"];static ADD_BLOCKS=new Map([["ADD_POI","addPoi"],["PROFIL_IMAGE","updateImageProfil"]]);static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_DESCRIPTION","updateDescription"],["UPDATE_BLOCK_LOCALITY","updateLocality"],["UPDATE_BLOCK_INFO","updateInfo"],["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Poi.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Poi.ADD_BLOCKS,n,r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this.isAuthor())throw new ApiError("Vous n'avez pas les droits pour modifier ce POI",403);if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;for(const[n,r]of Array.from(Poi.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(Poi.UPDATE_BLOCKS,r,o),t=!0)}return t};async addPoi(e={}){return!this.isMe&&this.parent&&(e.parent={},e.parent[`${this.parent.id}`]={type:this.parent.getEntityType(),name:this.parent.name}),this.callIsConnected((()=>this.endpointApi.addPoi(e)))}async getOrganizations(){throw new ApiError(`getOrganizations n'existe pas dans ${this.constructor.name}`,501)}async getProjects(){throw new ApiError(`getProjects n'existe pas dans ${this.constructor.name}`,501)}async getEvents(){throw new ApiError(`getEvents n'existe pas dans ${this.constructor.name}`,501)}async getPois(){throw new ApiError(`getPois n'existe pas dans ${this.constructor.name}`,501)}async getBadgesIssuer(){throw new ApiError(`getBadgesIssuer n'existe pas dans ${this.constructor.name}`,501)}async getNews(){throw new ApiError(`getNews n'existe pas dans ${this.constructor.name}`,501)}async getSubscribers(e={}){return super.getSubscribers(e)}async project(){throw new ApiError(`project n'existe pas dans ${this.constructor.name}`,501)}async poi(){throw new ApiError(`poi n'existe pas dans ${this.constructor.name}`,501)}async event(){throw new ApiError(`event n'existe pas dans ${this.constructor.name}`,501)}async badge(){throw new ApiError(`badge n'existe pas dans ${this.constructor.name}`,501)}async news(){throw new ApiError(`news n'existe pas dans ${this.constructor.name}`,501)}async follow(){return super.follow()}async unfollow(){return super.unfollow()}}class Project extends BaseEntity{static entityType="projects";static entityTag="Project";static SCHEMA_CONSTANTS=["ADD_PROJECT","UPDATE_BLOCK_DESCRIPTION","UPDATE_BLOCK_INFO","UPDATE_BLOCK_SOCIAL","UPDATE_BLOCK_LOCALITY","UPDATE_BLOCK_SLUG","PROFIL_IMAGE"];static ADD_BLOCKS=new Map([["ADD_PROJECT","addProject"],["PROFIL_IMAGE","updateImageProfil"]]);static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_DESCRIPTION","updateDescription"],["UPDATE_BLOCK_SOCIAL","updateSocial"],["UPDATE_BLOCK_LOCALITY","updateLocality"],["UPDATE_BLOCK_INFO","updateInfo"],["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];transforms={github:G("github"),gitlab:G("gitlab"),facebook:G("facebook"),twitter:G("twitter"),instagram:G("instagram"),diaspora:G("diaspora"),mastodon:G("mastodon"),telegram:G("telegram"),signal:G("signal"),parent:V};_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Project.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Project.ADD_BLOCKS,n,r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour modifier ce projet",403);if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;for(const[n,r]of Array.from(Project.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(Project.UPDATE_BLOCKS,r,o),t=!0)}return t};async addProject(e={}){return!this.isMe&&this.parent&&(e.parent={},e.parent[`${this.parent.id}`]={type:this.parent.getEntityType(),name:this.parent.name}),this.callIsConnected((()=>this.endpointApi.addProject(e)))}async getOrganizations(){throw new ApiError(`getOrganizations n'existe pas dans ${this.constructor.name}`,501)}async getProjects(e={}){return super.getProjects(e)}async getEvents(e={}){return super.getEvents(e)}async getPois(e={}){return super.getPois(e)}async getBadgesIssuer(e={}){return super.getBadgesIssuer(e)}async getNews(e={}){return super.getNews(e)}async getSubscribers(e={}){return super.getSubscribers(e)}async getContributors(e={},t={}){e.searchType=this._getDefaultFromEndpoint("GET_CONTRIBUTORS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getContributors",restoredState:t?.restoredState,finalizer:async e=>{const{toBeValidated:n,isAdmin:r,isInviting:o,isAdminPending:i,roles:s=[]}=t;this.isMe?(e.pathParams={id:this.id},e.filters=this._buildLinkFilters(this.id,{linkType:"projects",toBeValidated:n,isAdmin:r,isAdminPending:i,isInviting:o,roles:s})):(delete e?.pathParams,e.filters=this._buildLinkFilters(this.id,{linkType:"projects",toBeValidated:!1,isAdmin:r,isInviting:o,roles:s}));return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getContributorsAdmin(e))):()=>this.endpointApi.getContributorsNoAdmin(e))()}}).next()}async getGallery(e={}){return super.getGallery(e)}async project(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un projet dans ce projet",403);return super.project(e)}async poi(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un POI dans ce projet",403);return super.poi(e)}async event(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un événement dans ce projet",403);return super.event(e)}async badge(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un badge dans ce projet",403);return super.badge(e)}async news(e={}){return super.news(e)}async requestToJoin(){return super.requestToJoin()}async requestToJoinAdmin(){return super.requestToJoinAdmin()}async acceptInvitation(){return super.acceptInvitation()}requestPromoteToAdmin(){return super.requestPromoteToAdmin()}async leave(){return super.leave()}async follow(){return super.follow()}async unfollow(){return super.unfollow()}}class User extends BaseEntity{static entityType="citoyens";static entityTag="User";static SCHEMA_CONSTANTS=["UPDATE_BLOCK_DESCRIPTION","UPDATE_BLOCK_INFO","UPDATE_BLOCK_SOCIAL","UPDATE_BLOCK_LOCALITY","UPDATE_BLOCK_SLUG","PROFIL_IMAGE"];static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_DESCRIPTION","updateDescription"],["UPDATE_BLOCK_SOCIAL","updateSocial"],["UPDATE_BLOCK_LOCALITY","updateLocality"],["UPDATE_BLOCK_INFO","updateInfo"],["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];transforms={github:G("github"),gitlab:G("gitlab"),facebook:G("facebook"),twitter:G("twitter"),instagram:G("instagram"),diaspora:G("diaspora"),mastodon:G("mastodon"),telegram:G("telegram"),signal:G("signal")};constructor(e,t,n){if(!n.EndpointApi)throw new ApiError("EndpointApi class must be injected to avoid circular dependency.",500);if(!t?.id&&!t?.slug)throw new ApiError("Vous devez fournir un id ou un slug pour créer un User.",400);if(!n.Organization)throw new ApiError("Organization class must be injected.",500);if(!n.Project)throw new ApiError("Project class must be injected.",500);if(!n.Event)throw new ApiError("Event class must be injected.",500);if(!n.Poi)throw new ApiError("Poi class must be injected.",500);if(!n.Badge)throw new ApiError("Badge class must be injected.",500);if(!n.News)throw new ApiError("News class must be injected.",500);super(e,t,n)}get slug(){return this._draftData.slug||null}get isMe(){return this.isConnected&&this.userId===this.id}get parentIsMe(){return super.isMe}get isActingUser(){return this.parentIsMe&&!this.isMe}getEntityType(){return"citoyens"}async get(){return this.apiClient.safeCall((async()=>{if(this.isMe){const e=await this.endpointApi.meInfoUrl();return this._setData(e,{forceInitialDraftReset:!0}),e}{const e=await this._getPublicProfile();return this._setData(e,{forceInitialDraftReset:!0}),e}}))}async changePassword(e){return this.callIsMe((()=>this.endpointApi.changePassword(e)))}async delete(e){return this.callIsMe((()=>this.endpointApi.deleteAccount(e)))}async save(){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour sauvegarder.",401);return await super.save()}_add=async()=>{throw new ApiError("Vous ne pouvez pas ajouter un utilisateur par ce moyen.",403)};_update=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;for(const[n,r]of Array.from(User.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(User.UPDATE_BLOCKS,r,o),t=!0)}return t};static fromServerData(e,t,n){const r=new this(t,e,n);return e&&"object"==typeof e&&Object.keys(e).length>0&&"function"==typeof r._setData&&r._setData(e),r}async updateSettings(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour les paramètres.",401);const t=await super.updateSettings(e);return await this.refresh(),t}async updateDescription(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour la description.",401);return super.updateDescription(e)}async updateInfo(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour les informations.",401);return super.updateInfo(e)}async updateSocial(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour les réseaux sociaux.",401);return super.updateSocial(e)}async updateLocality(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour la localité.",401);return super.updateLocality(e)}async updateSlug(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour le slug.",401);return super.updateSlug(e)}async updateImageProfil(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour l'image de profil.",401);return super.updateImageProfil(e)}async updateImageBanner(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour l'image de bannière.",401);return super.updateImageBanner(e)}async getOrganizations(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_ORGANIZATIONS_NO_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getOrganizations",restoredState:t?.restoredState,finalizer:async e=>{delete e?.pathParams;const t=this.isMe?()=>this.callIsMe((()=>this.endpointApi.getOrganizationsAdmin(e))):()=>this.endpointApi.getOrganizationsNoAdmin(e);return this.isMe||e.filters||(e.filters={[`links.members.${this.id}`]:{$exists:!0},[`links.members.${this.id}.toBeValidated`]:{$exists:!1},[`links.members.${this.id}.isInviting`]:{$exists:!1}}),t()}}).next()}async getProjects(e={}){return super.getProjects(e)}async getEvents(e={}){return super.getEvents(e)}async getPois(e={}){return super.getPois(e)}async getNews(e={}){return super.getNews(e)}async getFriends(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_FRIENDS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getFriends",restoredState:t?.restoredState,finalizer:async e=>(delete e?.pathParams,!this.isMe&&this.id&&(e.pathParams={id:this.id}),this.endpointApi.getFriendsAdmin(e))}).next()}async getSubscriptions(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_SUBSCRIPTIONS","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getSubscriptions",restoredState:t?.restoredState,finalizer:async e=>{delete e?.pathParams;const t=this.isMe?()=>this.callIsMe((()=>this.endpointApi.getSubscriptionsAdmin(e))):()=>this.endpointApi.getSubscriptions(e);return this.isMe||e.filters||(e.filters={[`links.followers.${this.id}`]:{$exists:!0}}),t()}}).next()}async getSubscribers(e={}){return super.getSubscribers(e)}async getBadgesIssuer(e={}){return super.getBadgesIssuer(e)}async getBadges(e={}){return await this.linkEntitiesFromServerData("badges",e)}async getGallery(e={}){return super.getGallery(e)}async user(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur",401);if(!e.id&&!e.slug)throw new ApiError("Vous devez fournir un id ou un slug pour créer un User.",400);const t=this.deps,n=new User(this,e,t);return await n.get(),n}async organization(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer une organisation.",401);return super.organization(e)}async project(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un projet.",401);return super.project(e)}async news(e={}){if(!("id"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer une actualité.",401);return super.news(e)}async poi(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un POI.",401);return super.poi(e)}async event(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un événement.",401);return super.event(e)}async badge(e={}){if(!("id"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un badge.",401);return super.badge(e)}async sendFriendRequest(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour envoyer une demande d'amis.",401);if(this._checkLinkableEntity(),!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const{connectTypeConnect:e}=this._getLinkMeta(),t=this._getLinkFromConnectedUser();if(!t){const t={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id,connectType:e},n=await this.endpointApi.connect(t);return await(this.userContext?.refresh()),n}if(t.isInviting&&t.invitorId===this.id)return this.acceptFriendRequest();if(t.isInviting&&t.invitorId===this.userId)throw new ApiError("Vous avez déjà envoyé une demande d'amis à cet utilisateur.",403);throw new ApiError("Vous êtes déjà connecté à cette entité.",409)}async acceptFriendRequest(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour accepter une demande d'amitié.",401);if(this._checkLinkableEntity(),!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const e=this._getLinkFromConnectedUser();if(e?.isInviting&&e.invitorId===this.id){const e={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id,linkOption:"isInviting"},t=await this.endpointApi.linkValidate(e);return await(this.userContext?.refresh()),t}throw new ApiError("Vous n'avez pas d'invitation à valider.",404)}async removeFriend(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour supprimer un ami.",401);if(this._checkLinkableEntity(),!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const{connectTypeDisconnect:e}=this._getLinkMeta();if(!this._getLinkFromConnectedUser())throw new ApiError("Vous n'êtes pas connecté à cette entité.",404);const t={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id,connectType:e},n=await this.endpointApi.disconnect(t);return await(this.userContext?.refresh()),n}async requestToJoin(){throw new ApiError("l'utilisation de requestToJoin n'est pas autorisée sur un utilisateur.",403)}async requestToJoinAdmin(){throw new ApiError("l'utilisation de requestToJoinAdmin n'est pas autorisée sur un utilisateur.",403)}async acceptInvitation(){throw new ApiError("l'utilisation de acceptInvitation n'est pas autorisée sur un utilisateur.",403)}async leave(){throw new ApiError("l'utilisation de leave n'est pas autorisée sur un utilisateur.",403)}async follow(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour suivre un utilisateur.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!(this.userContext?.serverData?.links?.follows?.[this.id]||null)){const e={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id},t=await this.endpointApi.follow(e);return await(this.userContext?.refresh()),t}throw new ApiError("Vous êtes déjà abonné à cet utilisateur.",409)}async unfollow(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour vous désabonner d'un utilisateur.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(this.userContext?.serverData?.links?.follows?.[this.id]||null){const e={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id,connectType:"followers"},t=await this.endpointApi.disconnect(e);return await(this.userContext?.refresh()),t}throw new ApiError("Vous n'êtes pas abonné à cet utilisateur.",404)}isFriend(){if(!this.isActingUser)throw new ApiError("Vous devez être connecté pour vérifier si vous êtes ami.",401);this._assertEntityType("citoyens");const e=this._getLinkFromConnectedUser();return this._validateUserLink(e)}isFollower(){if(!this.isActingUser)throw new ApiError("Vous devez être connecté pour vérifier si il vous suit.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);return this._assertEntityType("citoyens"),this._isLinked("followers")}isFollowing(){if(!this.isActingUser)throw new ApiError("Vous devez être connecté pour vérifier si vous le suivez.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);return this._assertEntityType("citoyens"),this._isLinked("follows")}async entityBySlug(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer cet entité.",401);return super.entityBySlug(e)}_validateBasePreconditions(e,t){if(!this.userId)throw new ApiError(`Vous devez être connecté pour ${e}.`,401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.parent?.id)throw new ApiError("L'entité parente n'est pas enregistrée.",404);if(!t.includes(this.parent.getEntityType()))throw new ApiError(`L'entité doit être de type : ${t.join(", ")}, reçu : ${this.parent.getEntityType()}`,400)}_validateMemberPreconditions(e,t){if(this._validateBasePreconditions(e,t),!this.parent?.id)throw new ApiError("L'entité parente n'est pas enregistrée.",404);const n=this.parent.getEntityType();if("events"===n)return;let r=!1;switch(n){case"organizations":r=this.parent.isMember();break;case"projects":r=this.parent.isContributor();break;default:r=!1}if(!r){throw new ApiError(`Vous devez être ${{organizations:"membre",projects:"contributeur"}[n]||"membre"} pour effectuer cette action.`,401)}}_validateAdminPreconditions(e,t){if(this._validateMemberPreconditions(e,t),!this.parent?.isAdmin())throw new ApiError("Vous devez être administrateur pour effectuer cette action.",401)}_getParentLinkForUser(){const{connectTypeDisconnect:e}=this.parent._getLinkMeta(),t=this.id;return t&&this.parent?.serverData?.links?.[e]?.[t]||null}_getValidatedParentLink(e,t,n){const r=n?.silent??!0;try{this._validateBasePreconditions(e,t)}catch(e){if(r)return null;throw e}return this._getParentLinkForUser()}async _refreshWithParent(){await this.refresh(),this.parent&&await this.parent.refresh()}isAdmin(e){const t=this._getValidatedParentLink("isAdmin",["organizations","projects"],{silent:e?.silent});return this._validateUserLink(t)&&!0===t?.isAdmin}isMember(e){const t=this._getValidatedParentLink("isMember",["organizations"],{silent:e?.silent});return this._validateUserLink(t)}isContributor(e){const t=this._getValidatedParentLink("isContributor",["projects"],{silent:e?.silent});return this._validateUserLink(t)}isAttendee(e){const t=this._getValidatedParentLink("isAttendee",["events"],{silent:e?.silent});return this._validateUserLink(t)}isInviting(e){const t=this._getValidatedParentLink("isInviting",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.isInviting}isInvitingFriend(e){const t=this._getValidatedUserLink("isInvitingFriend",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.isInviting}isInvitingAdmin(e){const t=this._getValidatedParentLink("isInvitingAdmin",["organizations","projects"],{silent:e?.silent});return!!t&&((!0===t.isAdminInviting||!0===t.isInviting)&&!0===t.isAdmin)}isAdminPending(e){const t=this._getValidatedParentLink("isAdminPending",["organizations","projects"],{silent:e?.silent});return!!t&&(!0===t.isAdmin&&!0===t.isAdminPending)}isToBeValidated(e){const t=this._getValidatedParentLink("isToBeValidated",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.toBeValidated}isToBeValidatedFriend(e){const t=this._getValidatedUserLink("isToBeValidatedFriend",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.toBeValidated}async sendRequestToJoinParent({admin:e}={admin:!1}){e?this._validateAdminPreconditions("sendRequestToJoinParent",["organizations","projects"]):this._validateMemberPreconditions("sendRequestToJoinParent",["organizations","projects","events"]);const{connectTypeConnect:t}=this.parent._getLinkMeta(),n=this._getParentLinkForUser();if(!n){const n=this.parent.getEntityType(),r={childId:this.id,childType:"citoyens",parentType:n,parentId:this.parent.id,connectType:e?"admin":t},o=await this.callIsConnected((()=>this.endpointApi.connect(r)));return await this._refreshWithParent(),o}if(n.isInviting||n?.isAdminInviting)throw new ApiError("Une invitation est déjà en attente d'acceptation.",400);throw new ApiError("Vous êtes déjà connecté à cette entité.",400)}async validateMemberRequest(){this._validateAdminPreconditions("validateMemberRequest",["organizations","projects"]);const e=this._getParentLinkForUser();if(!e?.toBeValidated)throw new ApiError("Cet utilisateur n'a pas de demande en attente de validation.",400);const t=this.parent.getEntityType(),n={childId:this.id,childType:"citoyens",parentType:t,parentId:this.parent.id,linkOption:"toBeValidated"},r=await this.callIsConnected((()=>this.endpointApi.linkValidate(n)));return await this._refreshWithParent(),r}async validateAdminRequest(){this._validateAdminPreconditions("validateAdminRequest",["organizations","projects"]);const e=this._getParentLinkForUser();if(!e?.isAdminPending)throw new ApiError("Cet utilisateur n'a pas de demande d'admin en attente.",400);const t=this.parent.getEntityType(),n={childId:this.id,childType:"citoyens",parentType:t,parentId:this.parent.id,linkOption:"isAdminPending"},r=await this.callIsConnected((()=>this.endpointApi.linkValidate(n)));return await this._refreshWithParent(),r}async removeFromParent(){this._validateAdminPreconditions("removeFromParent",["organizations","projects"]);if(!this._getParentLinkForUser())throw new ApiError("Cet utilisateur n'est pas connecté à cette entité.",400);const e=this.parent.getEntityType(),{connectTypeDisconnect:t}=this.parent._getLinkMeta(),n={childId:this.id,childType:"citoyens",parentType:e,parentId:this.parent.id,connectType:t},r=await this.callIsConnected((()=>this.endpointApi.disconnect(n)));return await this._refreshWithParent(),r}async promoteToAdmin(){this._validateAdminPreconditions("promoteToAdmin",["organizations","projects"]);const e=this._getParentLinkForUser();if(!e)throw new ApiError("Cet utilisateur n'est pas membre de cette entité.",400);if(e?.isAdmin&&(e?.isInviting||e?.isAdminInviting))throw new ApiError("Cet utilisateur est déjà en cours d'invitation en tant qu'admin.",400);if(e?.isAdmin&&!e?.isInviting&&!e?.isAdminInviting)throw new ApiError("Cet utilisateur est déjà admin.",400);const t=this.parent.getEntityType(),n={childId:this.id,childType:"citoyens",parentType:t,parentId:this.parent.id,connectType:"admin"},r=await this.callIsConnected((()=>this.endpointApi.connect(n)));return await this._refreshWithParent(),r}async demoteFromAdmin(){this._validateAdminPreconditions("demoteFromAdmin",["organizations","projects"]);const e=this._getParentLinkForUser();if(!e?.isAdmin||e.isAdminPending)throw new ApiError("Cet utilisateur n'est pas admin de cette entité.",400);const t=this.parent.getEntityType(),{connectTypeDisconnect:n}=this.parent._getLinkMeta(),r=t,o={childId:this.id,childType:"citoyens",parentType:r,parentId:this.parent.id,connect:n,isAdmin:!1},i=await this.callIsConnected((()=>this.endpointApi.demoteAdmin(o)));return await this._refreshWithParent(),i}}Object.assign(User.prototype,{});class ObjectID{_str;constructor(e){if(this._str=void 0,e){if(e=e.toLowerCase(),24!==(t=e).length||!/^[0-9a-f]*$/.test(t))throw new Error("Invalid hexadecimal string for creating an ObjectID");this._str=e}var t}equals(e){return e instanceof ObjectID&&this.valueOf()===e.valueOf()}toString(){return`ObjectID("${this._str}")`}clone(){return new ObjectID(this._str)}typeName(){return"oid"}getTimestamp(){return Number.parseInt(this._str?.substr(0,8)??"",16)}valueOf(){return this._str}toJSONValue(){return this.valueOf()}toHexString(){return this.valueOf()}}const K=ObjectID,Z={common1:{type:"string"},common2:{format:"email",type:"string"},common3:{type:"boolean"},common4:{format:"uri",type:"string"},common5:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$",type:"string"},common6:{additionalProperties:!1,properties:{id:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$",type:"string"}},required:["id"],type:"object"},common8:{additionalProperties:!1,properties:{reason:{default:"",type:"string"}},required:["reason"],type:"object"},common10:{default:"",type:"string"},common11:{pattern:"^[a-f0-9]{24}$",type:"string"},common12:{const:"citoyens"},common13:{properties:{value:{type:"boolean"}}},common15:{enum:["isOpenData","isOpenEdition","private","feedback"]},common16:{const:"organizations"},common17:{const:"projects"},common18:{const:"events"},common19:{default:"citoyens",enum:["citoyens","projects","organizations","events"],type:"string"},common20:{},common21:{else:{properties:{id:{pattern:"^[a-f0-9]{24}$",type:"string"}}},if:{properties:{typeElement:{const:"citoyens"}}},then:{properties:{id:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$",type:"string"}}}},common24:{properties:{typeElement:{const:"citoyens"}}},common27:{not:{type:"null"}},common29:{default:"citoyens",enum:["citoyens","projects","organizations","poi","events"],type:"string"},common30:{anyOf:[{format:"email",type:"string"},{const:"",type:"string"}]},common31:{const:"",type:"string"},common32:{anyOf:[{items:{type:"string"},type:"array"},{enum:[""],type:"string"}]},common33:{items:{type:"string"},type:"array"},common34:{enum:[""],type:"string"},common35:{anyOf:[{format:"uri",type:"string"},{const:"",type:"string"}]},common36:{properties:{name:{not:{type:"null"}}},required:["name"]},common38:{properties:{url:{not:{type:"null"}}},required:["url"]},common40:{properties:{tags:{not:{type:"null"}}},required:["tags"]},common42:{properties:{email:{not:{type:"null"}}},required:["email"]},common44:{format:"date",type:"string"},common45:{const:"info",default:"info",type:"string"},common46:{anyOf:[{type:"string"},{const:"",type:"string"}]},common47:{$ref:"#/$defs/sharedFields/name"},common48:{$ref:"#/$defs/sharedFields/tags"},common49:{default:"citoyens",enum:["citoyens"],type:"string"},common50:{$ref:"#/$defs/sharedFields/url"},common51:{properties:{avancement:{not:{type:"null"}}},required:["avancement"]},common53:{properties:{parent:{not:{type:"null"}}},required:["parent"]},common55:{$ref:"#/$defs/sharedFields/emailNullable"},common56:{additionalProperties:!1,patternProperties:{"^[a-fA-F0-9]{24}$":{additionalProperties:!1,properties:{name:{type:"string"},type:{type:"string"}},required:["type","name"],type:"object"}},type:"object"},common58:{additionalProperties:!1,properties:{name:{type:"string"},type:{type:"string"}},required:["type","name"],type:"object"},common59:{name:{type:"string"},type:{type:"string"}},common60:{properties:{type:{not:{type:"null"}}},required:["type"]},common62:{additionalProperties:!1,patternProperties:{"^(?:[a-f0-9]{24}|@userId)$":{additionalProperties:!1,properties:{name:{type:"string"},type:{type:"string"}},required:["type"],type:"object"}},type:"object"},common65:{enum:["workshop","competition","concert","contest","conference","debate","exhibition","festival","crowdfunding","fair","course","protest","market","film","getTogether","meeting","spectacle","internship","stand","others"],type:"string"},common66:{enum:["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],type:"string"},common67:{enum:["link","tool","machine","software","rh","Resource material","Financial Ressource","ficheBlanche","geoJson","compostPickup","video","sharedLibrary","recoveryCenter","trash","history","something2See","funPlace","place","artPiece","streetArts","openScene","stand","parking","other"],type:"string"},common68:{enum:["poi"],type:"string"},common69:{$ref:"#/$defs/socialField"},common70:{default:"citoyens",enum:["citoyens","projects","organizations"],type:"string"},common71:{properties:{id:{pattern:"^[a-f0-9]{24}$"}}},common74:{oneOf:[{const:"",type:"string"},{additionalProperties:!1,properties:{"@type":{const:"PostalAddress",type:"string"},addressCountry:{type:"string"},addressLocality:{type:"string"},codeInsee:{type:"string"},level1:{type:"string"},level1Name:{type:"string"},level3:{minLength:0,type:"string"},level3Name:{minLength:0,type:"string"},level4:{minLength:0,type:"string"},level4Name:{minLength:0,type:"string"},localityId:{type:"string"},postalCode:{type:"string"},streetAddress:{type:"string"}},required:["@type","addressCountry","codeInsee","addressLocality","localityId","level1","level1Name"],type:"object"}]},common75:{additionalProperties:!1,properties:{"@type":{const:"PostalAddress",type:"string"},addressCountry:{type:"string"},addressLocality:{type:"string"},codeInsee:{type:"string"},level1:{type:"string"},level1Name:{type:"string"},level3:{minLength:0,type:"string"},level3Name:{minLength:0,type:"string"},level4:{minLength:0,type:"string"},level4Name:{minLength:0,type:"string"},localityId:{type:"string"},postalCode:{type:"string"},streetAddress:{type:"string"}},required:["@type","addressCountry","codeInsee","addressLocality","localityId","level1","level1Name"],type:"object"},common79:{additionalProperties:!1,properties:{"@type":{const:"GeoCoordinates",type:"string"},latitude:{type:["string","number"]},longitude:{type:["string","number"]}},required:["latitude","longitude"],type:"object"},common83:{additionalProperties:!0,properties:{coordinates:{items:{type:"number"},maxItems:2,minItems:2,type:"array"},float:{const:!0,default:!0,type:"boolean"},type:{const:"Point",type:"string"}},required:["type","coordinates","float"],type:"object"},common86:{type:"number"},common87:{const:!0,default:!0,type:"boolean"},common89:{properties:{id:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},common92:{maxLength:100,minLength:3,pattern:"^[a-zA-Z0-9]+$",type:"string"},common93:{properties:{type:{const:"citoyens"}}},common95:{additionalProperties:!1,else:{properties:{ownerId:{pattern:"^[a-f0-9]{24}$"}}},if:{properties:{folder:{const:"citoyens"}}},properties:{folder:{default:"citoyens",enum:["citoyens","projects","organizations","events","poi"],type:"string"},ownerId:{type:"string"}},required:["folder","ownerId"],then:{properties:{ownerId:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},type:"object"},common101:{default:"citoyens",enum:["citoyens","projects","organizations","events","poi"],type:"string"},common104:{properties:{parentId:{pattern:"^[a-f0-9]{24}$"}}},common106:{properties:{parentType:{const:"citoyens"}}},common108:{properties:{parentId:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},common110:{default:!0,type:"boolean"},common111:{default:0,type:"integer"},common112:{required:["text"]},common113:{required:["mediaImg"]},common114:{required:["mediaFile"]},common115:{additionalProperties:!1,properties:{countFiles:{type:"number"},files:{items:{type:"string"},type:"array"}},required:["countFiles","files"],type:"object"},common117:{additionalProperties:!1,properties:{countImages:{type:"number"},images:{items:{type:"string"},type:"array"}},required:["countImages","images"],type:"object"},common119:{items:{properties:{count:{minimum:1,type:"integer"},id:{pattern:"^[a-f0-9]{24}$",type:"string"},name:{type:"string"},slug:{type:"string"},type:{type:"string"},value:{type:"string"}},required:["id","name","slug","type","value","count"],type:"object"},type:"array"},common123:{default:"public",enum:["public","private","restricted"],type:"string"},common124:{const:"news",default:"news",type:"string"},common125:{additionalProperties:!1,else:{properties:{ownerId:{pattern:"^[a-f0-9]{24}$"}}},if:{properties:{folder:{const:"citoyens"}}},properties:{folder:{default:"citoyens",enum:["citoyens","projects","organizations"],type:"string"},ownerId:{type:"string"}},required:["folder","ownerId"],then:{properties:{ownerId:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},type:"object"},common127:{additionalProperties:!1,properties:{id:{pattern:"^[a-f0-9]{24}$",type:"string"}},required:["id"],type:"object"},common128:{default:!1,type:"boolean"},common129:{properties:{childId:{pattern:"^[a-f0-9]{24}$"}}},common131:{properties:{childType:{const:"citoyens"}}},common133:{const:"share",default:"share",type:"string"},common134:{properties:{childId:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},common136:{default:"news",enum:["news"],type:"string"},common137:{items:{additionalProperties:!1,properties:{count:{type:"number"},id:{pattern:"^[a-f0-9]{24}$",type:"string"},name:{type:"string"},slug:{type:"string"},type:{type:"string"},value:{type:"string"}},required:["id","name","slug","type","value","count"],type:"object"},type:"array"},common140:{enum:["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects","citoyens","poi"],type:"string"},common141:{const:!1,default:!1,type:"boolean"},common142:{const:"",default:"",type:"string"},common143:{default:0,type:"number"},common144:{default:30,type:"number"},common145:{additionalProperties:!1,patternProperties:{"^[^\\s]+$":{additionalProperties:!1,properties:{id:{type:"string"},type:{enum:["cities","level1"],type:"string"}},required:["id","type"],type:"object"}},type:"object"},common150:{additionalProperties:!1,patternProperties:{"^[^\\s]+$":{additionalProperties:!1,properties:{indexMax:{type:"number"},indexMin:{type:"number"}},required:["indexMin","indexMax"],type:"object"}},type:"object"},common152:{additionalProperties:!1,properties:{indexMax:{type:"number"},indexMin:{type:"number"}},required:["indexMin","indexMax"],type:"object"},common154:{enum:["ALL"],type:"string"},common155:{default:0,minimum:0,type:"integer"},common156:{const:["projects"],default:["projects"],items:{enum:["projects"],type:"string"},type:"array"},common158:{$exists:!0},common159:{additionalProperties:!1,properties:{$exists:{const:!0}},required:["$exists"],type:"object"},common162:{additionalProperties:!1,else:{properties:{id:{pattern:"^[a-f0-9]{24}$"}}},if:{properties:{type:{const:"citoyens"}}},properties:{id:{type:"string"},type:{default:"citoyens",enum:["citoyens","projects","organizations"],type:"string"}},required:["type","id"],then:{properties:{id:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},type:"object"},common164:{const:["poi"],default:["poi"],items:{enum:["poi"],type:"string"},type:"array"},common165:{const:["NGO","Cooperative","LocalBusiness","Group","GovernmentOrganization"],default:["NGO","Cooperative","LocalBusiness","Group","GovernmentOrganization"],items:{enum:["NGO","Cooperative","LocalBusiness","Group","GovernmentOrganization"],type:"string"},type:"array"},common167:{$exists:!1},common168:{additionalProperties:!1,properties:{$exists:{const:!1}},required:["$exists"],type:"object"},common170:{const:!1},common171:{default:30,type:"integer"},common172:{const:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],default:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],items:{enum:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],type:"string"},type:"array"},common174:{additionalProperties:!1,properties:{$exists:{default:!1,type:"boolean"}},required:["$exists"],type:"object"},common176:{additionalProperties:!1,properties:{$in:{items:{type:"string"},minItems:1,type:"array"}},required:["$in"],type:"object"},common179:{const:["citoyens"],default:["citoyens"],items:{enum:["citoyens"],type:"string"},type:"array"},common180:{enum:["citoyens"],type:"string"},common181:{const:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects"],default:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects"],items:{enum:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects"],type:"string"},type:"array"},common183:{not:{propertyNames:{pattern:"^(?!links\\.followers\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}},common186:{"^links\\.followers\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":{additionalProperties:!1,properties:{$exists:{const:!0}},required:["$exists"],type:"object"},"^links\\.followers\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":{additionalProperties:!1,properties:{$exists:{const:!1}},required:["$exists"],type:"object"},"^links\\.followers\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":{additionalProperties:!1,properties:{$exists:{const:!1}},required:["$exists"],type:"object"}},common187:{not:{propertyNames:{pattern:"^(?!links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}},common190:{default:"citoyens",enum:["citoyens","organizations","projects"],type:"string"},common191:{const:["badges"],default:["badges"],items:{enum:["badges"],type:"string"},type:"array"},common193:{const:["citoyens","projects","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],default:["citoyens","projects","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],items:{enum:["citoyens","projects","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],type:"string"},type:"array"},common195:{additionalProperties:!1,properties:{$exists:{const:!0,type:"boolean"}},required:["$exists"],type:"object"},common197:{const:!0,type:"boolean"},common198:{additionalProperties:!1,properties:{$exists:{const:!1,type:"boolean"}},required:["$exists"],type:"object"},common201:{"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteEmetteur$":{additionalProperties:!1,properties:{$exists:{const:!1,type:"boolean"}},required:["$exists"],type:"object"},"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteRecepteur$":{additionalProperties:!1,properties:{$exists:{const:!0,type:"boolean"}},required:["$exists"],type:"object"}},common202:{indexMax:30,indexMin:0},common203:{properties:{parentType:{const:"organizations"}}},common205:{properties:{parentType:{const:"projects"}}},common207:{properties:{parentType:{const:"events"}}},common209:{default:"@userId",pattern:"^([a-f0-9]{24}|@\\w+)$",type:"string"},common210:{const:"citoyens",default:"citoyens",enum:["citoyens"],type:"string"},common211:{enum:["citoyens","organizations","projects","events"],type:"string"},common212:{const:"citoyens",default:"citoyens",type:"string"},common213:{const:"@userId",default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$",type:"string"},common214:{default:{isOpenData:!0,isOpenEdition:!0},properties:{isOpenData:{default:!0,type:"boolean"},isOpenEdition:{default:!0,type:"boolean"}},required:["isOpenData","isOpenEdition"],type:"object"},common217:{additionalProperties:!1,default:{"@userId":{type:"citoyens"}},patternProperties:{"^(?:[a-f0-9]{24}|@userId)$":{additionalProperties:!1,properties:{name:{type:"string"},type:{type:"string"}},required:["type"],type:"object"}},type:"object"},common220:{const:"poi",default:"poi",type:"string"},common221:{const:"events",default:"events",type:"string"},common222:{format:"date-time",type:"string"},common223:{pattern:"^([01]\\d|2[0-3]):[0-5]\\d$",type:"string"},common224:{type:"integer"},common225:{additionalProperties:!1,properties:{id:{default:"@userId",pattern:"^[a-f0-9]{24}$",type:"string"},type:{const:"citoyens",default:"citoyens",type:"string"}},required:["type","id"],type:"object"},common228:{const:"badges",default:"badges",type:"string"},common229:{const:"badge",default:"badge",type:"string"},common230:{patternProperties:{"^[0-9a-f]{24}$":{additionalProperties:!1,properties:{isAdmin:{default:"",enum:["","admin"],type:"string"},name:{type:"string"},roles:{items:{type:"string"},type:"array"}},required:["name"],type:"object"}},type:"object"},common234:{default:"",enum:["","admin"],type:"string"},common235:{enum:["projects","organizations"],type:"string"},common236:{items:{enum:["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","organizations","projects","events","citoyens","poi"],type:"string"},type:"array"},common238:{default:"",oneOf:[{additionalProperties:!0,type:"object"},{const:"",type:"string"}]},common240:{additionalProperties:!0,properties:{tags:{additionalProperties:!0,properties:{verb:{type:"string"}},type:"object"}},type:"object"},common244:{additionalProperties:{enum:[1,-1],type:"integer"},type:"object"},common246:{additionalProperties:!1,properties:{id:{pattern:"^[a-f0-9]{24}$",type:"string"},type:{default:"events",type:"string"}},required:["id","type"],type:"object"},common249:{items:{properties:{id:{type:"string"}},required:["id"],type:"object"},type:"array"},common252:{additionalProperties:!1,properties:{contextId:{pattern:"^[a-f0-9]{24}$",type:"string"},contextType:{enum:["projects","organizations"],type:"string"},costumEditMode:{default:!1,type:"boolean"},costumSlug:{type:"string"},sourceKey:{items:{type:"string"},type:"array"}},type:"object"},common254:{items:{enum:["answers"],type:"string"},type:"array"},common256:{enum:["comments","news"],type:"string"},common257:{default:"citoyens",enum:["citoyens","organizations","projects","events","poi"],type:"string"}},J={endpoints:[{auth:"none",constant:"PERSON_REGISTER",contentType:"application/x-www-form-urlencoded",generateModule:"UserNoAuth",method:"POST",onlyAuthNone:!0,path:"/co2/person/register",request:{additionalProperties:!1,properties:{app:Z.common1,email:Z.common2,isInvitation:Z.common3,mode:Z.common1,name:Z.common1,pendingUserId:Z.common1,pwd:Z.common1,username:Z.common1},required:["name","username","email","pwd"],type:"object"}},{auth:"none",constant:"AUTHENTICATE_URL",contentType:"application/json",generateModule:"UserNoAuth",method:"POST",onlyAuthNone:!0,path:"/api/cocolight/authenticate",postActions:[{path:"accessToken",type:"setToken"},{path:"refreshToken",type:"setRefreshToken"},{event:"userLoggedIn",path:"user",type:"emitEvent"}],request:{additionalProperties:!1,properties:{email:Z.common2,password:Z.common1},required:["email","password"],type:"object"}},{auth:"none",constant:"REFRESH_TOKEN_URL",contentType:"application/json",method:"POST",path:"/api/cocolight/refreshtoken",request:{additionalProperties:!1,properties:{refreshToken:Z.common1},required:["refreshToken"],type:"object"}},{auth:"bearer",constant:"ME_INFO_URL",contentType:"application/json",method:"POST",path:"/api/cocolight/me"},{auth:"none",constant:"PASSWORD_RECOVERY",contentType:"application/x-www-form-urlencoded",generateModule:"UserNoAuth",method:"POST",onlyAuthNone:!0,path:"/co2/person/sendemail",request:{additionalProperties:!1,properties:{email:Z.common2,type:{const:"password",default:"password",type:"string"}},required:["email","type"],type:"object"}},{auth:"bearer",constant:"SERVER_EXCHANGE_TOKEN",contentType:"application/json",method:"POST",path:"/api/cocolight/exchangetoken",request:{additionalProperties:!1,properties:{serverUrl:Z.common4},required:["serverUrl"],type:"object"}},{auth:"bearer",constant:"CHANGE_PASSWORD",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/person/changepassword",request:{additionalProperties:!1,properties:{mode:{const:"changePassword",default:"changePassword",type:"string"},newPassword:Z.common1,newPassword2:Z.common1,oldPassword:Z.common1,scope:{default:"",type:["string"]},userId:Z.common5},required:["mode","userId","oldPassword","newPassword","newPassword2"],type:"object"}},{auth:"bearer",constant:"DELETE_ACCOUNT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/delete/id/{id}/type/citoyens",pathParams:Z.common6,postActions:[{type:"resetSession"},{event:"accountDeleted",path:null,type:"emitEvent"}],request:Z.common8},{auth:"bearer",constant:"UPDATE_SETTINGS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updatesettings",request:{additionalProperties:!1,allOf:[{else:{properties:{idEntity:Z.common11}},if:{properties:{typeEntity:Z.common12}},then:{properties:{idEntity:Z.common5}}},{if:{properties:{type:{enum:["birthDate","email","locality","phone","directory"]},typeEntity:Z.common12}},then:{properties:{value:{enum:["private","public","mask"],type:"string"}}}},{if:{properties:{type:{enum:["activitypub","isOpenData"]},typeEntity:Z.common12}},then:Z.common13},{if:{properties:{type:Z.common15,typeEntity:Z.common16}},then:Z.common13},{if:{properties:{type:Z.common15,typeEntity:Z.common17}},then:Z.common13},{if:{properties:{type:{enum:["isOpenData","isOpenEdition","public"]},typeEntity:Z.common18}},then:Z.common13}],properties:{idEntity:Z.common1,type:Z.common1,typeEntity:Z.common19,value:Z.common20},required:["type","value","typeEntity","idEntity"],type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_DESCRIPTION",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{additionalProperties:!1,allOf:[Z.common21,{anyOf:[{properties:{description:Z.common27},required:["description"]},{properties:{shortDescription:Z.common27},required:["shortDescription"]}]}],properties:{block:{const:"descriptions",default:"descriptions",type:"string"},descMentions:Z.common10,description:Z.common1,id:Z.common1,scope:{default:"",type:["string","null"]},shortDescription:Z.common1,typeElement:Z.common29},required:["block","typeElement","id"],type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_INFO",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{$defs:{sharedFields:{email:Z.common2,emailNullable:Z.common30,name:Z.common1,tags:Z.common32,url:Z.common35}},allOf:[{if:Z.common24,then:{additionalProperties:!1,anyOf:[Z.common36,{properties:{birthDate:Z.common27},required:["birthDate"]},{properties:{fixe:Z.common27},required:["fixe"]},{properties:{mobile:Z.common27},required:["mobile"]},Z.common38,Z.common40,Z.common42],properties:{birthDate:{anyOf:[Z.common44,Z.common31]},block:Z.common45,email:{$ref:"#/$defs/sharedFields/email"},fixe:Z.common46,id:Z.common5,mobile:Z.common46,name:Z.common47,scope:Z.common10,tags:Z.common48,typeElement:Z.common49,url:Z.common50}}},{if:{properties:{typeElement:Z.common17}},then:{additionalProperties:!1,anyOf:[Z.common36,Z.common38,Z.common40,Z.common42,Z.common51,Z.common53],properties:{avancement:{enum:["abandoned","concept","development","production","started","testing","idea","mature","qa","finished"],type:"string"},block:Z.common45,email:Z.common55,id:Z.common1,name:Z.common47,parent:Z.common56,scope:Z.common10,tags:Z.common48,typeElement:{default:"citoyens",enum:["projects"],type:"string"},url:Z.common50}}},{if:{properties:{typeElement:Z.common18}},then:{additionalProperties:!1,anyOf:[Z.common36,Z.common38,Z.common40,Z.common42,Z.common51,Z.common60,{properties:{organizer:Z.common27},required:["organizer"]},Z.common53],properties:{block:Z.common45,email:Z.common55,id:Z.common1,name:Z.common47,organizer:Z.common62,parent:Z.common56,scope:Z.common10,tags:Z.common48,type:Z.common65,typeElement:{default:"citoyens",enum:["events"],type:"string"},url:Z.common50}}},{if:{properties:{typeElement:Z.common16}},then:{additionalProperties:!1,anyOf:[Z.common36,Z.common38,Z.common40,Z.common42,Z.common60],properties:{block:Z.common45,email:Z.common55,id:Z.common1,name:Z.common47,scope:Z.common10,tags:Z.common48,type:Z.common66,typeElement:{enum:["organizations"],type:"string"},url:Z.common50}}},{if:{properties:{typeElement:{const:"poi"}}},then:{additionalProperties:!1,anyOf:[Z.common36,Z.common40,Z.common60,{properties:{urls:Z.common27},required:["urls"]}],properties:{block:Z.common45,id:Z.common1,name:Z.common47,scope:Z.common10,tags:Z.common48,type:Z.common67,typeElement:Z.common68,urls:Z.common32}}}],properties:{block:Z.common45,id:Z.common1,scope:Z.common10,typeElement:Z.common29},required:["block","typeElement","id"],type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_SOCIAL",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{$defs:{socialField:{anyOf:[Z.common34,Z.common4]}},allOf:[Z.common21,{anyOf:[{properties:{gitlab:Z.common27},required:["gitlab"]},{properties:{github:Z.common27},required:["github"]},{properties:{twitter:Z.common27},required:["twitter"]},{properties:{facebook:Z.common27},required:["facebook"]},{properties:{instagram:Z.common27},required:["instagram"]},{properties:{diaspora:Z.common27},required:["diaspora"]},{properties:{mastodon:Z.common27},required:["mastodon"]},{properties:{telegram:Z.common27},required:["telegram"]},{properties:{signal:Z.common27},required:["signal"]}]}],properties:{block:{const:"network",default:"network",type:"string"},diaspora:Z.common69,facebook:Z.common69,github:Z.common69,gitlab:Z.common69,id:Z.common1,instagram:Z.common69,mastodon:Z.common69,scope:Z.common10,signal:Z.common69,telegram:Z.common69,twitter:Z.common69,typeElement:Z.common70},required:["block","typeElement","id"],type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_LOCALITY",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{else:Z.common71,if:Z.common24,properties:{address:Z.common74,block:{const:"localities",default:"localities",type:"string"},geo:{oneOf:[Z.common31,Z.common79]},geoPosition:{oneOf:[Z.common31,Z.common83]},id:Z.common1,scope:Z.common10,typeElement:Z.common29},required:["block","typeElement","id","address"],then:Z.common89,type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_SLUG",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{else:Z.common71,if:Z.common24,properties:{block:Z.common45,id:Z.common1,scope:Z.common10,slug:Z.common92,typeElement:Z.common29},required:["block","typeElement","id","slug"],then:Z.common89,type:"object"}},{auth:"bearer",constant:"CHECK",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/slug/check",request:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{block:Z.common45,id:Z.common1,slug:Z.common92,type:Z.common19},required:["block","type","id","slug"],then:Z.common89,type:"object"}},{auth:"bearer",constant:"PROFIL_IMAGE",contentType:"multipart/form-data",method:"POST",path:"/co2/document/upload-save/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/profil_avatar/contentKey/profil/docType/image",pathParams:Z.common95,request:{additionalProperties:!1,properties:{profil_avatar:Z.common20},required:["profil_avatar"],type:"object"}},{auth:"bearer",constant:"PROFIL_BANNER",contentType:"multipart/form-data",method:"POST",path:"/co2/document/upload-save/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/banner/docType/image/contentKey/banner",pathParams:Z.common95,request:{additionalProperties:!1,properties:{banner:Z.common20,cropH:Z.common86,cropW:Z.common86,cropX:Z.common86,cropY:Z.common86,formOrigin:{const:"banner",default:"banner"},parentId:Z.common11,parentType:Z.common101},required:["banner","parentId","parentType","formOrigin","cropW","cropH","cropX","cropY"],type:"object"}},{auth:"none",constant:"GET_ELEMENTS_ABOUT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/about/type/{type}/id/{id}/json/true",pathParams:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{id:Z.common1,type:{default:"citoyens",enum:["citoyens","projects","organizations","events","poi","badges","answers"],type:"string"}},required:["type","id"],then:Z.common89,type:"object"},request:{additionalProperties:!1,properties:{tpl:{const:"ficheInfoElement",default:"ficheInfoElement",type:"string"}},required:["tpl"],type:"object"}},{auth:"bearer",constant:"MULTICONNECT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/multiconnect",request:{additionalProperties:!1,else:Z.common104,if:Z.common106,properties:{listInvite:{additionalProperties:!1,patternProperties:{"^(citoyens|projects|organizations)$":{additionalProperties:!1,patternProperties:{"^[0-9a-fA-F]{24}$":{additionalProperties:!1,properties:{name:Z.common1},required:["name"],type:"object"}},type:"object"}},type:"object"},parentId:Z.common1,parentType:Z.common70},required:["parentId","parentType","listInvite"],then:Z.common108,type:"object"}},{auth:"none",constant:"GET_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/get/type/{type}/id/{id}/isLive/{isLive}/json/true",pathParams:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{id:Z.common1,isLive:Z.common110,type:Z.common70},required:["isLive","type","id"],then:Z.common89,type:"object"},request:{additionalProperties:!1,properties:{dateLimit:Z.common111,indexStep:{default:12,type:"integer"},search:{additionalProperties:!1,properties:{name:Z.common10},required:["name"],type:"object"}},required:["dateLimit","indexStep"],type:"object"}},{auth:"none",constant:"GET_NEWS_BY_ID",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/getbyids",request:{additionalProperties:!1,properties:{ids:{items:Z.common11,type:"array"}},required:["ids"],type:"object"}},{auth:"bearer",constant:"ADD_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/save",request:{additionalProperties:!1,anyOf:[Z.common112,Z.common113,Z.common114],else:Z.common104,if:Z.common106,properties:{json:Z.common87,markdownActive:Z.common110,mediaFile:Z.common115,mediaImg:Z.common117,mentions:Z.common119,parentId:Z.common1,parentType:Z.common70,scope:Z.common123,tags:Z.common32,text:Z.common1,type:Z.common124},required:["scope","markdownActive","parentId","parentType","type","json"],then:Z.common108,type:"object"}},{auth:"bearer",constant:"ADD_IMAGE_NEWS",contentType:"multipart/form-data",method:"POST",path:"/co2/document/uploadSave/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/newsImage/docType/image/contentKey/slider",pathParams:Z.common125,request:{additionalProperties:!1,properties:{newsImage:Z.common20},required:["newsImage"],type:"object"}},{auth:"bearer",constant:"ADD_FILE_NEWS",contentType:"multipart/form-data",method:"POST",path:"/co2/document/uploadSave/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/newsFile/docType/file",pathParams:Z.common125,request:{additionalProperties:!1,properties:{newsFile:Z.common20},required:["newsFile"],type:"object"}},{auth:"bearer",constant:"DELETE_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/delete/id/{id}",pathParams:Z.common127,request:{additionalProperties:!1,properties:{isLive:Z.common128},required:["isLive"],type:"object"}},{auth:"bearer",constant:"UPDATE_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/update",request:{additionalProperties:!1,anyOf:[Z.common112,Z.common113,Z.common114],else:Z.common104,if:Z.common106,properties:{idNews:Z.common11,markdownActive:Z.common110,mediaFile:Z.common115,mediaImg:Z.common117,mentions:Z.common119,parentId:Z.common1,parentType:Z.common70,scope:Z.common123,tags:Z.common32,text:Z.common1,type:Z.common124},required:["idNews","scope","markdownActive","parentId","parentType","type"],then:Z.common108,type:"object"}},{auth:"bearer",constant:"SHARE_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/share",request:{additionalProperties:!1,else:Z.common129,if:Z.common131,properties:{childId:Z.common11,childType:Z.common70,comment:Z.common1,connectType:Z.common133,parentId:Z.common11,parentType:Z.common124},required:["parentId","parentType","childId","childType","connectType"],then:Z.common134,type:"object"}},{auth:"none",constant:"GET_COMMENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/comment/index/type/{type}/id/{id}/json/true",pathParams:{additionalProperties:!1,properties:{id:Z.common11,type:Z.common136},required:["type","id"],type:"object"}},{auth:"bearer",constant:"ADD_COMMENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/comment/save",request:{additionalProperties:!1,properties:{argval:Z.common10,contextId:Z.common11,contextType:Z.common136,mentions:Z.common137,parentCommentId:{default:"",pattern:"^([a-f0-9]{24}|)$",type:"string"},path:Z.common10,text:Z.common1},required:["text","contextId","contextType"],type:"object"}},{auth:"bearer",constant:"DELETE_COMMENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/comment/delete/id/{id}",pathParams:Z.common127},{auth:"bearer",constant:"UPDATE_COMMENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/comment/update",request:{additionalProperties:!1,properties:{id:Z.common11,params:{properties:{mentions:Z.common137,text:Z.common1},required:["text"],type:"object"}},required:["id","params"],type:"object"}},{auth:"none",constant:"SEARCH_TAGS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/api/tags/search?q={q}",pathParams:{additionalProperties:!1,properties:{q:Z.common1},required:["q"],type:"object"}},{auth:"none",constant:"SHOW_VOTE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/action/list/type/{type}/id/{id}/actionType/vote/json/true",pathParams:{additionalProperties:!1,properties:{id:Z.common11,type:{default:"news",enum:["news","comments"],type:"string"}},required:["type","id"],type:"object"}},{auth:"none",constant:"GLOBAL_AUTOCOMPLETE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:{default:["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects","citoyens","poi"],items:Z.common140,type:"array"},fediverse:Z.common141,filters:Z.common142,indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common145,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchTags:Z.common33,searchType:{items:Z.common140,type:"array"}},required:["name","searchType","countType","indexMin","indexStep","initType","count","notSourceKey","filters","fediverse"],type:"object"}},{auth:"none",constant:"CITY_AUTOCOMPLETE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{indexMax:{minimum:5,type:"integer"},indexMin:{minimum:0,type:"integer"},locality:Z.common142,name:Z.common1,searchBy:{const:"ALL",default:"ALL",type:"string"},searchType:{const:["cities"],default:["cities"],items:{enum:["cities"],type:"string"},type:"array"}},required:["name","locality","searchType"],type:"object"}},{auth:"none",constant:"CITY_AUTOCOMPLETE_BY_COUNTRY",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/city/autocompletemultiscope",request:{additionalProperties:!1,properties:{countryCode:{default:"FR",type:"string"},formInMap:Z.common128,scopeValue:Z.common1,type:{enum:["locality"],type:"string"}},required:["type","countryCode","scopeValue","formInMap"],type:"object"}},{auth:"none",constant:"SUGGESTION_INPUT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{indexMax:{default:20,minimum:20,type:"integer"},indexMin:Z.common155,name:Z.common1,searchType:{items:{enum:["organizations","projects","poi"],type:"string"},type:"array"}},required:["name","searchType","indexMin","indexMax"],type:"object"}},{auth:"none",constant:"GET_PROJECTS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common156,fediverse:Z.common141,filters:{additionalProperties:!1,default:{$or:{"links.contributors.@userId":Z.common158,"parent.@userId":Z.common158},"links.contributors.@userId":Z.common158},patternProperties:{"^links\\.contributors\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},properties:{$or:{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:{"^links\\.contributors\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^parent\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},type:"object"}},required:["$or"],type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common156},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_PROJECTS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/{type}/id/{id}/canSee/true",pathParams:Z.common162,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common156,fediverse:Z.common141,filters:{additionalProperties:!1,default:{$or:{"links.contributors.@{pathParams.id}":Z.common158,"parent.@{pathParams.id}":Z.common158},"links.contributors.@{pathParams.id}":Z.common158},patternProperties:{"^links\\.contributors\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159},properties:{$or:{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:{"^links\\.contributors\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^parent\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159},type:"object"}},required:["$or"],type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common156},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_POIS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common164,fediverse:Z.common141,filters:{additionalProperties:!1,default:{"parent.@userId":Z.common158},patternProperties:{"^parent\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common164},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_POIS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/{type}/id/{id}/canSee/true",pathParams:Z.common162,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common164,fediverse:Z.common141,filters:{additionalProperties:!1,default:{"parent.@{pathParams.id}":Z.common158},patternProperties:{"^parent\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common164},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_ORGANIZATIONS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common165,fediverse:Z.common141,filters:{additionalProperties:!1,default:{"links.members.@userId":Z.common158,"links.members.@userId.isInviting":Z.common167,"links.members.@userId.toBeValidated":Z.common167},patternProperties:{"^links\\.members\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^links\\.members\\.(?:[a-f0-9]{24}|@\\w+)\\.isInviting$":Z.common168,"^links\\.members\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common165},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_ORGANIZATIONS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/{type}/id/{id}/canSee/true",pathParams:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{id:Z.common1,type:{default:"citoyens",enum:["citoyens","organizations"],type:"string"}},required:["type","id"],then:Z.common89,type:"object"},request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common165,fediverse:Z.common141,filters:{additionalProperties:!1,default:{"links.members.@{pathParams.id}":Z.common158,"links.members.@{pathParams.id}.isInviting":Z.common167,"links.members.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.members\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.members\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common168,"^links\\.members\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common165},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_MEMBERS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common172,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)$)"}}},{not:{propertyNames:{pattern:"^(?!links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$)"}}}],patternProperties:{"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdmin$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdminPending$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.isInviting$":Z.common174,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.roles$":Z.common176,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common172},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_MEMBERS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/organizations/id/{id}/canSee/true",pathParams:Z.common127,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common172,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}}],default:{"links.memberOf.@{pathParams.id}":Z.common158,"links.memberOf.@{pathParams.id}.isInviting":Z.common167,"links.memberOf.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdmin$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdminPending$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common174,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.roles$":Z.common176,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common174},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common172},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_FRIENDS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/citoyens/id/{id}/canSee/true",pathParams:Z.common6,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.friends\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}}],default:{"links.friends.@{pathParams.id}":Z.common158,"links.friends.@{pathParams.id}.isInviting":Z.common167,"links.friends.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.friends\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.friends\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common174,"^links\\.friends\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common174},type:"object"},indexMax:Z.common86,indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_SUBSCRIPTIONS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common181,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[Z.common183],default:{"links.followers.@userId":Z.common158,"links.followers.@{userId}.isInviting":Z.common167,"links.followers.@{userId}.toBeValidated":Z.common167},patternProperties:Z.common186,type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common181},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_SUBSCRIPTIONS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/citoyens/id/{id}/canSee/true",pathParams:Z.common6,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common181,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[Z.common183],default:{"links.followers.@{pathParams.id}":Z.common158,"links.followers.@{pathParams.id}.isInviting":Z.common167,"links.followers.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:Z.common186,type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common181},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_SUBSCRIBERS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[Z.common187],default:{"links.follows.@userId":Z.common158,"links.follows.@{userId}.isInviting":Z.common167,"links.follows.@{userId}.toBeValidated":Z.common167},patternProperties:{"^links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common168,"^links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_SUBSCRIBERS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/{type}/id/{id}/canSee/true",pathParams:{additionalProperties:!1,allOf:[{else:Z.common71,if:Z.common93,then:Z.common89}],properties:{id:Z.common1,type:Z.common190},required:["type","id"],type:"object"},request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[Z.common187],default:{"links.follows.@{pathParams.id}":Z.common158},maxProperties:1,minProperties:1,patternProperties:{"^links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159},type:"object"},indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_CONTRIBUTORS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common172,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)$)"}}},{not:{propertyNames:{pattern:"^(?!links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$)"}}}],patternProperties:{"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdmin$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdminPending$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.isInviting$":Z.common174,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.roles$":Z.common176,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common172},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_CONTRIBUTORS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/projects/id/{id}/canSee/true",pathParams:Z.common127,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common172,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}}],default:{"links.projects.@{pathParams.id}":Z.common158,"links.projects.@{pathParams.id}.isInviting":Z.common167,"links.projects.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdmin$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdminPending$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common174,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.roles$":Z.common176,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common174},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common172},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_BADGES",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common191,fediverse:Z.common141,filters:{properties:{$or:{additionalProperties:!1,minProperties:1,patternProperties:{"^issuer\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},type:"object"},isParcours:Z.common3,"preferences.private":Z.common141},required:["preferences.private"],type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common191},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_BADGES_FILTERS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common193,fediverse:Z.common141,fields:Z.common191,filters:{oneOf:[{additionalProperties:!1,maxProperties:1,minProperties:1,patternProperties:{"badges\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common195}},{additionalProperties:!1,maxProperties:3,minProperties:3,patternProperties:{"badges\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common195,"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteEmetteur$":Z.common198,"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteRecepteur$":Z.common198}},{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:Z.common201},{additionalProperties:!1,maxProperties:1,minProperties:1,properties:{$or:{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:Z.common201,type:"object"}},required:["$or"]},{additionalProperties:!1,maxProperties:1,minProperties:1,patternProperties:{"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.revoke$":Z.common197}},{additionalProperties:!1,maxProperties:1,minProperties:1,patternProperties:{"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteEmetteur$":Z.common195}}],type:"object"},indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:{additionalProperties:!1,default:{Cooperative:Z.common202,GovernmentOrganization:Z.common202,Group:Z.common202,LocalBusiness:Z.common202,NGO:Z.common202,citoyens:Z.common202,projects:Z.common202},maxProperties:7,minProperties:7,patternProperties:{"^[a-zA-Z][a-zA-Z0-9]*$":Z.common152},type:"object"},searchType:Z.common193},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"CONNECT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/connect",request:{additionalProperties:!1,allOf:[{if:Z.common106,then:{properties:{connectType:{const:"friend",default:"friend"}}}},{if:Z.common203,then:{properties:{connectType:{enum:["admin","member"]}}}},{if:Z.common205,then:{properties:{connectType:{enum:["admin","contributor"]}}}},{if:Z.common207,then:{properties:{connectType:{default:"attendee",enum:["attendee","connect"]}}}}],properties:{childId:Z.common209,childType:Z.common210,connectType:{enum:["admin","member","contributor","attendee","friend","connect"],type:"string"},parentId:Z.common11,parentType:Z.common211},required:["childId","childType","parentType","parentId","connectType"],type:"object"}},{auth:"bearer",constant:"DISCONNECT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/disconnect",request:{additionalProperties:!1,allOf:[{if:Z.common106,then:{properties:{connectType:{default:"friends",enum:["friends","followers"]}}}},{if:Z.common203,then:{properties:{connectType:{default:"members",enum:["members","followers"]}}}},{if:Z.common205,then:{properties:{connectType:{default:"contributors",enum:["contributors","followers"]}}}},{if:Z.common207,then:{properties:{connectType:{default:"attendees",enum:["attendees","followers"]}}}}],properties:{childId:Z.common209,childType:Z.common210,connectType:{enum:["members","contributors","attendees","friends","followers"],type:"string"},parentId:Z.common11,parentType:Z.common211},required:["childId","childType","parentType","parentId","connectType"],type:"object"}},{auth:"none",constant:"GET_ELEMENTS_KEY",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/slug/getinfo/key/{slug}",pathParams:{additionalProperties:!1,properties:{slug:{pattern:"^([a-zA-Z0-9-_]+)$",type:"string"}},required:["slug"],type:"object"}},{auth:"bearer",constant:"GET_FAVORIS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/app/config/type/citoyens/id/{id}/json/true",pathParams:Z.common6},{auth:"bearer",constant:"DELETE_FAVORIS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updatepathvalue?index={index}",pathParams:{properties:{index:Z.common86},type:"object"},request:{additionalProperties:!1,properties:{collection:Z.common212,id:Z.common213,path:{const:"preferences.search.@{pathParams.index}",default:"preferences.search.@{pathParams.index}",type:"string"},pull:{const:"preferences.search",type:"string"},value:Z.common142},required:["id","collection","path","pull","value"],type:"object"}},{auth:"bearer",constant:"ADD_FAVORIS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updatepathvalue",request:{additionalProperties:!1,properties:{arrayForm:Z.common197,collection:Z.common212,id:Z.common213,path:{const:"preferences.search",default:"preferences.search",type:"string"},value:{additionalProperties:!1,properties:{description:Z.common1,locality:{patternProperties:{"^[a-f0-9]{24}$":{additionalProperties:!1,properties:Z.common59,required:["name","type"]}},type:"object"},name:Z.common1,tags:Z.common33,url:Z.common1},required:["url","name"],type:"object"}},required:["id","collection","path","arrayForm","value"],type:"object"}},{auth:"bearer",constant:"ADD_ORGANIZATION",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,properties:{address:Z.common75,collection:{const:"organizations",default:"organizations",type:"string"},email:Z.common2,geo:Z.common79,geoPosition:Z.common83,id:Z.common11,key:{const:"organization",default:"organization",type:"string"},name:{minLength:3,type:"string"},preferences:Z.common214,role:{enum:["admin","member"],type:"string"},scope:Z.common142,shortDescription:Z.common1,tags:Z.common33,type:Z.common66,url:Z.common35},required:["id","collection","key","name","type","role","scope"],type:"object"}},{auth:"bearer",constant:"ADD_PROJECT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,properties:{address:Z.common75,collection:{const:"projects",default:"projects",type:"string"},geo:Z.common79,geoPosition:Z.common83,id:Z.common11,key:{const:"project",default:"project",type:"string"},name:Z.common1,parent:Z.common217,preferences:{default:{crowdfunding:!0,isOpenData:!1,isOpenEdition:!1},properties:{crowdfunding:Z.common110,isOpenData:Z.common128,isOpenEdition:Z.common128},required:["isOpenData","isOpenEdition"],type:"object"},public:Z.common110,scope:Z.common142,shortDescription:Z.common1,tags:Z.common33,url:Z.common35},required:["id","collection","key","parent","name","public","scope"],type:"object"}},{auth:"bearer",constant:"ADD_POI",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,properties:{address:Z.common75,collection:Z.common220,description:Z.common1,geo:Z.common79,geoPosition:Z.common83,id:Z.common11,key:Z.common220,name:Z.common1,parent:Z.common217,scope:Z.common142,tags:Z.common33,type:Z.common67,urls:Z.common33},required:["id","collection","key","parent","type","name"],type:"object"}},{auth:"bearer",constant:"ADD_EVENT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,else:{required:["openingHours"]},if:{properties:{recurrency:Z.common170}},properties:{address:Z.common74,collection:Z.common221,email:Z.common30,endDate:Z.common222,geo:Z.common79,geoPosition:Z.common83,id:Z.common11,key:{const:"event",default:"event",type:"string"},name:{minLength:2,type:"string"},openingHours:{default:["","","","","","",""],items:{anyOf:[Z.common31,{additionalProperties:!1,properties:{dayOfWeek:{enum:["Mo","Tu","We","Th","Fr","Sa","Su"],type:"string"},hours:{default:[],items:{additionalProperties:!1,properties:{closes:Z.common223,opens:Z.common223},required:["opens","closes"],type:"object"},type:"array"}},required:["dayOfWeek","hours"],type:"object"}]},maxItems:7,minItems:7,type:"array"},organizer:Z.common217,parent:{oneOf:[Z.common62,Z.common31]},preferences:{default:{isOpenData:!1,isOpenEdition:!1},properties:{isOpenData:Z.common128,isOpenEdition:Z.common128},required:["isOpenData","isOpenEdition"],type:"object"},public:Z.common110,recurrency:Z.common128,scope:Z.common142,shortDescription:{format:"textarea",type:"string"},startDate:Z.common222,tags:{anyOf:[Z.common33,Z.common31]},timeZone:Z.common1,type:Z.common65,url:Z.common35},required:["id","collection","key","organizer","type","name","scope"],startBeforeEnd:!0,then:{required:["startDate","endDate"]},type:"object"}},{auth:"bearer",constant:"DELETE_POI",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/delete/type/poi/id/{id}",pathParams:Z.common127,request:Z.common8},{auth:"bearer",constant:"DELETE_EVENT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/delete/type/events/id/{id}/",pathParams:Z.common127,request:Z.common8},{auth:"bearer",constant:"DELETE_ELEMENT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/delete/type/{type}/id/{id}",pathParams:{additionalProperties:!1,properties:{id:Z.common11,type:Z.common1},required:["type","id"],type:"object"},request:Z.common8},{auth:"bearer",constant:"ADD_IMAGE_ELEMENT",contentType:"multipart/form-data",method:"POST",path:"/co2/document/upload-save/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/qqfile/docType/image/contentKey/profil",pathParams:{additionalProperties:!1,properties:{folder:{enum:["badges","events"],type:"string"},ownerId:Z.common11},required:["folder","ownerId"],type:"object"},request:{additionalProperties:!1,properties:{qqfile:Z.common20,qqfilename:Z.common1,qqtotalfilesize:Z.common224,qquuid:Z.common11},required:["qquuid","qqfilename","qqtotalfilesize","qqfile"],type:"object"}},{auth:"bearer",constant:"LINK_VALIDATE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/validate",request:{additionalProperties:!1,properties:{childId:Z.common5,childType:Z.common49,linkOption:{enum:["isInviting","toBeValidated","isAdminPending"],type:"string"},parentId:Z.common11,parentType:Z.common211},required:["childId","childType","parentType","parentId"],type:"object"}},{auth:"none",constant:"SEARCH_MEMBER_AUTOCOMPLETE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/searchmemberautocomplete",request:{additionalProperties:!1,properties:{search:Z.common1,searchMode:{default:"personOnly",enum:["personOnly","organizationOnly","mixte"],type:"string"}},required:["search","searchMode"],type:"object"}},{auth:"bearer",constant:"GET_NOTIFICATIONS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/getnotifications/type/{type}/id/{id}",pathParams:Z.common225,request:{additionalProperties:!1,properties:{indexMin:Z.common111},type:"object"}},{auth:"bearer",constant:"GET_NOTIFICATIONS_COUNT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/getnotifications/type/{type}/id/{id}",pathParams:Z.common225,request:{additionalProperties:!1,properties:{refreshTimestamp:Z.common224},type:"object"}},{auth:"bearer",constant:"NOTIFICATION_UPDATE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/update",request:{additionalProperties:!1,properties:{action:{enum:["seen","read"],type:"string"},all:Z.common87},required:["action","all"],type:"object"}},{auth:"bearer",constant:"REMOVE_ALL_NOTIFICATIONS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/removeall"},{auth:"bearer",constant:"MARK_NOTIFICATION_AS_READ",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/marknotificationasread",request:Z.common127},{auth:"none",constant:"ACTIVITYPUB_SEARCH",contentType:"application/x-www-form-urlencoded",method:"GET",params:[Z.common20],path:"/api/activitypub/search?address={address}",pathParams:{additionalProperties:!1,properties:{address:Z.common1},required:["address"],type:"object"}},{auth:"bearer",constant:"ACTIVITYPUB_LINK",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/api/activitypub/link",request:{additionalProperties:!1,properties:{action:{enum:["undo_follow","accept_invitation","reject_invitation","undo_accept","undo_request_follow","follow","remove_follow","accept_follower","reject_follower","remove_follower","remove_invitation"],type:"string"},actor:{additionalProperties:!1,properties:{id:Z.common1,name:Z.common1,type:{enum:["person"],type:"string"}},required:["id","type","name"],type:"object"},payload:Z.common4},required:["action","payload","actor"],type:"object"}},{auth:"none",constant:"ACTIVITYPUB_GET_COMMUNITY",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/api/activitypub/getcommunity/userId/${userId}/type/${type}/actor/person",pathParams:{additionalProperties:!1,properties:{type:{enum:["follows","followers"],type:"string"},userId:Z.common11},required:["userId","type"],type:"object"}},{auth:"none",constant:"GET_BADGE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/app/page/type/badges/id/{id}/json/true",pathParams:Z.common127},{auth:"none",constant:"GET_EMETTEUR_BADGES",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/app/badge/json/true"},{auth:"bearer",constant:"ADD_BADGES",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,properties:{collection:Z.common228,criteria:{additionalProperties:!1,properties:{narrative:Z.common1},required:["narrative"],type:"object"},description:Z.common1,id:Z.common11,isParcours:Z.common128,issuer:{additionalProperties:!1,patternProperties:{"^(?:[a-f0-9]{24}|@userId)$":{additionalProperties:!1,properties:{name:Z.common1,type:{enum:["citoyens","organizations","projects"],type:"string"}},required:["type"],type:"object"}},type:"object"},key:Z.common229,name:Z.common1,parent:{additionalProperties:!1,patternProperties:{"^[a-f0-9]{24}$":{additionalProperties:!1,properties:{name:Z.common1,type:Z.common228},required:["type"],type:"object"}},type:"object"},preferences:Z.common214,public:Z.common110,scope:Z.common142,tags:Z.common33},required:["id","collection","key","name","public","scope","issuer","criteria"],type:"object"}},{auth:"bearer",constant:"ASSIGN_BADGES",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/badges/assign",request:{additionalProperties:!1,properties:{award:{patternProperties:{"^[0-9a-f]{24}$":Z.common58},type:"object"},badgeId:Z.common11,collection:Z.common228,evidences:{items:{additionalProperties:!1,properties:{narative:Z.common1,url:Z.common4},required:["narative"],type:"object"},type:"array"},key:Z.common229,narative:Z.common1,scope:Z.common142},required:["key","collection","badgeId","award"],type:"object"}},{auth:"none",constant:"GET_EVENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/agenda",request:{additionalProperties:!0,properties:{count:Z.common128,countType:{const:["events"],default:["events"],type:"array"},endDateUTC:Z.common222,fediverse:Z.common128,filters:{additionalProperties:!1,default:{$or:{"links.attendees.@userId":Z.common158,"organizer.@userId":Z.common158},"links.attendees.@userId":Z.common158},patternProperties:{"^links\\.attendees\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},properties:{$or:{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:{"^links\\.attendees\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^organizer\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},type:"object"}},required:["$or"],type:"object"},indexMin:Z.common111,indexStep:{default:100,type:"integer"},locality:{patternProperties:{"^[^\\s]+$":{type:"object"}},type:"object"},name:Z.common1,recurrency:Z.common110,searchType:{const:["events"],default:["events"],items:{enum:["events"],type:"string"},type:"array"},startDateUTC:Z.common222,type:Z.common65},required:["searchType","indexMin","indexStep","fediverse"],type:"object"}},{auth:"bearer",constant:"SHARE_EVENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/share",request:{additionalProperties:!1,else:Z.common129,if:Z.common131,properties:{childId:Z.common11,childType:Z.common70,comment:Z.common1,connectType:Z.common133,parentId:Z.common11,parentType:Z.common221},required:["parentId","childId","childType","connectType","parentType"],then:Z.common134,type:"object"}},{auth:"bearer",constant:"INVITE_EVENT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/multiconnect",request:{additionalProperties:!1,else:Z.common104,if:Z.common106,properties:{listInvite:{additionalProperties:!1,minProperties:1,properties:{citoyens:Z.common230,invites:{patternProperties:{"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$":{additionalProperties:!1,properties:{email:Z.common2,isAdmin:Z.common234,msg:Z.common1,name:Z.common1,roles:Z.common33},required:["name","email"],type:"object"}},type:"object"},organizations:Z.common230,projects:Z.common230},type:"object"},parentId:Z.common1,parentType:Z.common70},required:["parentId","parentType","listInvite"],then:Z.common108,type:"object"}},{auth:"bearer",constant:"FOLLOW",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/follow",request:{additionalProperties:!1,properties:{childId:Z.common209,childType:Z.common210,parentId:Z.common11,parentType:Z.common211},required:["childId","childType","parentType","parentId"],type:"object"}},{auth:"none",constant:"GET_COSTUM_JSON",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/cms/getcostumjson?slug={slug}",pathParams:{slug:Z.common1}},{auth:"none",constant:"GLOBAL_AUTOCOMPLETE_COSTUM",contentType:"application/x-www-form-urlencoded",functionCocostum:"globalautocomplete",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,count:Z.common87,countType:Z.common236,fediverse:Z.common128,fields:Z.common33,filters:Z.common238,indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common145,mapUsed:Z.common197,name:Z.common1,notSourceKey:Z.common197,options:Z.common240,ranges:Z.common150,searchBy:Z.common154,searchTags:Z.common33,searchType:Z.common236,sortBy:Z.common244,sourceKey:Z.common33},required:["searchType","countType","indexMin","indexStep","initType","count","fediverse","costumSlug","costumEditMode"],type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_ACTORS",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestActors",method:"POST",path:"/costum/coevent/get_events/request/actors/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,parent_only:Z.common3,sourceKey:Z.common33,types:{items:{enum:["organizer","links.attendees","creator","links.creator","links.organizer","organizerName","animator"],type:"string"},type:"array"}},type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_SUBEVENTS",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestSubevents",method:"POST",path:"/costum/coevent/get_events/request/subevents/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,allOf:[{if:{properties:{date:Z.common1},required:["date"]},then:{required:["timezone"]}}],properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,date:{oneOf:[Z.common1,{properties:{between:{properties:{end:Z.common44,start:Z.common44},required:["start","end"],type:"object"}},required:["between"],type:"object"}]},fromToday:Z.common3,regions:Z.common249,sourceKey:Z.common33,tags:Z.common33,timezone:Z.common1,type:Z.common1},type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_ELEMENT_EVENT",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestElementEvent",method:"POST",path:"/costum/coevent/get_events/request/element_event/id/{id}/type/{type}",pathParams:Z.common246,request:Z.common252},{auth:"none",constant:"COSTUM_EVENT_REQUEST_CATEGORIES",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestCategories",method:"POST",path:"/costum/coevent/get_events/request/categories/id/{id}/type/{type}",pathParams:Z.common246,request:Z.common252},{auth:"none",constant:"COSTUM_EVENT_REQUEST_DATES",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestDates",method:"POST",path:"/costum/coevent/get_events/request/dates/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,regions:Z.common249,sourceKey:Z.common33,tags:Z.common33,type:Z.common1},type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_EVENT",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestEvent",method:"POST",path:"/costum/coevent/get_events/request/event/id/{id}/type/{type}",pathParams:Z.common246,request:Z.common252},{auth:"none",constant:"COSTUM_EVENT_REQUEST_LINK_TL_TO_EVENT",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestLinkTlToEvent",method:"POST",path:"/costum/coevent/get_events/request/link_tl_to_event/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,event:Z.common1,sourceKey:Z.common33,tl:Z.common1},required:["tl","event"],type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_LOAD_CONTEXT_TAG",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestLoadContextTag",method:"POST",path:"/costum/coevent/get_events/request/load_context_tag/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,event:Z.common11,search:Z.common1,sourceKey:Z.common33},type:"object"}},{auth:"none",constant:"GET_GALLERY",contentType:"application/x-www-form-urlencoded",functionCocostum:"",method:"POST",path:"/co2/gallery/index/type/{type}/id/{id}/docType/{docType}/tpl/json",pathParams:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{docType:{default:"image",enum:["image","file","bookmarks"],type:"string"},id:Z.common1,type:Z.common190},required:["id","type","docType"],then:Z.common89,type:"object"},request:{additionalProperties:!1,properties:{contentKey:Z.common1,folderId:Z.common1},type:"object"}},{auth:"none",constant:"GET_ATTENDEES_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.events\\.(?:[a-f0-9]{24}|@\\w+)$)"}}},{not:{propertyNames:{pattern:"^(?!links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$)"}}}],patternProperties:{"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdmin$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdminPending$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.isInviting$":Z.common174,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.roles$":Z.common176,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_ATTENDEES_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/events/id/{id}/canSee/true",pathParams:Z.common127,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}}],default:{"links.events.@{pathParams.id}":Z.common158,"links.events.@{pathParams.id}.isInviting":Z.common167,"links.events.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdmin$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdminPending$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common174,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.roles$":Z.common176,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common174},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"COFORM_ANSWERS_SEARCH",contentType:"application/x-www-form-urlencoded",functionCocostum:"answerlist",method:"POST",path:"/survey/coform/answerslist",request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,count:Z.common87,countType:Z.common254,fediverse:Z.common128,fields:Z.common33,filters:Z.common238,indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common145,mapUsed:Z.common197,name:Z.common1,notSourceKey:Z.common197,options:Z.common240,ranges:Z.common150,searchBy:Z.common154,searchTags:Z.common33,searchType:Z.common254,sortBy:Z.common244,sourceKey:Z.common33},required:["searchType","countType","indexMin","indexStep","initType","count","fediverse"],type:"object"}},{auth:"none",constant:"COFORM_ANSWERS_BY_ID",contentType:"application/x-www-form-urlencoded",functionCocostum:"findanswered",method:"POST",path:"/survey/coform/findanswered",request:{additionalProperties:!1,properties:{answerId:Z.common1,fields:Z.common33,finderPath:Z.common10},required:["answerId"],type:"object"}},{auth:"bearer",constant:"ADD_VOTE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/action/addaction",request:{additionalProperties:!1,properties:{action:{const:"vote",default:"vote",type:"string"},collection:Z.common256,details:{additionalProperties:!1,properties:{status:Z.common1},required:["status"],type:"object"},id:Z.common11},required:["id","collection","action","details"],type:"object"}},{auth:"bearer",constant:"ADD_REPORT_ABUSE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/action/addaction",request:{additionalProperties:!1,properties:{action:{const:"reportAbuse",default:"reportAbuse",type:"string"},collection:Z.common256,details:{additionalProperties:!1,properties:{comment:Z.common1,reason:Z.common1},required:["reason"],type:"object"},id:Z.common11},required:["id","collection","action","details"],type:"object"}},{auth:"bearer",constant:"UPDATE_PATH_VALUE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updatepathvalue",request:{additionalProperties:!1,properties:{arrayForm:Z.common3,collection:Z.common257,id:Z.common5,path:Z.common1,value:Z.common20},required:["id","collection","path","value"],type:"object"}},{auth:"bearer",constant:"DELETE_DOCUMENT_BY_CONTEXT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/document/delete/dir/co2/contextType/{contextType}/contextId/{contextId}",pathParams:{additionalProperties:!1,properties:{contextId:Z.common5,contextType:Z.common257},required:["contextType","contextId"],type:"object"},request:{additionalProperties:!1,properties:{ids:Z.common11,parentId:Z.common5,parentType:Z.common257,path:{const:"communecter",default:"communecter",type:"string"}},required:["id","collection","path","value"],type:"object"}},{auth:"bearer",constant:"DEMOTE_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/updateadminlink/",request:{additionalProperties:!1,properties:{childId:Z.common11,childType:Z.common180,connect:{enum:["members","contributors"],type:"string"},isAdmin:Z.common141,parentId:Z.common11,parentType:{enum:["organizations","projects"],type:"string"}},required:["parentId","parentType","childId","childType","connect","isAdmin"],type:"object"}}]};function H(e){return e instanceof Error}function W(e){return H(e)&&"response"in e&&"object"==typeof e.response&&"number"==typeof e.response.status}function Q(e){return H(e)?e.message:"string"==typeof e?e:e&&"object"==typeof e&&"message"in e?String(e.message):"Unknown error"}function Y(e){return function(e){return H(e)&&"status"in e&&"number"==typeof e.status}(e)?e.status:W(e)?e.response.status:e instanceof ApiError?e.status:void 0}class TokenStorageStrategy{}class MemoryStorageStrategy extends TokenStorageStrategy{_accessToken=null;_refreshToken=null;constructor(){super()}getAccessToken(){return this._accessToken}setAccessToken(e){this._accessToken=e}getRefreshToken(){return this._refreshToken}setRefreshToken(e){this._refreshToken=e}clear(){this._accessToken=null,this._refreshToken=null}}class LocalStorageStrategy extends TokenStorageStrategy{prefix;constructor(e="cocolight"){super(),this.prefix=e}getAccessToken(){return"undefined"!=typeof localStorage?localStorage.getItem(`${this.prefix}_accessToken`):null}setAccessToken(e){"undefined"!=typeof localStorage&&localStorage.setItem(`${this.prefix}_accessToken`,e??"")}getRefreshToken(){return"undefined"!=typeof localStorage?localStorage.getItem(`${this.prefix}_refreshToken`):null}setRefreshToken(e){"undefined"!=typeof localStorage&&localStorage.setItem(`${this.prefix}_refreshToken`,e??"")}clear(){"undefined"!=typeof localStorage&&(localStorage.removeItem(`${this.prefix}_accessToken`),localStorage.removeItem(`${this.prefix}_refreshToken`))}}class MultiServerTokenStorageStrategy extends TokenStorageStrategy{_currentBaseURL=null;constructor(){super()}use(e){if(!e)throw new Error("baseURL est requis");this._currentBaseURL=e.replace(/\/+$/,"")}_ensureContext(){if(!this._currentBaseURL)throw new Error("baseURL non défini. Appelez use(baseURL)")}_requireBaseURL(){return this._ensureContext(),this._currentBaseURL}}class MultiServerMemoryStorageStrategy extends MultiServerTokenStorageStrategy{_storage=new Map;constructor(){super()}getAccessToken(){const e=this._requireBaseURL();return this._storage.get(e)?.accessToken??null}setAccessToken(e){const t=this._requireBaseURL(),n=this._storage.get(t)||{};this._storage.set(t,{...n,accessToken:e})}getRefreshToken(){const e=this._requireBaseURL();return this._storage.get(e)?.refreshToken??null}setRefreshToken(e){const t=this._requireBaseURL(),n=this._storage.get(t)||{};this._storage.set(t,{...n,refreshToken:e})}clear(){const e=this._requireBaseURL();this._storage.delete(e)}getServers(){return Array.from(this._storage.keys())}exportAll(){return Object.fromEntries(this._storage.entries())}}class MultiServerLocalStorageStrategy extends MultiServerTokenStorageStrategy{prefix;constructor(e="cocolight"){super(),this.prefix=e}_key(e){return`${this.prefix}_tokens_${e}`}_getData(){if(this._ensureContext(),"undefined"==typeof localStorage)return{};const e=localStorage.getItem(this._key(this._currentBaseURL));return e?JSON.parse(e):{}}_setData(e){"undefined"!=typeof localStorage&&localStorage.setItem(this._key(this._currentBaseURL),JSON.stringify(e))}getAccessToken(){return this._getData().accessToken??null}setAccessToken(e){const t=this._getData();t.accessToken=e,this._setData(t)}getRefreshToken(){return this._getData().refreshToken??null}setRefreshToken(e){const t=this._getData();t.refreshToken=e,this._setData(t)}clear(){"undefined"!=typeof localStorage&&localStorage.removeItem(this._key(this._currentBaseURL))}getServers(){if("undefined"==typeof localStorage)return[];return Object.keys(localStorage).filter((e=>e.startsWith(`${this.prefix}_tokens_`))).map((e=>e.replace(`${this.prefix}_tokens_`,"")))}exportAll(){const e={};for(const t of this.getServers()){const n=this._key(t),r="undefined"!=typeof localStorage?localStorage.getItem(n):null;r&&(e[t]=JSON.parse(r))}return e}}const X=p;v.addType("oid",(e=>{if("string"==typeof e)return new K(e);if(void 0===e)return new K;throw new Error("Expected string value for ObjectID")}));class ApiClient extends s{__entityTag="ApiClient";userId=null;_baseURL;_refreshUrl;_endpoints;_debug;_fromJSONValue;_tokenStorage;_offlineClientManager=null;_ajv;_logger;_client;_breakerThreshold;_breakerResetTime;_breakerErrorCount=0;_breakerOpen=!1;_lastBreakerOpenTime=null;_accessToken=null;_refreshToken=null;_setUserId;constructor({baseURL:e,accessToken:t,refreshToken:n,refreshUrl:r="/api/cocolight/refreshtoken",endpoints:o=J.endpoints,timeout:i=3e4,debug:s=!1,maxRetries:a=0,circuitBreakerThreshold:p=5,circuitBreakerResetTime:d=6e4,fromJSONValue:m=!0,tokenStorageStrategy:l=null}){if(super(),!e)throw new ApiClientError('Le paramètre "baseURL" est obligatoire.',500);this._baseURL=e,this._refreshUrl=r,this._endpoints=o||J.endpoints,this._debug=s,this._fromJSONValue=m,this._breakerThreshold=p,this._breakerResetTime=d;let u=null;if(Object.defineProperty(this,"userId",{get:()=>u,set:()=>{throw new Error("Modification directe de userId non autorisée.")},enumerable:!0}),this._setUserId=e=>{u=e,this._logger?.debug(`[ApiClient] userId set: ${e}`)},this._ajv=new T({strict:!1,useDefaults:!0,allErrors:!0,verbose:!0}),A(this._ajv),this._ajv.addFormat("textarea",!0),this._ajv.addKeyword({keyword:"startBeforeEnd",type:"object",errors:!0,validate:this._startBeforeEndValidate}),this._logger=b({transport:{target:"pino-pretty",options:{colorize:!0}},level:s?"debug":"info"}),this._client=c.create({baseURL:e,timeout:i}),a>0&&(X(this._client,{retries:a,retryDelay:X.exponentialDelay,retryCondition:e=>X.isNetworkError(e)||X.isRetryableError(e),onRetry:(e,t,n)=>{this._logger.warn(`[Retry] Tentative #${e} pour ${n?.url}`),this.emit("retryAttempt",{retryCount:e,url:n?.url})}}),this._logger.info(`[ApiClient] Retry activé : ${a} max`)),l instanceof MultiServerTokenStorageStrategy&&l.use(this._baseURL),this._tokenStorage=l||new MemoryStorageStrategy,"function"!=typeof this._tokenStorage?.getAccessToken||"function"!=typeof this._tokenStorage?.setAccessToken||"function"!=typeof this._tokenStorage?.getRefreshToken||"function"!=typeof this._tokenStorage?.setRefreshToken||"function"!=typeof this._tokenStorage?.clear)throw new Error("[ApiClient] La stratégie de stockage des tokens n’est pas valide. Elle doit implémenter les méthodes requises.");n&&this.setRefreshToken(n),t&&this.setToken(t);const h=this._tokenStorage.getAccessToken();h&&this.setToken(h);const y=this._tokenStorage.getRefreshToken();y&&this.setRefreshToken(y),this._client.interceptors.response.use((e=>e),(async e=>{const t=e.config;if(t._retry)throw this._logger.error("[ApiClient] Requête déjà retentée, échec définitif."),e;if(e.response&&401===e.response.status&&this._refreshToken){t._retry=!0;try{this._logger.info("[ApiClient] Tentative de refresh du token...");if(await this._refreshAccessToken())return this._logger.info("[ApiClient] Token rafraîchi avec succès."),t.headers=t.headers??{},t.headers.Authorization="Bearer "+this.getToken(),this._logger.info("[ApiClient] Retente la requête originale avec le nouveau token."),this._client.request(t);throw this.resetSession(),new ApiClientError("Impossible de rafraîchir le token.",401)}catch(e){this.resetSession();const t={code:Y(e)||401,message:Q(e)};throw new ApiClientError("Erreur lors du rafraîchissement du token.",401,t)}}throw e}))}setToken(e){this._accessToken=e,this._tokenStorage.setAccessToken(e??""),e?this._client.defaults.headers.common.Authorization="Bearer "+e:delete this._client.defaults.headers.common.Authorization;const t=this._getIdFromToken(e);t&&(this._setUserId(t),this._logger.debug(`[ApiClient] userId extrait et défini : ${t}`)),this._logger.debug(`[ApiClient] setToken: ${e}`)}getToken(){return this._accessToken}setRefreshToken(e){if(this._refreshToken=e,this._tokenStorage.setRefreshToken(e??""),null===this.userId){const t=this._getIdFromToken(e);t&&(this._setUserId(t),this._logger.debug(`[ApiClient] userId extrait depuis refreshToken : ${t}`))}this._logger.debug(`[ApiClient] setRefreshToken: ${e}`)}getRefreshToken(){return this._refreshToken}get isConnected(){return!!this._accessToken}_getIdFromToken(e){if(!e)return null;try{const t=d(e);return this._logger.debug("[ApiClient] Payload décodé :",t),t.id||t.userId||null}catch(e){return this._logger.error("[ApiClient] Erreur lors du décodage du token :",e),null}}async _refreshAccessToken(){if(!this._refreshToken)return!1;const e=c.create({baseURL:this._baseURL,timeout:1e4,headers:{"Content-Type":"application/json"}});try{const t=await e.post(this._refreshUrl,{refreshToken:this._refreshToken});return!(!t.data||!t.data.token)&&(this.setToken(t.data.token),t.data.refreshToken&&this.setRefreshToken(t.data.refreshToken),this.emit("refreshSuccess",t.data),!0)}catch(e){return this.emit("refreshFailed",{error:Q(e)}),this.resetSession(),this._logger.error(`[ApiClient] Refresh Error : ${Q(e)}`),!1}}_checkCircuitBreaker(){if(!this._breakerOpen)return!0;const e=Date.now();return null!=this._lastBreakerOpenTime&&e-this._lastBreakerOpenTime>this._breakerResetTime&&(this._breakerOpen=!1,this._breakerErrorCount=0,this._logger.warn("[ApiClient] Circuit breaker réinitialisé"),this.emit("circuitBreakerReset"),!0)}_updateCircuitBreakerError(){this._breakerErrorCount+=1,this._logger.warn(`[ApiClient] Erreur #${this._breakerErrorCount} sur ${this._breakerThreshold}`),this._breakerErrorCount>=this._breakerThreshold&&(this._breakerOpen=!0,this._lastBreakerOpenTime=Date.now(),this._logger.error("[ApiClient] Circuit breaker ACTIVÉ - L'API est considérée indisponible"),this.emit("circuitBreakerOpen",{timestamp:this._lastBreakerOpenTime}))}_resetCircuitBreakerSuccess(){this._breakerErrorCount=0,this._breakerOpen&&(this._breakerOpen=!1,this._logger.warn("[ApiClient] Circuit breaker refermé suite à un succès"))}static stripNullsInPlace(e){if(e&&"object"==typeof e&&e.value&&"function"==typeof e.value.pipe)return e;if(Array.isArray(e))for(let t=e.length-1;t>=0;t--)null===e[t]||void 0===e[t]?e.splice(t,1):"object"==typeof e[t]&&ApiClient.stripNullsInPlace(e[t]);else if(e&&"object"==typeof e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(null===e[t]||void 0===e[t]?delete e[t]:"object"==typeof e[t]&&ApiClient.stripNullsInPlace(e[t]));return e}_resolveSpecialValuesInPlace(e,t={}){const n={userId:()=>this.userId,accessToken:()=>this._accessToken,refreshToken:()=>this._refreshToken,baseURL:()=>this._baseURL,pathParams:e=>{const n=this._getValueByPath(t,e);return null!=n?n:void 0}},r=/@(?:\{([^}]+)\}|([\w.]+))/g,o=e=>"string"!=typeof e?e:e.replace(r,((t,r,o)=>{if(r){if(r.startsWith("pathParams.")){const e=r.substring(11),t=n.pathParams(e);return null!=t?t:`@{${r}}`}{const e=n[r];if("function"==typeof e){const t=e();return null!=t?t:`@{${r}}`}return`@{${r}}`}}if(o){if(o.startsWith("pathParams.")){const e=o.match(/^pathParams\.([^.]+)(.*)$/);if(e){const t=e[1],r=e[2],i=n.pathParams(t);return null!=i?i+r:`@${o}`}return`@${o}`}{const e=n[o];if("function"==typeof e){const t=e();return null!=t?t:`@${o}`}return`@${o}`}}return e})),i=e=>{if((e=>e&&"object"==typeof e&&("function"==typeof e.pipe||"undefined"!=typeof Buffer&&e instanceof Buffer))(e))return e;if(Array.isArray(e))return e.map(i);if((e=>"[object Object]"===Object.prototype.toString.call(e))(e)){const t={};for(const[n,r]of Object.entries(e)){t[o(n)]=i(r)}return t}return"string"==typeof e?o(e):e};return i(e)}_cleanSchemaLeftoverAlias(e){const t=/@\w+/;if(Array.isArray(e))return e.map((e=>this._cleanSchemaLeftoverAlias(e)));if(e&&"object"==typeof e){const n={};for(const r of Object.keys(e)){const o=e[r];if(!t.test(r)){if("default"===r){if("string"==typeof o&&t.test(o))continue;if(o&&"object"==typeof o){const e=this._cleanSchemaLeftoverAlias(o);Object.keys(e).length>0&&(n[r]=e);continue}}"string"==typeof o&&t.test(o)||(n[r]=this._cleanSchemaLeftoverAlias(o))}}return n}return e}async safeCall(e,...t){try{return await e(...t)}catch(e){throw this._logger.error(`[ApiClient.safeCall] Erreur: ${Q(e)}`),e}}async callEndpoint(e,t={},n=!0,r=!0){const o=this._endpoints.find((t=>t.constant===e));if(!o)throw new ApiClientError(`Endpoint introuvable : ${e}`,404);const{path:i,method:s,contentType:a,auth:c,pathParams:p,request:d,responses:m}=o,l=(s||"GET").toLowerCase(),u=a||"application/json",h={"Content-Type":u};if(this._accessToken)"bearer"===c?h.Authorization=`Bearer ${this._accessToken}`:c&&"none"!==c||h.Authorization||(h.Authorization=`Bearer ${this._accessToken}`);else if("bearer"===c)throw new ApiClientError(`Token requis pour l'endpoint sécurisé : ${e}`,401);let y,f=i,g={};if(p){let n=p;"none"===c&&null===this.userId&&(n=this._cleanSchemaLeftoverAlias(p));const r=t.pathParams||{},o=this._ajv.compile(n);if(!o(r)){const t=this._ajvErrorHuman(o.errors??[]);throw this.emit("validationError",{stage:"pathParams",errors:o.errors}),new ApiValidationError(`callEndpoint: ${e} - Path parameter validation failed.`,400,t,o.errors)}g=this._resolveSpecialValuesInPlace(r),f=f.replace(/\{(\w+)\}/g,((e,t)=>{const n=g[t];if(void 0!==n)return encodeURIComponent(n);throw new ApiClientError(`Path param manquant ou non résolu : {${t}}`,400)}))}if(d){let n=d;"none"===c&&null===this.userId&&(n=this._cleanSchemaLeftoverAlias(d));let r={...t};delete r.pathParams,"application/x-www-form-urlencoded"===u&&(r=ApiClient.normalizeDatesForValidation(r),r=ApiClient.normalizeSchemaDateFields(r,n));const o=ApiClient.stripNullsInPlace(r),i=this._ajv.compile(n);if(!i(o)){const t=i.errors?this._ajvErrorHuman(i.errors):[];throw this.emit("validationError",{stage:"request",errors:i.errors}),new ApiValidationError(`callEndpoint: ${e} - Request validation failed.`,400,t,i.errors)}t=this._resolveSpecialValuesInPlace(o,g)}if(this._offlineClientManager?.isOffline()){if("function"==typeof this._offlineClientManager._enqueueOfflineAction){this._logger.warn(`[ApiClient] Mode dégradé : mise en file de ${e}`),await this._offlineClientManager._enqueueOfflineAction({constant:e,data:t,options:{transformResponseData:n,validateResponseSchema:r}}),this._logger.info(`[ApiClient] Requête ${e} mise en file (offline mode)`),this.emit("queuedOffline",{constant:e,reason:"offlineMode",data:t});return{data:null,offline:!0}}throw this._logger.warn("[ApiClient] Mode dégradé actif mais offlineManager non initialisé correctement"),new ApiClientError("Mode hors-ligne actif, mais gestionnaire offline non disponible.",503)}if(!this._checkCircuitBreaker()){if(!1===this._offlineClientManager?.isOffline?.()&&"function"==typeof this._offlineClientManager._enqueueOfflineAction){this._logger.warn(`[ApiClient] Circuit breaker actif → mise en file de ${e}`),await this._offlineClientManager._enqueueOfflineAction({constant:e,data:t,options:{transformResponseData:n,validateResponseSchema:r}}),this._logger.info(`[ApiClient] Requête ${e} mise en file (circuit breaker)`),this.emit("queuedOffline",{constant:e,reason:"circuitBreaker",data:t});return{data:null,breaker:!0}}throw new CircuitBreakerError("Le circuit breaker est activé, impossible d'appeler l'API")}"application/json"===u||"multipart/form-data"===u?y=t:"application/x-www-form-urlencoded"===u&&(y=ApiClient.toURLSearchParams(t)),this._logger.debug(`[ApiClient] callEndpoint: ${e} -> ${f}, method=${l}`);try{const e=await this._client.request({url:f,method:l,headers:h,["get"===l?"params":"data"]:y});if(r){const t=String(e.status),n=m?.[t];if(n){const t=this._ajv.compile(n);if(!t(e.data)){const n=this._ajvErrorHuman(t.errors??[]);throw this.emit("validationError",{stage:"response",errors:t.errors}),new ApiValidationError("Response validation failed.",e.status,n,t.errors)}}}return this._resetCircuitBreakerSuccess(),"function"==typeof n?e.data=n(e.data):!0===n&&(e.data=this._transformData(e.data)),Array.isArray(o.postActions)&&o.postActions.forEach((t=>{const n=t.path?this._getValueByPath(e.data,t.path):null;switch(t.type){case"setToken":this.setToken(n);break;case"setRefreshToken":this.setRefreshToken(n);break;case"resetSession":this.resetSession();break;case"emitEvent":t.event&&(this.emit(t.event,n),this._logger.debug(`[ApiClient] Event émis : ${t.event}`,n));break;case"callMethod":"function"==typeof this[t.method]?(this[t.method](),this._logger.debug(`[ApiClient] Méthode appelée : ${t.method}`)):this._logger.warn(`[ApiClient] Méthode inconnue : ${t.method}`);break;default:this._logger.warn(`[ApiClient] Action inconnue : ${t.type}`)}})),e}catch(t){if(this._updateCircuitBreakerError(),this._logger.error(`[ApiClient] Erreur lors de l'appel de ${e}: ${Q(t)}`),t instanceof ApiValidationError)throw t;{const e=W(t)?t.response.status:500,n=W(t)?t.response.data:null;throw new ApiClientError(`Erreur lors de l'appel de l'API : ${Q(t)}`,e,n)}}}_ajvErrorHuman(e){try{const t=new a(e);return t.errors.map((({message:e})=>e))}catch(t){return this._logger.error("[ApiClient] _ajvErrorHuman",t),e.map((({message:e})=>e))}}checkAndThrowApiResponseError(e){if(!("status"in e))return e;const t=e.data;if(!t||"object"!=typeof t)return e;if("boolean"==typeof t.result&&!1===t.result)throw new ApiResponseError(t.msg||"Erreur inconnue",e.status,t);if(t.resultErrors&&"object"==typeof t.resultErrors&&"boolean"==typeof t.resultErrors.result&&!1===t.resultErrors.result)throw new ApiResponseError(t.resultErrors.msg||"Erreur inconnue",e.status,t);return e}resetSession(){this.setToken(null),this.setRefreshToken(null),this._setUserId(null),this._tokenStorage.clear(),delete this._client.defaults.headers.common.Authorization,this._logger.info("[ApiClient] Session utilisateur réinitialisée."),this.emit("sessionReset")}_getValueByPath(e,t){if(!t)return;return t.split(".").reduce(((e,t)=>e&&e[t]),e)}static normalizeDatesForValidation(e){if(null==e)return e;if(e&&"object"==typeof e&&e.__isReactive&&e.__raw)return ApiClient.normalizeDatesForValidation(e.__raw);if(e instanceof Date)return e.toISOString().replace(/\.\d{3}Z$/,"+0000");if(Array.isArray(e))return e.map((e=>ApiClient.normalizeDatesForValidation(e)));if("object"==typeof e){const t={};for(const n of Object.keys(e))t[n]=ApiClient.normalizeDatesForValidation(e[n]);return t}return e}static normalizeSchemaDateFields(e,t){if(!e||!t||"object"!=typeof e)return e;const n={...e};let r=t.properties||{};if(t.allOf&&Array.isArray(t.allOf))for(const e of t.allOf)e.properties&&(r={...r,...e.properties}),e.then&&e.then.properties&&(r={...r,...e.then.properties});t.then&&t.then.properties&&(r={...r,...t.then.properties});for(const[e,t]of Object.entries(r)){const r=t;if("date"===r?.format&&n[e]){const t=n[e];"string"==typeof t&&t.includes("T")&&(n[e]=t.split("T")[0])}}return n}static toURLSearchParams(e,t={}){return this._buildParams(e,new URLSearchParams,t)}static _buildParams(e,t,n={}){if("object"!=typeof e||null===e)throw new TypeError("La donnée doit être un objet non nul.");const{dots:r=!1,indexes:o=!1,metaTokens:i=!0}=n,s=[];function a(e){return"[object Object]"===Object.prototype.toString.call(e)||Array.isArray(e)}function c(e){return e.endsWith("[]")?e.slice(0,-2):e}function p(e,t,n=!1){return e?e.concat(t).map(((e,t)=>(e=c(e),!n&&t?`[${e}]`:e))).join(n?".":""):t}function d(e){return null==e?"":e instanceof Date?e.toISOString():(e instanceof Blob||e instanceof File||e instanceof ArrayBuffer||ArrayBuffer.isView(e),e)}return function e(n,m=[]){null==n||s.includes(n)||(s.push(n),Object.entries(n).forEach((([n,s])=>{void 0!==s&&function(e,n,s){if(e&&"object"==typeof e){if(n.endsWith("{}"))return n=i?n:n.slice(0,-2),t.append(p(s,n,r),JSON.stringify(e)),!1;if(Array.isArray(e)&&!e.some(a)||n.endsWith("[]"))return n=c(n),e.forEach(((e,i)=>{if(null!=e){const a=o?p(s.concat(n),i,r):`${p(s,n,r)}[]`;t.append(a,d(e))}})),!1}return!!a(e)||(t.append(p(s,n,r),d(e)),!1)}(s,n.trim(),m)&&e(s,m.concat(c(n)))})),s.pop())}(e),t}_transformData(e){if(e&&"object"==typeof e)if(e.resultGoods?.msg)e=this._normalizeJsonData({msg:e.resultGoods.msg,...e});else if(e.resultErrors?.msg)e=this._normalizeJsonData({msg:e.resultErrors.msg,...e});else if(e.results&&"object"==typeof e.results&&!Array.isArray(e.results))e.results=Object.keys(e.results).map((t=>this._normalizeJsonData({id:t,...e.results[t]})));else if(Array.isArray(e.results)&&e.results.length>0)e.results=e.results.map((e=>this._normalizeJsonData(e)));else if(e.news&&Array.isArray(e.news)&&0===e.news.length)e=e.news;else if(e.news&&"object"==typeof e.news&&!Array.isArray(e.news))e=Object.keys(e.news).map((t=>this._normalizeJsonData({id:t,...e.news[t]})));else if(e.notif&&"object"==typeof e.notif&&!Array.isArray(e.notif))e.notif=Object.keys(e.notif).map((t=>this._normalizeJsonData({id:t,...e.notif[t]})));else if(e.citoyens&&"object"==typeof e.citoyens&&!Array.isArray(e.citoyens)&&e.organizations&&"object"==typeof e.organizations&&!Array.isArray(e.organizations))e=[...Object.keys(e.citoyens).map((t=>this._normalizeJsonData({id:t,...e.citoyens[t]}))),...Object.keys(e.organizations).map((t=>this._normalizeJsonData({id:t,...e.organizations[t]})))];else if(e.citoyens&&"object"==typeof e.citoyens&&!Array.isArray(e.citoyens))e=Object.keys(e.citoyens).map((t=>this._normalizeJsonData({id:t,...e.citoyens[t]})));else if(e.cities&&"object"==typeof e.cities&&!Array.isArray(e.cities))e=Object.keys(e.cities).map((t=>this._normalizeJsonData({id:t,...e.cities[t]})));else if(e.cities&&Array.isArray(e.cities)&&0===e.cities.length)e=e.cities;else if(e.newComment&&"object"==typeof e.newComment)e.newComment=this._normalizeJsonData({...e.newComment});else if(Array.isArray(e))e=e.map((e=>this._normalizeJsonData(e)));else if(e.map&&"object"==typeof e.map)e.map=this._normalizeJsonData(e.map);else if(e.object&&"object"==typeof e.object)e.object=this._normalizeJsonData(e.object);else if("object"==typeof e&&Object.keys(e).length>0){const t=Object.keys(e).every((e=>/^[0-9a-fA-F]{24}$/.test(e)));e=t?Object.keys(e).map((t=>({id:t,...this._normalizeJsonData(e[t])}))):this._normalizeJsonData(e)}return e}_normalizeJsonData(e){if(!e||"object"!=typeof e)return e;if(e=this._normalizeRecursively(e),e?.mediaImg?.images&&Array.isArray(e.mediaImg.images)&&e.mediaImg.images.length>0&&(e.mediaImg.countImages=e.mediaImg.images.length),e?.mediaFile?.files&&Array.isArray(e.mediaFile.files)&&e.mediaFile.files.length>0&&(e.mediaFile.countFiles=e.mediaFile.files.length),e?.src?.changes&&"object"==typeof e.src.changes&&Object.keys(e.src.changes).length>0&&Object.keys(e.src.changes).forEach((t=>{e.src.changes[t]&&(e.src.changes[t]=this._ensureFullURL(e.src.changes[t]))})),e?.openingHours&&Array.isArray(e.openingHours)&&e.openingHours.length>0&&(e.openingHours=e.openingHours.filter((e=>e.dayOfWeek&&e.hours&&e.hours[0]&&e.hours[0].opens))),e.replies&&"object"==typeof e.replies&&Object.keys(e.replies).length>0&&(e.replies=Object.keys(e.replies).map((t=>this._normalizeJsonData({id:t,...e.replies[t]})))),e?.author&&"object"==typeof e.author&&Object.keys(e.author).length>0&&!("profilThumbImageUrl"in e.author)){const t=Object.keys(e.author)[0];e.author={...e.author[t]}}return e?.timeAgo&&delete e.timeAgo,"people"===e?.author?.typeSig&&(e.author.type="citoyens"),"people"===e?.typeSig&&(e.collection="citoyens"),"organizations"===e?.typeSig&&(e.collection="organizations"),this._fromJSONValue?v.fromJSONValue(e):e}_ensureFullURL(e){if(!e)return e;if(!(e=e.trim())||/^https?:\/\//i.test(e))return e;let t="/";return t=this._baseURL.endsWith("/")&&e.startsWith("/")||this._baseURL.endsWith("/")||e.startsWith("/")?"":"/",`${this._baseURL}${t}${e}`}_normalizeString(e){return"true"===e||"false"!==e&&e}_normalizeId(e){return e._id&&e._id.$id&&/^[0-9a-fA-F]{24}$/.test(e._id.$id)&&(e.id=e._id.$id,e._id={$type:"oid",$value:e._id.$id}),e.id&&e.id.$id&&/^[0-9a-fA-F]{24}$/.test(e.id.$id)&&(e._id={$type:"oid",$value:e.id.$id},e.id=e.id.$id),e}_normalizeDate(e){if(e&&"object"==typeof e&&"number"==typeof e.sec)return{$date:1e3*e.sec};if("number"==typeof e)return{$date:1e3*e};if("string"==typeof e&&""!==e.trim()){const t=new Date(e);if(!isNaN(t.getTime()))return v.toJSONValue(t)}return e}_normalizeImage(e){return"string"==typeof e&&""!==e.trim()?this._ensureFullURL(e):e}_imageFields=["profilImageUrl","profilThumbImageUrl","profilMediumImageUrl","profilMarkerImageUrl","profilBannerUrl","profilRealBannerUrl","imagePath","imageThumbPath","docPath","imageThumb","imageMediumPath"];_dateFields=["modified","created","updated","birthDate","lastLoginDate","startDate","endDate","date","issuedOn"];_normalizeRecursively(e){if("string"==typeof e)return this._normalizeString(e);if(Array.isArray(e))return e.map((e=>this._normalizeRecursively(e)));if(null!==e&&"object"==typeof e){const t={};return Object.keys(e).forEach((n=>{let r=this._normalizeRecursively(e[n]);this._dateFields.includes(n)&&(r=this._normalizeDate(r)),this._imageFields.includes(n)&&(r=this._normalizeImage(r)),"content"===n&&r&&"object"==typeof r&&r.image&&(r.image=this._normalizeImage(r.image)),t[n]=r})),this._normalizeId(t)}return e}_startBeforeEndValidate=(e,t)=>{if(!t.startDate||!t.endDate)return!0;const n=new Date(t.startDate)<new Date(t.endDate);return n||(this._startBeforeEndValidate.errors=[{instancePath:"/startDate",schemaPath:"#/startBeforeEnd",keyword:"startBeforeEnd",params:{},message:"startDate must be before endDate"}]),n};getRequestSchema(e){const t=this._endpoints.find((t=>t.constant===e));return t?.request||null}getPathSchema(e){return this._endpoints.find((t=>t.constant===e))?.pathParams||null}onEvent(e={}){const t=["retryAttempt","queuedOffline","circuitBreakerOpen","circuitBreakerReset","refreshSuccess","refreshFailed","sessionReset","validationError","offlineModeChanged","userLoggedIn"];for(const n of t)"function"==typeof e[n]&&this.on(n,e[n])}getDeclaredEvents(){const e=new Set;for(const t of this._endpoints)if(Array.isArray(t.postActions))for(const n of t.postActions)"emitEvent"===n.type&&n.event&&e.add(n.event);return Array.from(e)}}function ee(e){return e&&"object"==typeof e&&"status"in e&&"data"in e}class UserApi{client;loggedUser=null;constructor(e){this.client=e instanceof ApiClient?e:new ApiClient(e)}get isConnected(){return this.client.isConnected}get userId(){return this.client.userId}async login(e,t){return this.client.safeCall((async()=>{const n=await this.client.callEndpoint("AUTHENTICATE_URL",{email:e,password:t});return this.loggedUser=new User(this.client,n.data.user,{EndpointApi:EndpointApi,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment}),this.loggedUser}))}async meIsconnected(){if(!this.client.isConnected||!this.client.userId)throw new ApiError("User not connected",401);return this.client._logger.info("UserApi","meIsconnected",this.client.userId),this.loggedUser=new User(this.client,{id:this.client.userId},{EndpointApi:EndpointApi,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment}),this.loggedUser}async register({name:e,username:t,email:n,pwd:r}){return this.client.safeCall((async()=>{const o=await this.client.callEndpoint("PERSON_REGISTER",{name:e,username:t,email:n,pwd:r});if(!ee(o))throw new ApiError("Requête mise en file (offline/circuit breaker)",503,o);if(!1===o?.data?.result)throw new ApiResponseError(o.data.msg,o.status,o.data);return o.data}))}async recoverPassword(e){return this.client.safeCall((async()=>{const t=await this.client.callEndpoint("PASSWORD_RECOVERY",{email:e});if(!ee(t))throw new ApiError("Requête mise en file (offline/circuit breaker)",503,t);if(!1===t?.data?.result)throw new ApiResponseError(t.data.msg,t.status,t.data);return t.data}))}}f("User",User),f("Organization",Organization),f("Project",Project),f("Event",Event),f("Poi",Poi),f("Badge",Badge),f("EndpointApi",EndpointApi),f("News",News),f("Comment",Comment),f("Answer",Answer);class Api{_loggedUser;_client;static async userLogin(e,t,n){const r=Api.userApi(n);return await Api.userApiLogin(r,e,t)}static userApi(e){try{return new UserApi(e)}catch(e){throw console.error("[Api.userApi] Erreur lors de la création d'un objet utilisateur :",e.message),e}}static async userApiLogin(e,t,n){try{if(!e)throw new ApiError("userApi is not defined",500);if(!e.client)throw new ApiError("userApi.client is not defined",500);if(e.client.isConnected){const t=await e.meIsconnected();return new Api(t,e.client)}{if(!t||!n)throw new ApiError("email and password are required",400);const r=await e.login(t,n);return new Api(r,e.client)}}catch(e){if(e instanceof ApiClientError&&e?.details?.error)throw new ApiAuthenticationError(e.details.error,e.status,e.details);throw e}}constructor(e,t){this._loggedUser=e,this._client=t}async me(){if(!this._loggedUser)throw new ApiAuthenticationError("Accès refusé : utilisateur non authentifié.",401);return await this._loggedUser.get(),this._loggedUser}async user(e){try{if(e.id||e.slug){const t=new User(this._client,e,{EndpointApi:EndpointApi,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment});return await t.get(),t}return new User(this._client,e,{EndpointApi:EndpointApi,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment})}catch(e){throw console.error("[Api.user] Erreur lors de la création d'un objet utilisateur public :",e.message),e}}async organization(e){try{const t=new Organization(this._client,e,{EndpointApi:EndpointApi,User:User,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment,Answer:Answer});if(!e.id&&!e.slug)throw new Error("Vous devez fournir un id ou un slug pour créer une instance Organization.");return await t.get(),t}catch(e){throw console.error("[Api.organization] Erreur lors de la création d'un objet organisation :",e.message),e}}async project(e){try{const t=new Project(this._client,e,{EndpointApi:EndpointApi,User:User,Organization:Organization,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment});if(!e.id&&!e.slug)throw new Error("Vous devez fournir un id ou un slug pour créer une instance Project.");return await t.get(),t}catch(e){throw console.error("[Api.project] Erreur lors de la création d'un objet projet :",e.message),e}}async event(e){try{const t=new Event(this._client,e,{EndpointApi:EndpointApi,User:User,Organization:Organization,Project:Project,Poi:Poi,Badge:Badge,News:News,Comment:Comment});if(!e.id&&!e.slug)throw new Error("Vous devez fournir un id ou un slug pour créer une instance Event.");return await t.get(),t}catch(e){throw console.error("[Api.event] Erreur lors de la création d'un objet événement :",e.message),e}}async poi(e){try{const t=new Poi(this._client,e,{EndpointApi:EndpointApi,User:User,Organization:Organization,Project:Project,Poi:Poi,Badge:Badge,News:News,Comment:Comment});if(!e.id&&!e.slug)throw new Error("Vous devez fournir un id ou un slug pour créer une instance Poi.");return await t.get(),t}catch(e){throw console.error("[Api.poi] Erreur lors de la création d'un objet poi :",e.message),e}}async answer(e){try{const t=new Answer(this._client,e,{EndpointApi:EndpointApi,User:User,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment});if(!e.id)throw new Error("Vous devez fournir un id pour créer une instance Answer.");return await t.get(),t}catch(e){throw console.error("[Api.answer] Erreur lors de la création d'un objet Answer :",e.message),e}}async entitySlug(e){if(!e)throw new ApiError("slug requis",400);try{const t=await this.endpointApi.getElementsKey({pathParams:{slug:e}});if(t.contextId&&t.contextType){const n=w(t.contextType,this._client,{id:t.contextId});if(!n)throw new ApiResponseError(`Le type d'entité pour le slug ${e} n'est pas reconnu`,200,t);return await n.get(),n}throw new ApiResponseError(`Le slug ${e} n'est pas valide`,200,t)}catch(t){throw t instanceof ApiResponseError?new ApiResponseError(`Impossible de récupérer l'identifiant pour le slug ${e}`,t.status,t.responseData):t}}get client(){return this._client}get endpointApi(){return new EndpointApi(this._client)}logout(){this._loggedUser=null,this._client.resetSession(),this._client._logger.info("UserApi: User logged out")}}class OfflineQueueStorageStrategy{}class MemoryOfflineStorage extends OfflineQueueStorageStrategy{_queue=[];constructor(){super()}async loadQueue(){return this._queue}async saveQueue(e){this._queue=[...e]}}class LocalStorageOfflineStorage extends OfflineQueueStorageStrategy{key;constructor(e="cocolight-api-offline-queue"){super(),this.key=e}async loadQueue(){try{const e=localStorage.getItem(this.key);return(e?JSON.parse(e):null)??[]}catch{return[]}}async saveQueue(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch(e){console.warn("[Offline] Échec du stockage localStorage",e)}}}class OfflineClientManager{_clients;_client;_offlineMode;_pingInterval;_offlineQueueStorage;_offlineQueue;_monitoringStarted;constructor(e){if(!(e&&e instanceof ApiClient))throw new Error("[OfflineClientManager] apiClient doit être une instance de ApiClient");this._clients=new Map,this._client=e,this._offlineMode=void 0,this._pingInterval=void 0,this._offlineQueueStorage=void 0,this._offlineQueue=[],this._monitoringStarted=void 0}static async attachTo(e,t={}){e._offlineClientManager=new OfflineClientManager(e);const n=await async function(e="auto"){if("memory"===e)return new MemoryOfflineStorage;if("localStorage"===e){if("undefined"!=typeof window&&window.localStorage)return new LocalStorageOfflineStorage;throw new Error("localStorage is not available in this environment.")}if("file"===e){if("undefined"!=typeof window&&window.localStorage)throw new Error("file storage is not available in this environment.");const{FileOfflineStorage:e}=await Promise.resolve().then((function(){return pe}));return new e}if("auto"===e){if("undefined"!=typeof window&&window.localStorage)return new LocalStorageOfflineStorage;{const{FileOfflineStorage:e}=await Promise.resolve().then((function(){return pe}));return new e}}throw new Error(`Unsupported offline storage strategy: ${e}`)}(t?.offlineStorageStrategy||"auto");await e._offlineClientManager._initOfflineQueue(n),t?.disableOfflineMonitoring||e._offlineClientManager.startOfflineMonitoring(t)}async getClient(e){const t=`${e.baseURL}|${e.accessToken}`;if(this._clients.has(t))return this._clients.get(t);const n=new ApiClient({baseURL:e.baseURL,accessToken:e.accessToken,refreshToken:e.refreshToken,debug:this._client._debug});return this._clients.set(t,n),n}async replayAction(e){const t=await this.getClient(e.meta);try{const n=await t.callEndpoint(e.constant,e.data,e.options?.transformResponseData??!0,e.options?.validateResponseSchema??!0);return this._client._logger.info(`[OfflineReplay] Succès ${e.constant} sur ${e.meta.baseURL}`),n}catch(t){throw this._client._logger.error(`[OfflineReplay] Échec ${e.constant}`,t.message),t}}startOfflineMonitoring({interval:e=3e4,disableOfflineMonitoring:t=!1}={}){t||this._monitoringStarted||(this._monitoringStarted=!0,this._offlineMode="undefined"!=typeof window&&"undefined"!=typeof navigator&&!navigator.onLine,"undefined"!=typeof window&&(window.addEventListener("online",(()=>this.setOfflineMode(!1))),window.addEventListener("offline",(()=>this.setOfflineMode(!0)))),this._pingInterval=setInterval((async()=>{const e=this._offlineMode;try{await this._client._client.head("/api/cocolight/infoserver",{timeout:5e3}),e&&this.setOfflineMode(!1)}catch{this._client._logger.error("[OfflineMonitor] ping() échoué → passage en offline"),this.setOfflineMode(!0)}}),e))}setOfflineMode(e){this._offlineMode!==e&&(this._offlineMode=e,"function"==typeof this._client.emit&&this._client.emit("offlineModeChanged",e),this._client._logger.info(`[ApiClient] Mode offline : ${e} (set depuis monitoring)`),e||"function"!=typeof this._replayOfflineQueue||this._replayOfflineQueue())}isOffline(){return!!this._offlineMode}async _enqueueOfflineAction({constant:e,data:t,options:n={}}){if(!this._offlineQueueStorage)throw new Error("[OfflineClientManager] _offlineQueueStorage non initialisé");const r=this._client.getToken()||this._client.getRefreshToken(),o=this._client._endpoints.find((t=>t.constant===e));if("required"===(o?.authPolicy||("none"===o?.auth?"none":"required"))&&!r)return void this._client._logger.warn(`[Offline] Action ignorée : token requis mais absent (${e})`);const i={constant:e,data:t,options:n,meta:{baseURL:this._client._baseURL,accessToken:this._client.getToken(),refreshToken:this._client.getRefreshToken(),timestamp:Date.now()}};this._offlineQueue.push(i),await this._offlineQueueStorage.saveQueue(this._offlineQueue),this._client._logger.info(`[Offline] Action mise en file : ${e}`)}async _replayOfflineQueue(){if(!this._offlineQueueStorage)throw new Error("[OfflineClientManager] _offlineQueueStorage non initialisé");const e=[...this._offlineQueue];this._offlineQueue=[],await this._offlineQueueStorage.saveQueue([]);for(const t of e){const e=this._client._endpoints.find((e=>e.constant===t.constant)),n=e?.authPolicy||("none"===e?.auth?"none":"required"),r=t.meta.accessToken||t.meta.refreshToken;if("required"!==n||r)try{await this.replayAction(t)}catch(e){this._client._logger.error("[Offline] Relecture échouée :",e.message),this._offlineQueue.push(t)}else this._client._logger.warn(`[Offline] Rejetée : token requis manquant (${t.constant})`)}await this._offlineQueueStorage.saveQueue(this._offlineQueue)}async _initOfflineQueue(e){if(!(e&&e instanceof OfflineQueueStorageStrategy))throw new Error("[OfflineClientManager] storageStrategy doit être une instance de OfflineQueueStorageStrategy");this._offlineQueueStorage=e,this._offlineQueue=await e.loadQueue()}}const te=["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],ne=["abandoned","concept","development","production","started","testing","idea","mature","qa","finished"],re=["workshop","competition","concert","contest","conference","debate","exhibition","festival","crowdfunding","fair","course","protest","market","film","getTogether","meeting","spectacle","internship","stand","others"],oe=["link","tool","machine","software","rh","Resource material","Financial Ressource","ficheBlanche","geoJson","compostPickup","video","sharedLibrary","recoveryCenter","trash","history","something2See","funPlace","place","artPiece","streetArts","openScene","stand","parking","other"],ie={ApiClient:ApiClient,Api:Api,error:h,reactive:q,effect:j,batch:k,isSignal:x,reactiveObject:N,isReactive:M,computed:B,watch:$,getSignals:z,subscribeTo:R,tokenStorageStrategy:{createDefaultTokenStorageStrategy:async function(e="auto"){if("memory"===e)return new MemoryStorageStrategy;if("localStorage"===e){if("undefined"!=typeof window&&window.localStorage)return new LocalStorageStrategy;throw new Error("localStorage is not available in this environment.")}if("file"===e){if("undefined"!=typeof window&&window.localStorage)throw new Error("file storage is not available in this environment.");const{FileStorageStrategy:e}=await Promise.resolve().then((function(){return ce}));return new e}if("undefined"!=typeof window&&window.localStorage)return new LocalStorageStrategy;const{FileStorageStrategy:t}=await Promise.resolve().then((function(){return ce}));return new t},TokenStorageStrategy:TokenStorageStrategy,createDefaultMultiServerTokenStorageStrategy:async function(e="auto"){if("memory"===e)return new MultiServerMemoryStorageStrategy;if("localStorage"===e){if("undefined"!=typeof window&&void 0!==window.localStorage)return new MultiServerLocalStorageStrategy;throw new Error("localStorage n'est pas disponible dans cet environnement.")}if("file"===e){if("undefined"!=typeof window&&void 0!==window.localStorage)throw new Error("Le stockage fichier n'est pas disponible côté navigateur.");const{MultiServerFileStorageStrategy:e}=await Promise.resolve().then((function(){return ae}));return new e}if("undefined"!=typeof window&&void 0!==window.localStorage)return new MultiServerLocalStorageStrategy;const{MultiServerFileStorageStrategy:t}=await Promise.resolve().then((function(){return ae}));return new t},MultiServerTokenStorageStrategy:MultiServerTokenStorageStrategy},helper:{fromEntityJSON:g,restorePaginationFromJSON:BaseEntity.restorePaginationFromJSON},OfflineClientManager:OfflineClientManager};var se=Object.freeze({__proto__:null,bufferToReadable:async function(e){const{Readable:t}=await import("stream");return t.from(e)},createPassThrough:async function(){const{PassThrough:e}=await import("stream");return new e}});var ae=Object.freeze({__proto__:null,MultiServerFileStorageStrategy:class MultiServerFileStorageStrategy extends MultiServerTokenStorageStrategy{filePath;constructor(e="tokens.json",t=u.join(l.homedir(),".config","cocolight")){super(),this.filePath=u.join(t,e),m.existsSync(t)||m.mkdirSync(t,{recursive:!0})}_readFile(){if(!m.existsSync(this.filePath))return{};try{return JSON.parse(m.readFileSync(this.filePath,"utf8"))}catch{return{}}}_writeFile(e){m.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf8")}getAccessToken(){const e=this._requireBaseURL();return this._readFile()[e]?.accessToken??null}setAccessToken(e){const t=this._requireBaseURL(),n=this._readFile();n[t]={...n[t]||{},accessToken:e},this._writeFile(n)}getRefreshToken(){const e=this._requireBaseURL();return this._readFile()[e]?.refreshToken??null}setRefreshToken(e){const t=this._requireBaseURL(),n=this._readFile();n[t]={...n[t]||{},refreshToken:e},this._writeFile(n)}clear(){const e=this._requireBaseURL(),t=this._readFile();delete t[e],this._writeFile(t)}getServers(){return Object.keys(this._readFile())}exportAll(){return this._readFile()}}});var ce=Object.freeze({__proto__:null,FileStorageStrategy:class FileStorageStrategy extends TokenStorageStrategy{dir;filePath;constructor(e="tokens.json",t=u.join(l.homedir(),".config","cocolight")){super(),this.dir=t,this.filePath=u.join(t,e),this._ensureDirectoryExists()}_ensureDirectoryExists(){m.existsSync(this.dir)||m.mkdirSync(this.dir,{recursive:!0})}_readFile(){if(!m.existsSync(this.filePath))return{};try{return JSON.parse(m.readFileSync(this.filePath,"utf8"))}catch(e){return console.error("Error reading token file:",e),{}}}_writeFile(e){m.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf8")}getAccessToken(){return this._readFile().accessToken||null}setAccessToken(e){const t=this._readFile();t.accessToken=e,this._writeFile(t)}getRefreshToken(){return this._readFile().refreshToken||null}setRefreshToken(e){const t=this._readFile();t.refreshToken=e,this._writeFile(t)}clear(){this._writeFile({})}}});var pe=Object.freeze({__proto__:null,FileOfflineStorage:class FileOfflineStorage extends OfflineQueueStorageStrategy{dir;filePath;constructor(e="offline-queue.json",t=u.join(l.homedir(),".config","cocolight")){super(),this.dir=t,this.filePath=u.join(t,e),this._ensureDirectoryExists()}_ensureDirectoryExists(){m.existsSync(this.dir)||m.mkdirSync(this.dir,{recursive:!0})}_readFile(){if(!m.existsSync(this.filePath))return[];try{return JSON.parse(m.readFileSync(this.filePath,"utf8"))}catch(e){return console.error("Erreur lecture offline queue :",e),[]}}_writeFile(e){try{m.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf8")}catch(e){console.warn("[OfflineQueue] Erreur d'écriture:",e)}}async loadQueue(){return this._readFile()}async saveQueue(e){this._writeFile(e)}}});export{re as EVENT_TYPES,te as ORGANIZATION_TYPES,oe as POI_TYPES,ne as PROJECT_AVANCEMENTS,ie as default};
1
+ import e from"bson-objectid";import*as t from"file-type";import*as n from"ajv";import*as r from"ajv-formats";import*as o from"ejson";import*as i from"pino";import{EventEmitter as s}from"events";import{AggregateAjvError as a}from"@segment/ajv-human-errors";import c from"axios";import p from"axios-retry";import{jwtDecode as d}from"jwt-decode";import*as m from"fs";import*as l from"os";import*as u from"path";class ApiError extends Error{name="ApiError";status;details;constructor(e,t,n){super(e),this.status=t,this.details=n}}class ApiClientError extends ApiError{name="ApiClientError";constructor(e,t,n){super(e,t,n)}}class ApiValidationError extends Error{name="ApiValidationError";status;messages;details;constructor(e,t,n,r=null){super(e),this.status=t,this.messages=n,this.details=r}}class CircuitBreakerError extends ApiError{name="CircuitBreakerError";constructor(e){super(e,503)}}class ApiResponseError extends Error{name="ApiResponseError";status;responseData;details;constructor(e,t,n,r=null){super(e),this.status=t,this.responseData=n,this.details=r}}class ApiAuthenticationError extends ApiError{name="ApiAuthenticationError";constructor(e,t,n){super(e,t,n)}}var h=Object.freeze({__proto__:null,ApiAuthenticationError:ApiAuthenticationError,ApiClientError:ApiClientError,ApiError:ApiError,ApiResponseError:ApiResponseError,ApiValidationError:ApiValidationError,CircuitBreakerError:CircuitBreakerError});const y=new Map;function f(e,t){y.set(e,t)}function g(e,t=null){if(!(n=e)||"object"!=typeof n||!("__entityTag"in n))return e;var n;let r=t;const o=e;if(o.parent&&"object"==typeof o.parent){const e=o.parent,n=e.serverData?.id||e.id;if(t&&"id"in t&&t.id===n)r=t;else{const e=g(o.parent,t);e&&"object"==typeof e&&"id"in e&&(r=e)}}let i=e.serverData?.collection;if(i||(i={User:"citoyens",Organization:"organizations",Project:"projects",Event:"events",Poi:"poi",News:"news",Badge:"badges",Comment:"comments",Answer:"answers"}[e.__entityTag]||null),!i)return e;const s=function(e,t){const n=y.get(t),r=t,o={EndpointApi:y.get("EndpointApi"),User:"User"===r?n:y.get("User"),Organization:"Organization"===r?n:y.get("Organization"),Project:"Project"===r?n:y.get("Project"),Event:"Event"===r?n:y.get("Event"),Poi:"Poi"===r?n:y.get("Poi"),Badge:"Badge"===r?n:y.get("Badge"),News:"News"===r?n:y.get("News"),Comment:"Comment"===r?n:y.get("Comment"),Answer:"Answer"===r?n:y.get("Answer")};return{citoyens:{entityClass:o.User,deps:o},organizations:{entityClass:o.Organization,deps:o},projects:{entityClass:o.Project,deps:o},events:{entityClass:o.Event,deps:{...o,Badge:void 0}},poi:{entityClass:o.Poi,deps:{...o,Badge:void 0,News:void 0,Comment:void 0}},news:{entityClass:o.News,deps:{...o}},badges:{entityClass:o.Badge,deps:{EndpointApi:o.EndpointApi,User:o.User,Organization:o.Organization,Project:o.Project}},comments:{entityClass:o.Comment,deps:{...o}},answers:{entityClass:o.Answer,deps:{...o}}}[e]||null}(i,e.__entityTag);if(!s)return e;if(!s.entityClass?.fromJSON)throw new Error(`Classe inconnue ou fromJSON manquant pour ${e.__entityTag}`);return s.entityClass.fromJSON(e,r,s.deps)}function w(e,t=null,n={}){const r={citoyens:{entityTag:"User",meta:e=>_(e,{remove:[]})},organizations:{entityTag:"Organization",meta:e=>_(e,{remove:[]})},projects:{entityTag:"Project",meta:e=>_(e,{remove:[]})},events:{entityTag:"Event",meta:e=>_(e,{remove:["Badge"]})},poi:{entityTag:"Poi",meta:e=>_(e,{remove:["Badge","News","Comments"]})},news:{entityTag:"News",meta:e=>_(e,{remove:[]})},badges:{entityTag:"Badge",meta:()=>function(e){const t=y.get(e),n={EndpointApi:y.get("EndpointApi"),User:y.get("User"),Organization:y.get("Organization"),Project:y.get("Project")};return n[e]=t,{entityClass:t,deps:n}}("Badge")},comments:{entityTag:"Comment",meta:e=>_(e,{remove:[]})},answers:{entityTag:"Answer",meta:e=>_(e,{remove:[]})}},o=r[e];if(!o)return console.warn(`Collection inconnue : '${e}'`),null;const{entityTag:i,meta:s}=o,{entityClass:a,deps:c}=s(i);if(!a)throw new Error(`EntityClass introuvable pour ${i}`);return new a(t,n,c)}function _(e,t){const n=y.get(e),r={EndpointApi:y.get("EndpointApi"),User:y.get("User"),Organization:y.get("Organization"),Project:y.get("Project"),Event:y.get("Event"),Poi:y.get("Poi"),Badge:y.get("Badge"),News:y.get("News"),Comment:y.get("Comment"),Answer:y.get("Answer")};return r[e]=n,t.remove.forEach((e=>delete r[e])),{entityClass:n,deps:r}}const E=e=>e&&e.default?e.default:e,T=E(n),A=E(r),b=E(i),v=E(o),S=[],P=new WeakMap,I=new WeakMap;let O=0;const C=new Set;function j(e){const t=()=>{try{S.push(t),e()}finally{S.pop()}};return t(),t}function k(e){O++;try{e()}finally{if(O--,0===O){const e=Array.from(C);C.clear();for(const t of e)t()}}}function D(e){let t=e;const n=new Set;return{get value(){const e=S[S.length-1];return e&&n.add(e),t},set value(e){t!==e&&(t=e,O>0?n.forEach((e=>C.add(e))):n.forEach((e=>e())))},subscribe:e=>(n.add(e),()=>n.delete(e)),__isSignal:!0}}function x(e){return e&&!0===e.__isSignal}function L(e,t=[]){if("object"!=typeof e||null===e)return e;if(Array.isArray(e))return function(e,t){return new Proxy(e,{get(e,n,r){if("string"==typeof n&&!isNaN(+n)){const r=e[+n];return M(r)?r:L(r,[...t,n])}return Reflect.get(e,n,r)},set(e,n,r){if("string"==typeof n&&!isNaN(+n)){const o=L(r,[...t,n]);e[+n]=o}return!0}})}(e,t);if(e.__isReactive)return e;if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return e;if("undefined"!=typeof File&&e instanceof File)return e;if("undefined"!=typeof Blob&&e instanceof Blob)return e;if(e&&"function"==typeof e.pipe&&"function"==typeof e.on)return e;if(e instanceof Date)return e;if(e.__entityTag)return e;const n=new Map,r=new Proxy(e,{get(e,r){if("__raw"===r)return e;if("__isReactive"===r)return!0;if(!n.has(r)){const o=D(L(e[r],[...t,String(r)]));n.set(r,o)}return n.get(r).value},set(e,r,o){const i=L(o,[...t,String(r)]);if(!n.has(r)){const e=D(i);n.set(r,e)}return n.get(r).value=i,e[r]=function(e){return x(e)?e.value:e}(i),!0},deleteProperty:(e,t)=>(n.delete(t),Reflect.deleteProperty(e,t))});return I.set(r,n),r}function N(e){return"object"!=typeof e||null===e||e.__isReactive?e:L(e)}function M(e){return null!==e&&"object"==typeof e&&!0===e.__isReactive}function B(e){if(P.has(e))return P.get(e);const t=D();return j((()=>t.value=e())),P.set(e,t),t}function $(e,t){let n;j((()=>{const r=e();r!==n&&(t(r,n),n=r)}))}function z(e){return M(e)?I.get(e):null}function R(e,t,n){const r=z(e);if(!r||!r.has(t))return()=>{};const o=r.get(t);return o?.subscribe?.((()=>n(o.value)))??(()=>{})}var q=Object.freeze({__proto__:null,batch:k,computed:B,effect:j,getSignals:z,isReactive:M,isSignal:x,reactive:N,subscribeTo:R,watch:$});const{fromBuffer:U}=t,F=e;class BaseEntity{__entityTag;deps;apiClient;parent;userContext;endpointApi;data;meta;_draftData={};_initialDraftData={};_serverData=N({});_calledFromSave=!1;_syncReactiveDraft=!1;_isDeleted=!1;_add;_update;_allowedFieldsCache;_allowedFieldsMetadata;static entityTag="BaseEntity";static entityType;static SCHEMA_CONSTANTS;static VIRTUAL_SCHEMAS;static CUSTOM_FIELD_HANDLERS;_checkNotDeleted(){if(this._isDeleted)throw new ApiError(`Cet objet ${this.__entityTag} a été supprimé et ne peut plus être utilisé.`,400)}constructor(e,t={},n={},r={}){this.__entityTag=r.entityTag||this.getEntityTag(this._getCtor().entityTag)||"BaseEntity",this.deps=n;if("ApiClient"===this.getEntityTag(e?.__entityTag))this.apiClient=e,this.parent=null,this.userContext=null;else{if(!e||!("apiClient"in e))throw new ApiError("Parent invalide ou ApiClient manquant.",400);{const t=e;this.apiClient=t.apiClient,this.parent=t,this.userContext="User"===this.getEntityTag(t?.__entityTag)?t:t.userContext||null}}if("function"==typeof n.EndpointApi)this.endpointApi=new n.EndpointApi(this.apiClient);else{if("object"!=typeof n.EndpointApi)throw new ApiError("deps.EndpointApi doit être une classe ou une instance valide.",500);this.endpointApi=n.EndpointApi}this._serverData=N({});const{draft:o,proxy:i,initial:s}=this._buildDraftAndProxy({data:{...t,...this.defaultFields},serverData:this._serverData,constant:this._getCtor().SCHEMA_CONSTANTS,apiClient:this.apiClient,transforms:this.transforms,removeFields:this.removeFields});this._initialDraftData=s,this._draftData=o,this.data=i}_getCtor(){return this.constructor}getEntityTag=e=>e?.replace(/^_/,"");get id(){return this._draftData.id||null}get slug(){return this._draftData.slug||null}_id(e){this._draftData.id=e}get isConnected(){return this.apiClient.isConnected}get userId(){return this.apiClient.userId}get draftData(){return this._draftData}get initialDraftData(){return this._initialDraftData}get serverData(){return this._serverData}get isMe(){return!!(this.isConnected&&this.userId&&this.userContext?.id&&"string"==typeof this.userId&&"string"==typeof this.userContext?.id&&this.userId===this.userContext?.id)}getEntityType(){return this._getCtor().entityType}hasChanges(){const e=this._toRawDeep(this._draftData),t=this._serialize(e),n=this._serialize(this._initialDraftData);return JSON.stringify(t)!==JSON.stringify(n)}async refresh(){if(!this.id)throw new ApiError("Impossible de rafraîchir sans ID.",400);return this.get()}async save(){if(this._checkNotDeleted(),!this.isConnected)throw new ApiError("Non connecté.",401);this._calledFromSave=!0;try{const e={...this._draftData};if(!this.id&&"function"==typeof this._add)return await this._add(e),this._resetInitialDraftData(),this.userContext&&await(this.userContext?.refresh()),await this.refresh();if("function"==typeof this._update){const t=await this._update(e);if(this._resetInitialDraftData(),t)return await this.refresh()}return this._serverData}finally{this._calledFromSave=!1}}static fromServerData(e,t,n){const r=new this(t,{},n);return r._setData(e),r}_transformServerData(e){return e}_setData(e,{forceInitialDraftReset:t=!1}={}){this.userContext&&this.userContext!==this&&this.apiClient._logger?.debug?.(`[${this.__entityTag}] Mise à jour liée à userContext : ${this.userContext.id}`);const n=this._transformServerData(e)??{};if(this._serverData&&M(this._serverData)){for(const e of Object.keys(this._serverData))e in n||delete this._serverData[e];for(const e of Object.keys(n))this._serverData[e]=n[e]}else this._serverData=N({...n});const r=this._draftData?this._toRawDeep(this._draftData):{},o={...e||{},...this.defaultFields,...r},{draft:i,proxy:s,initial:a}=this._buildDraftAndProxy({data:o,serverData:this._serverData,previousDraft:this._draftData,constant:this._getCtor().SCHEMA_CONSTANTS,apiClient:this.apiClient,transforms:this.transforms,removeFields:this.removeFields});t?this._initialDraftData=structuredClone(this._toRawDeep(i)):this._initialDraftData||(this._initialDraftData=a),M(this._draftData)?this._updateDraftPreservingUserChanges(i):this._draftData=N(i),this.data||(this.data=s)}_updateDraftPreservingUserChanges(e){for(const t of Object.keys(this._draftData||{}))t in e||delete this._draftData[t];for(const t of Object.keys(e)){const n=this._draftData?.[t],r=this._initialDraftData?.[t];void 0!==n&&void 0!==r&&this._serialize(this._toRawDeep(n))!==this._serialize(r)||(this._draftData[t]=e[t])}}_resetInitialDraftData(){const e=this._toRawDeep(this._draftData);this._initialDraftData=structuredClone(e)}_toRawDeep(e){if(!this||"function"!=typeof this._toRawDeep)throw new Error("`this._toRawDeep` is not bound correctly. Use a lambda to preserve context.");if(x(e))return this._toRawDeep(e.value);if(e&&"object"==typeof e&&e.__isReactive&&e.__raw)return this._toRawDeep(e.__raw);if(e instanceof Date)return e;if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return e;if("undefined"!=typeof File&&e instanceof File)return e;if("undefined"!=typeof Blob&&e instanceof Blob)return e;if(e&&"function"==typeof e.pipe&&"function"==typeof e.on)return e;if(Array.isArray(e))return e.map((e=>this._toRawDeep(e)));if("object"==typeof e&&null!==e){const t={};for(const n of Object.keys(e))t[n]=this._toRawDeep(e[n]);return t}return e}defaultFields={};removeFields=[];transforms={};toJSON(){const e={};return this.parent?.id&&(e.id=this.parent.id),"function"==typeof this.parent?.getEntityType&&(e.type=this.parent.getEntityType()),this.parent?.__entityTag&&(e.__entityTag=this.parent.__entityTag),this.parent?.slug&&(e.slug=this.parent.slug),this.parent?.serverData&&(e.serverData={id:this.parent.serverData.id,collection:this.parent.serverData.collection,slug:this.parent.serverData.slug,...this.parent.serverData.name&&{name:this.parent.serverData.name},...this.parent.serverData.parent&&{parent:this.parent.serverData.parent},...this.parent.serverData.organizer&&{organizer:this.parent.serverData.organizer},...this.parent.serverData.links&&{links:this.parent.serverData.links}}),{__entityTag:this.__entityTag,__isSerializedEntity:!0,serverData:this._serialize(this._serverData),parent:Object.keys(e).length>0?e:null}}_serialize(e){try{return JSON.parse(v.stringify(this._removeUnserializables(e)))}catch(e){const t=e;return this.apiClient?._logger?.error?.("Erreur de sérialisation EJSON:",{message:t?.message,stack:t?.stack,error:e}),null}}_removeUnserializables(e,t=new WeakSet){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return e;if(e instanceof RegExp)return e;if(e&&"object"==typeof e&&"_bsontype"in e&&"ObjectID"===e._bsontype)return e;if(e instanceof Uint8Array||ArrayBuffer.isView(e))return e;if(e instanceof BaseEntity)return e.toJSON();if(t.has(e))return null;if(t.add(e),e.__isReactive&&"object"==typeof e.__raw)return this._removeUnserializables(e.__raw,t);if(Array.isArray(e))return e.map((e=>this._removeUnserializables(e,t)));const n={};for(const r of Object.keys(e)){const o=e[r];if("function"!=typeof o&&"symbol"!=typeof o&&void 0!==o)try{n[r]=this._removeUnserializables(o,t)}catch{n[r]=null}}return n}static _revive(e,t){const n=v.fromJSONValue(e);return this._deserializeNestedEntities(n,t)}static _deserializeNestedEntities(e,t){if(null===e||"object"!=typeof e)return e;if(e instanceof Date||e instanceof RegExp)return e;if(Array.isArray(e))return e.map((e=>this._deserializeNestedEntities(e,t)));if(e.__isSerializedEntity&&e.__entityTag&&e.serverData)return g(e,t);const n={};for(const[r,o]of Object.entries(e))n[r]=this._deserializeNestedEntities(o,t);return n}static fromJSON(e,t,n){if(!e||"object"!=typeof e||!("serverData"in e))throw new Error("Invalid JSON format: missing serverData");const{serverData:r}=e;return this.fromServerData(this._revive(r,t),t,n||{})}async call(e,t={}){return this.apiClient.safeCall((async()=>{const n=await this.apiClient.callEndpoint(e,t);return this.apiClient.checkAndThrowApiResponseError(n),n.data}))}async callNoConnected(e,t={}){if(this.isConnected)throw new ApiAuthenticationError("Vous devez ne devez pas être connecté pour faire cette action.",403);return this.call(e,t)}async callIsConnected(e,t={}){if(!this.isConnected)throw new ApiAuthenticationError("Vous devez être connecté pour faire cette action.",401);return"function"==typeof e?await e():this.call(e,t)}async callIsMe(e,t={}){if(!this.isMe)throw new ApiAuthenticationError("Vous devez être vous-même pour faire cette action.",403);return"function"==typeof e?await e():await this.callIsConnected(e,t)}async _validateImage(e){return await this._validateUploadInput(e,{allowedMimeTypes:["image/jpeg","image/png","image/jpg"],expectedType:"image"})}async _validateFile(e){return await this._validateUploadInput(e,{allowedMimeTypes:["application/pdf","text/plain","text/csv"],expectedType:"file"})}async _validateUploadInput(e,{allowedMimeTypes:t=[],expectedType:n="any"}){if(!e)throw new ApiValidationError("Le fichier est requis.",400,["Le fichier est requis"]);const r="undefined"==typeof window&&"undefined"!=typeof process;let o=null,i="";if("undefined"!=typeof File&&e instanceof File){if(i=e.type,!t.includes(i))throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);o=e}else if("undefined"!=typeof Blob&&e instanceof Blob){if(i=e.type,!t.includes(i))throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);const n=i.split("/")[1]||"bin",r=`${Date.now()}.${n}`;o=new File([e],r,{type:i})}else if(r&&Buffer.isBuffer(e)){const r=await U(e);if(!r)throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);if(i=r.mime,!t.includes(i))throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);if("image"===n){const t=r.ext,n=`${Date.now()}.${t}`;o=await this._createReadStreamFromBuffer(e,n,i)}else o=e}else{if(!r||!(s=e)||"object"!=typeof s||"function"!=typeof s.pipe||"function"!=typeof s.on)throw new ApiValidationError("Type de fichier non reconnu.",400,["Type de fichier non reconnu."]);{const n=e,r=[],s=await this._passThrough(),a=await this._passThrough(),c=4100;let p=0;n.on("data",(e=>{p<c&&(r.push(e),p+=e.length)})),n.pipe(s).pipe(a),await new Promise((e=>setTimeout(e,10)));const d=Buffer.concat(r),m=await U(d);if(!m)throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);if(i=m.mime,!t.includes(i))throw new ApiValidationError("Le type du fichier est invalide.",400,["Le type du fichier est invalide"]);a.path=`${Date.now()}.${m.ext}`,a.mimeType=i,o=a}}var s;return o}async _createReadStreamFromBuffer(e,t="file.bin",n="application/octet-stream"){const r=await this._bufferToReadable(e);return r.path=t,r.mimeType=n,r}async _bufferToReadable(e){if("undefined"==typeof window){const{bufferToReadable:t}=await Promise.resolve().then((function(){return se}));return t(e)}throw new Error("bufferToReadable ne doit pas être appelé dans le navigateur")}async _passThrough(){if("undefined"==typeof window){const{createPassThrough:e}=await Promise.resolve().then((function(){return se}));return e()}throw new Error("passThrough ne doit pas être appelé dans le navigateur")}_omitProps(e,t){if(!e||"object"!=typeof e)return{};const n={...e};for(const e of t)delete n[e];return n}_pickProps(e,t,n={}){if(!e||"object"!=typeof e)return{};const r={};for(const o of t)if(o in e){const t=e[o];"function"==typeof n[o]?r[o]=n[o](t,e):r[o]=t}return r}_hasAtLeastOne(e,t=[]){return t.some((t=>t in e&&null!=e[t]))}_createFilteredProxy(e){return new Proxy(e,{get(e,t,n){const r=e.filter((e=>!e._isDeleted));if("length"===t)return r.length;if("string"==typeof t&&/^\d+$/.test(t))return r[Number(t)];const o=Reflect.get(r,t,n);return"function"==typeof o?o.bind(r):o}})}_newId(){return F().toHexString()}_getAllowedFieldsForCurrentState(){if(!this._allowedFieldsMetadata)return this._allowedFieldsCache||[];const{combinedSchema:e,removeFields:t}=this._allowedFieldsMetadata,n=this._toRawDeep(this._draftData),r={...this.defaultFields,...n};let o=this._extractWritableFields(e,r);return r.id&&!o.includes("id")&&o.push("id"),r.slug&&!o.includes("slug")&&o.push("slug"),o=o.filter((e=>!t.includes(e))),o}_createDraftProxy(e,t={},n={},r=[],o={},i={},s=this){return new Proxy({},{get:(e,r)=>{if("string"==typeof r||"symbol"==typeof r){if("string"==typeof r&&r in n){const e=n[r],t=o[r];return"function"==typeof t?t(e,n):e}if(t&&"object"==typeof t&&"string"==typeof r&&r in t){const e=t[r],n=o[r];return"function"==typeof n?n(e,t):e}}},set:(t,r,o)=>{if("string"!=typeof r)return!1;const a=s._getAllowedFieldsForCurrentState();if(!a.includes(r)){const t=`[DraftProxy] Le champ "${r}" n'est pas autorisé.`;if(i.throwOnError)throw new ApiValidationError(t,400,[t],{field:r,value:o,allowedFields:a});return e._logger?.warn?.(t),!1}const c=n[r];return c&&"object"==typeof c&&!0===c.__isSignal?c.value=o:n[r]=o,!0},deleteProperty:(e,t)=>{if("string"!=typeof t)return!1;return!!s._getAllowedFieldsForCurrentState().includes(t)&&(delete n[t],!0)},has:(e,r)=>"string"==typeof r&&(r in n||t&&"object"==typeof t&&r in t),ownKeys:()=>{const e=new Set([...Object.keys(t||{}),...Object.keys(n||{})]);return Array.from(e)},getOwnPropertyDescriptor:(e,r)=>{if("string"==typeof r)return r in n||t&&"object"==typeof t&&r in t?{enumerable:!0,configurable:!0}:void 0}})}_extractWritableFields(e={},t={},n={defs:{},visited:new Set}){if(!e||"object"!=typeof e)return[];if(e.$id&&n.visited.has(e.$id))return[];e.$id&&n.visited.add(e.$id),n.defs=e.$defs||e.definitions||n.defs;const r=[];if(e.$ref){const o=e.$ref.replace(/^#\/?(\$defs|definitions)\//,""),i=n.defs[o];i&&r.push(...this._extractWritableFields(i,t,n))}if(e.allOf&&e.allOf.forEach((e=>r.push(...this._extractWritableFields(e,t,n)))),e.if&&e.then){const o=e.if.properties;let i=!0;if(o)for(const e in o){const n=o[e]?.const;if(t[e]!==n){i=!1;break}}i&&e.then?r.push(...this._extractWritableFields(e.then,t,n)):!i&&e.else&&r.push(...this._extractWritableFields(e.else,t,n))}return e.properties&&r.push(...Object.entries(e.properties).filter((([e,t])=>!0!==t.readOnly&&void 0===t.const)).map((([e])=>e))),Array.from(new Set(r))}_buildDraftAndProxy({data:e={},serverData:t=null,previousDraft:n=null,constant:r,apiClient:o,transforms:i={},throwOnError:s=!0,removeFields:a=[]}){const c=Array.isArray(r)?r:[r],p={allOf:[],$defs:{}};for(const e of c){let t=o.getRequestSchema(e);const n=this._getCtor(),r=n.VIRTUAL_SCHEMAS?.[e];if(r&&(t=this._mergeSchemas(t,r)),!t)throw new ApiError(`Unable to find schema for ${e}.`,404);if(t.$defs)for(const[n,r]of Object.entries(t.$defs))p.$defs[n]?o._logger.warn(`Duplicate $defs key '${n}' from schema '${e}'`):p.$defs[n]=r;p.allOf.push(t)}let d=this._extractWritableFields(p,e);e.id&&-1===d.indexOf("id")&&d.push("id"),e.slug&&-1===d.indexOf("slug")&&d.push("slug"),d=d.filter((e=>!a.includes(e))),this._allowedFieldsCache=d,this._allowedFieldsMetadata={combinedSchema:p,transforms:i,removeFields:a};const m=Object.fromEntries(d.map((t=>{const n=e[t];return[t,"function"==typeof i[t]?i[t](n,e):n]})).filter((([e,t])=>void 0!==t))),l=structuredClone?structuredClone(m):JSON.parse(JSON.stringify(m)),u=n&&M(n)?Object.assign(n,m):N(m),h=M(t)?t:t&&"object"==typeof t?N(t):t;return{draft:u,proxy:this._createDraftProxy(o,h,u,d,i,{throwOnError:s}),initial:l}}async _invokeBlockMethod(e,t,n){const r=this[t];return await r.call(this,n)}_isUploadType(e){return!("undefined"==typeof Buffer||!Buffer.isBuffer(e))||("undefined"!=typeof File&&e instanceof File||("undefined"!=typeof Blob&&e instanceof Blob||!(!e||"function"!=typeof e.pipe||"function"!=typeof e.on)))}_compareValues(e,t){return this._isUploadType(e)||this._isUploadType(t)?e!==t:JSON.stringify(this._toRawDeep(e))!==JSON.stringify(this._toRawDeep(t))}_mergeSchemas(e,t){return e?t?{allOf:[e,t],$defs:{...e.$defs,...t.$defs}}:e:t}_hasFieldChanged(e){const t=this._draftData[e],n=this._initialDraftData[e];return this._compareValues(t,n)}async _invokeCustomFieldHandler(e,t,n){const r=this[e];if("function"!=typeof r)throw new ApiError(`Custom handler "${e}" not found for field "${n}"`,500);return await r.call(this,t)}_extractChangedFieldsFromSchema(e,t,n={},r,o=[]){const i=e.getRequestSchema(t);let s=this._extractWritableFields(i,n);const a={},c=r?.()||{};s=s.filter((e=>!o.includes(e)));for(const e of s){if(void 0===n[e])continue;const t=n[e],r=c[e];this._compareValues(t,r)&&(a[e]=t)}return Object.keys(a).length>0?a:null}_extractAllValidFieldsFromSchema(e,t,n={},r,o=[]){const i=e.getRequestSchema(t);let s=this._extractWritableFields(i,n);const a={},c={},p=r?.()||{};s=s.filter((e=>!o.includes(e)));for(const e of s){if(void 0===n[e])continue;const t=n[e],r=p[e];JSON.stringify(t)!==JSON.stringify(r)&&(a[e]=t),c[e]=t}return Object.keys(a).length>0?c:null}async _resolveId(e){if(!this.id&&this.slug)try{const t=await this.endpointApi.getElementsKey({pathParams:{slug:this.slug}});if(!t.contextId||t.contextType!==e)throw new ApiResponseError(`Le slug ${this.slug} ne correspond pas à un ${e}`,200,t);this._id(t.contextId)}catch(t){if(t instanceof ApiResponseError){throw t.responseData.contextType!==e?t:new ApiResponseError(`Impossible de récupérer l'identifiant pour le slug ${this.slug}`,t.status,t.responseData)}throw t}if(!this.id)throw new ApiError(`Impossible de résoudre l'identifiant pour le type ${e}.`,404);return this.id}async _getPublicProfile(){if(await this._resolveId(this.getEntityType()),!this.id)throw new ApiError("L'identifiant de l'entité n'est pas défini.",400);const e=this.getEntityType();if("news"===e||"comments"===e)throw new ApiError("getElementsAbout ne supporte pas le type 'news'.",400);return this.endpointApi.getElementsAbout({pathParams:{id:this.id,type:e},tpl:"ficheInfoElement"})}_getEntityMeta(e){const t=this.constructor,n=this.__entityTag,r={EndpointApi:this.deps.EndpointApi,User:"User"===n?t:this.deps.User,Organization:"Organization"===n?t:this.deps.Organization,Project:"Project"===n?t:this.deps.Project,Event:"Event"===n?t:this.deps.Event,Poi:"Poi"===n?t:this.deps.Poi,Badge:"Badge"===n?t:this.deps.Badge,News:"News"===n?t:this.deps.News,Comment:"Comment"===n?t:this.deps.Comment,Answer:"Answer"===n?t:this.deps.Answer};return{citoyens:{entityClass:r.User,deps:r},organizations:{entityClass:r.Organization,deps:r},projects:{entityClass:r.Project,deps:r},events:{entityClass:r.Event,deps:{...r,Badge:void 0}},poi:{entityClass:r.Poi,deps:{...r,Badge:void 0,News:void 0}},news:{entityClass:r.News,deps:{...r}},badges:{entityClass:r.Badge,deps:{EndpointApi:r.EndpointApi,User:r.User,Organization:r.Organization,Project:r.Project}},comments:{entityClass:r.Comment,deps:{...r}},answers:{entityClass:r.Answer,deps:{...r}}}[e]||null}_linkEntity(e,t){const n=this._getEntityMeta(e);return n?n.entityClass.fromServerData(t,this,n.deps):t}_linkNestedEntity(e){if(!e||"object"!=typeof e)return e;if(!e.id||!e.type)return e;try{return this._linkEntity(e.type,e)}catch(t){return this.apiClient._logger?.warn?.(`Impossible de lier l'entité imbriquée de type ${e.type}:`,t),e}}async _linkEntityById(e,t,n){const r=this._getEntityMeta(e);if(!r)return null;const o=new r.entityClass(this,{id:t},r.deps);return n?.skipGet||await o.get(),o}_linkEntities(e){return e.flatMap((e=>e?.collection?[this._linkEntity?.(e.collection,e)??e]:(this.apiClient._logger?.warn?.(`Objet ignoré car sans 'collection' : ${e?.id}`),[])))}async linkEntitiesFromServerData(e,t={},n={}){const r=n.key||e,o="function"==typeof n.mapFn?n.mapFn:null,i=e=>!0===e||"true"===e,s=e=>!1===e||"false"===e,a=this.serverData?.[r],c=[];if(a&&"object"==typeof a&&Object.keys(a).length>0)for(const n of Object.keys(a)){const r=a[n],p=Object.entries(t).every((([e,t])=>{const n=r[e];if("function"==typeof t)try{return t(n)}catch(t){return console.warn(`Erreur dans le filtre personnalisé pour ${e}`,t),!1}return t instanceof RegExp?"string"==typeof n&&t.test(n):"string"==typeof t&&"string"==typeof n?n.toLowerCase().includes(t.toLowerCase()):i(t)?i(n):s(t)?s(n):"string"!=typeof n||"string"!=typeof t||isNaN(Date.parse(n))||isNaN(Date.parse(t))?n===t:new Date(n).getTime()===new Date(t).getTime()}));if(p)try{const t=await this._linkEntityById(e,n);t&&(t.meta=r,c.push(o?o(t):t))}catch(t){this.apiClient._logger?.error?.(`Erreur lors de la récupération de l'entité ${e} (${n}) :`,t)}}return c}_entityInstanceData(e,t){const n=this._getEntityMeta(e);if(!n)throw new ApiError(`Type d'entité inconnu: ${e}`,400);const r=this.__entityTag,o=this.constructor;return new n.entityClass(this,t,{[r]:o,...n.deps})}async entity(e,t={}){try{const n=this._entityInstanceData(e,t),r={citoyens:["id","slug"],organizations:["id","slug"],projects:["id","slug"],events:["id","slug"],poi:["id","slug"],news:["id"],badges:["id"],comments:[],answers:["id"]}[e];return r&&this._hasAtLeastOne(t,r)&&await n.get(),n}catch(t){throw this.apiClient._logger.error(`[Api.${this.__entityTag}.${e}] Erreur lors de la création d'une instance ${e} :`,t.message),t}}async entityBySlug(e){if(!e)throw new ApiError("Le slug est requis.",400);try{const t=await this.endpointApi.getElementsKey({pathParams:{slug:e}});if(t.contextId&&t.contextType){const e=await this.entity(t.contextType,{id:t.contextId});return await this._fixEntityUserContext(e),e}throw new ApiResponseError(`Le slug ${e} n'est pas valide`,200,t)}catch(t){throw t instanceof ApiResponseError?new ApiResponseError(`Impossible de récupérer l'identifiant pour le slug ${e}`,t.status,t.responseData):t}}async _fixEntityUserContext(e){const t=e.getEntityType();if(!["events","projects","poi"].includes(t))return;const n=this._extractRealParent(e);if(!n)return;const r=await this._findOrCreateParent(n);r&&r!==e.parent&&(e.userContext=this._extractUserContext(r),e.parent=r)}_extractRealParent(e){const t=e.serverData;if("events"===e.getEntityType()){const e=t;if(e.organizer){const t=Object.entries(e.organizer),n=t.find((([e,t])=>"projects"===t.type));if(n)return{type:"projects",id:n[0]};const r=t.find((([e,t])=>"organizations"===t.type));if(r)return{type:"organizations",id:r[0]};const o=t.find((([e,t])=>"citoyens"===t.type));if(o)return{type:"citoyens",id:o[0]};const i=t[0];if(i&&i[1])return{type:i[1].type,id:i[0]}}}const n=t;if(n.parent){const e=Object.entries(n.parent)[0];if(e&&e[1])return{type:e[1].type,id:e[0]}}return null}async _findOrCreateParent(e){try{let t=this.parent;for(;t;){if(t.id===e.id&&t.getEntityType()===e.type)return t;t=t.parent}const n={citoyens:"citoyens",organizations:"organizations",projects:"projects"}[e.type];if(n){const t=this._entityInstanceData(n,{id:e.id});return await t.get(),t}return null}catch(e){return this.apiClient._logger?.warn?.("Impossible de créer le parent réel:",e),null}}_extractUserContext(e){return"User"===this.getEntityTag(e?.__entityTag)?e:e.userContext||null}_isAdminViaHierarchy(){const e=this.getEntityType(),t=this.serverData;let n;if("events"===e)n=t?.organizer;else{if("projects"!==e&&"poi"!==e)return!1;n=t?.parent}if(!n||"object"!=typeof n)return!1;for(const[e,t]of Object.entries(n)){if(!t||"object"!=typeof t)continue;const n=t.type;if(n&&this._isAdminOfParent(e,n))return!0}return!1}_isAdminOfParent(e,t){const n=this.userContext?.serverData?.links;if(!n)return!1;let r;if("citoyens"===t)return!1;if("organizations"===t)r="memberOf";else{if("projects"!==t)return!1;r="projects"}const o=n[r];if(!o)return!1;const i=o[e];return this._validateUserLink(i)&&!0===i?.isAdmin&&!i?.isAdminPending}_buildLinkFilters(e,{linkType:t,isAdmin:n,isAdminPending:r,isInviting:o,toBeValidated:i=!1,roles:s=[]}){if("string"!=typeof e||null===e)throw new TypeError("id doit être une chaîne non-nulle.");if("string"!=typeof t)throw new TypeError("linkType doit être une chaîne.");if(void 0!==n&&"boolean"!=typeof n)throw new TypeError("isAdmin doit être un booléen.");if(void 0!==r&&"boolean"!=typeof r)throw new TypeError("isAdminPending doit être un booléen.");if(void 0!==o&&"boolean"!=typeof o)throw new TypeError("isInviting doit être un booléen.");if(void 0!==i&&"boolean"!=typeof i)throw new TypeError("toBeValidated doit être un booléen.");if(!Array.isArray(s))throw new TypeError("roles doit être un tableau de chaînes.");const a=`links.${t}.${e}`,c={[`${a}`]:{$exists:!0}};return"boolean"==typeof i&&(c[`${a}.toBeValidated`]={$exists:i}),"boolean"==typeof o&&(c[`${a}.isInviting`]={$exists:o}),!0===n&&(c[`${a}.isAdmin`]={$exists:!0}),!0===r&&(c[`${a}.isAdminPending`]={$exists:!0}),s.length>0&&(c[`${a}.roles`]={$in:s}),c}_getLinkMeta(){const e=this.getEntityType(),t={organizations:{linkType:"memberOf",connectTypeConnect:"member",connectTypeDisconnect:"members"},projects:{linkType:"projects",connectTypeConnect:"contributor",connectTypeDisconnect:"contributors"},events:{linkType:"events",connectTypeConnect:"attendee",connectTypeDisconnect:"attendees"},citoyens:{linkType:"friends",connectTypeConnect:"friend",connectTypeDisconnect:"friends"}}[e];if(!t)throw new ApiError(`Aucune correspondance de lien définie pour le type d'entité "${e}"`,404);return t}_checkLinkableEntity(){try{this._getLinkMeta()}catch(e){if(e instanceof ApiError)throw new ApiError(`L'entité "${this.getEntityType()}" ne prend pas en charge les actions de lien.`,400);throw e}}_getLinkFromConnectedUser(){const{linkType:e}=this._getLinkMeta();if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);return this?.userContext?.serverData?.links?.[e]?.[this.id]||null}async _submitLinkRequest(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const{connectTypeConnect:e}=this._getLinkMeta(),t=this._getLinkFromConnectedUser();if(!t){this._assertNotEntityType("connect",["poi","badges","news"]);const t=this.getEntityType(),n={childId:this.userId,childType:"citoyens",parentType:t,parentId:this.id,connectType:e},r=await this.callIsMe((()=>this.endpointApi.connect(n)));return await(this.userContext?.refresh()),r}if(t.isInviting)return this._acceptLinkRequest();if(t.toBeValidated)throw new ApiError("Vous êtes déjà en attente de validation.",400);throw new ApiError("Vous êtes déjà connecté à cette entité.",400)}async _submitLinkRequestAdmin(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const e=this._getLinkFromConnectedUser();if(!e){this._assertNotEntityType("connect",["poi","badges","news"]);const e=this.getEntityType(),t={childId:this.userId,childType:"citoyens",parentType:e,parentId:this.id,connectType:"admin"},n=await this.callIsMe((()=>this.endpointApi.connect(t)));return await(this.userContext?.refresh()),n}if(e.isInviting||e.isAdminInviting)return this._acceptLinkRequest();if(e.toBeValidated&&e.isAdminPending)throw new ApiError("Vous êtes déjà en attente de validation pour devenir admin.",400);if(e.toBeValidated)throw new ApiError("Vous êtes déjà en attente de validation pour rejoindre cette entité.",400);throw new ApiError("Vous êtes déjà connecté à cette entité.",400)}async _acceptLinkRequest(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const e=this._getLinkFromConnectedUser();if(e&&(e.isInviting||e.isAdminInviting)){this._assertNotEntityType("linkValidate",["poi","badges","news"]);const e=this.getEntityType(),t={childId:this.userId,childType:"citoyens",parentType:e,parentId:this.id,linkOption:"isInviting"},n=await this.callIsMe((()=>this.endpointApi.linkValidate(t)));return await(this.userContext?.refresh()),n}throw new ApiError("Vous n'avez pas d'invitation à valider.",400)}async _leaveLinkRequest(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const{connectTypeDisconnect:e}=this._getLinkMeta();if(!this._getLinkFromConnectedUser())throw new ApiError("Vous n'êtes pas connecté à cette entité.",404);this._assertNotEntityType("disconnect",["poi","badges","news"]);const t=this.getEntityType(),n={childId:this.userId,childType:"citoyens",parentType:t,parentId:this.id,connectType:e},r=await this.callIsMe((()=>this.endpointApi.disconnect(n)));return await(this.userContext?.refresh()),r}async get(){return this.apiClient.safeCall((async()=>{const e=await this._getPublicProfile();return this._setData(e,{forceInitialDraftReset:!0}),e}))}async updateSettings(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateSettings",["poi","badges","news"]);const t=this.getEntityType(),{type:n,value:r}=e;if("string"!=typeof n)throw new ApiValidationError("Le champ 'type' est requis (string).",400,["type requis"]);const o={type:n,value:r,idEntity:this.id,typeEntity:t};return this.callIsConnected((()=>this.endpointApi.updateSettings(o)))}async updateDescription(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateDescription",["badges","news"]);const t=this.getEntityType(),n={block:"descriptions",id:this.id,typeElement:t,...e};return this.callIsConnected((()=>this.endpointApi.updateBlockDescription(n)))}async updateInfo(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateInfo",["badges","news"]);const t=this.getEntityType(),n={block:"info",id:this.id,typeElement:t,...e};return this.callIsConnected((()=>this.endpointApi.updateBlockInfo(n)))}async updateSocial(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateSocial",["badges","news","poi","events"]);const t=this.getEntityType(),n={block:"network",id:this.id,typeElement:t,...e};return this.callIsConnected((()=>this.endpointApi.updateBlockSocial(n)))}_isPostalAddress(e){return!!e&&"object"==typeof e&&"PostalAddress"===e["@type"]&&"string"==typeof e.addressCountry&&"string"==typeof e.addressLocality&&"string"==typeof e.level1&&"string"==typeof e.level1Name&&"string"==typeof e.codeInsee&&"string"==typeof e.localityId}_isGeo(e){return!(!e||"object"!=typeof e||"number"!=typeof e.latitude&&"string"!=typeof e.latitude||"number"!=typeof e.longitude&&"string"!=typeof e.longitude)}_isGeoPosition(e){return!!e&&"object"==typeof e&&"Point"===e.type&&Array.isArray(e.coordinates)&&2===e.coordinates.length&&("number"==typeof e.coordinates[0]||"string"==typeof e.coordinates[0])&&("number"==typeof e.coordinates[1]||"string"==typeof e.coordinates[1])&&!0===e.float}async updateLocality(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(this._assertNotEntityType("updateLocality",["badges","news","comments","answers"]),!("address"in e))throw new ApiValidationError("Le champ 'address' est requis.",400,["address requis"]);const t=e.address;if(""!==t&&!this._isPostalAddress(t))throw new ApiValidationError("Format de 'address' invalide.",400,["address invalide"]);const n=t,r=this.getEntityType(),o={block:"localities",id:this.id,typeElement:r,address:n,..."geo"in e&&this._isGeo(e.geo)?{geo:e.geo}:{},..."geoPosition"in e&&this._isGeoPosition(e.geoPosition)?{geoPosition:e.geoPosition}:{},..."locality"in e?{locality:e.locality}:{}};return this.callIsConnected((()=>this.endpointApi.updateBlockLocality(o)))}async updateSlug({slug:e}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateSlug",["badges","news","poi","comments"]);const t=this.getEntityType();try{await this.endpointApi.check({block:"info",type:t,id:this.id,slug:e})}catch(e){if(e instanceof ApiResponseError)throw new ApiResponseError("Erreur lors de la vérification du slug.",e.status,e.responseData);throw e}const n={block:"info",typeElement:t,id:this.id,slug:e};return this.callIsConnected((()=>this.endpointApi.updateBlockSlug(n)))}async updateImageProfil({profil_avatar:e}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateImageProfil",["badges","news","comments","answers"]);const t=this.getEntityType();e=await this._validateImage(e);const n={pathParams:{folder:t,ownerId:this.id},profil_avatar:e};return this.callIsConnected((()=>this.endpointApi.profilImage(n)))}async updateImageBanner({banner:e,cropW:t,cropH:n,cropX:r,cropY:o}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("updateImageBanner",["badges","news","comments","answers"]);const i=this.getEntityType();e=await this._validateImage(e);const s={pathParams:{folder:i,ownerId:this.id},parentType:i,parentId:this.id,formOrigin:"banner",cropW:t,cropH:n,cropX:r,cropY:o,banner:e};return this.callIsConnected((()=>this.endpointApi.profilBanner(s)))}async organization(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer une organisation.",403);return await this.entity("organizations",e)}async project(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isConnected)throw new ApiError("Vous devez être connecté pour créer un projet.",401);return await this.entity("projects",e)}async poi(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isConnected)throw new ApiError("Vous devez être connecté pour créer un POI.",401);return await this.entity("poi",e)}async event(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isConnected)throw new ApiError("Vous devez être connecté pour créer un événement.",401);return await this.entity("events",e)}async badge(e={}){if(!("id"in e)&&!this.isConnected)throw new ApiError("Vous devez être connecté pour créer un badge.",401);return await this.entity("badges",e)}async news(e={}){if(!e?.id&&!this.isConnected)throw new ApiError("Vous devez être connecté.",401);return await this.entity("news",e)}async getOrganizations(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_ORGANIZATIONS_NO_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getOrganizations",restoredState:t?.restoredState,finalizer:async e=>{this.isMe?e.pathParams={type:this.getEntityType(),id:this.id}:(delete e?.pathParams,e.filters={[`links.members.${this.id}`]:{$exists:!0},[`links.members.${this.id}.toBeValidated`]:{$exists:!1},[`links.members.${this.id}.isInviting`]:{$exists:!1}});return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getOrganizationsAdmin(e))):()=>this.endpointApi.getOrganizationsNoAdmin(e))()}}).next()}async getProjects(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_PROJECTS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getProjects",restoredState:t?.restoredState,finalizer:async e=>{this.isMe?e.pathParams={type:this.getEntityType(),id:this.id}:(delete e?.pathParams,e.filters={$or:{[`links.contributors.${this.id}`]:{$exists:!0},[`parent.${this.id}`]:{$exists:!0}},[`links.contributors.${this.id}`]:{$exists:!0}});return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getProjectsAdmin(e))):()=>this.endpointApi.getProjectsNoAdmin(e))()}}).next()}async getEvents(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_EVENTS","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getEvents",restoredState:t?.restoredState,finalizer:async e=>(delete e?.pathParams,e.filters={$or:{[`links.attendees.${this.id}`]:{$exists:!0},[`organizer.${this.id}`]:{$exists:!0}}},this.endpointApi.getEvents(e))}).next()}async getPois(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_POIS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getPois",restoredState:t?.restoredState,finalizer:async e=>{this.isMe?e.pathParams={type:this.getEntityType(),id:this.id}:(delete e?.pathParams,e.filters={[`parent.${this.id}`]:{$exists:!0}});return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getPoisAdmin(e))):()=>this.endpointApi.getPoisNoAdmin(e))()}}).next()}async getSubscribers(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_SUBSCRIBERS","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getSubscribers",restoredState:t?.restoredState,finalizer:async e=>(delete e?.pathParams,e.filters={[`links.follows.${this.id}`]:{$exists:!0},[`links.follows.${this.id}.toBeValidated`]:{$exists:!1},[`links.follows.${this.id}.isInviting`]:{$exists:!1}},this.endpointApi.getSubscribers(e))}).next()}async getBadgesIssuer(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_BADGES","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getBadgesIssuer",restoredState:t?.restoredState,finalizer:async e=>(delete e?.pathParams,e.filters=e.filters||{"preferences.private":!1},e.filters.$or={},e.filters.$or[`issuer.${this.id}`]={$exists:!0},this.endpointApi.getBadges(e))}).next()}async getNews(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("getNews",["badges","news","poi","events","comments","answers"]);const t=this.getEntityType(),n="dateLimit"in e&&"number"==typeof e.dateLimit?{dateLimit:e.dateLimit}:{dateLimit:0},r="indexStep"in e&&"number"==typeof e.indexStep?{indexStep:e.indexStep}:{indexStep:12},o="search"in e&&"object"==typeof e.search&&null!==e.search&&"name"in e.search&&"string"==typeof e.search.name?{search:{name:e.search.name}}:{},i={pathParams:{type:t,id:this.id,isLive:!0},...n,...r,...o},s=await this.endpointApi.getNews(i);if(!Array.isArray(s))throw new ApiResponseError("Erreur lors de la récupération des actualités.",500,s);const a=this._linkEntities(s);return this._createFilteredProxy(a)}async getGallery(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);this._assertNotEntityType("getGallery",["badges","news","poi","events","comments","answers"]);const t={pathParams:{type:this.getEntityType(),id:this.id,docType:e.pathParams?.docType||"image"}};return await this.endpointApi.getGallery(t)}async searchMembers(e){const t=await this.endpointApi.searchMemberAutocomplete(e);if(!t||!Array.isArray(t))return[];this._assertNotEntityType("searchMembers",["badges","news","poi","comments"]),t.forEach((e=>{for(const t of Object.keys(e))["id","name","slug","profilThumbImageUrl","profilMarkerImageUrl","type","collection"].includes(t)||delete e[t]}));return this._linkEntities(t)}async requestToJoin(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);return this._checkLinkableEntity(),this._submitLinkRequest()}async requestToJoinAdmin(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);return this._checkLinkableEntity(),this._submitLinkRequestAdmin()}async requestPromoteToAdmin(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);if(this._checkLinkableEntity(),!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);const e=this._getLinkFromConnectedUser();if(!e)throw new ApiError("vous n'êtes pas membre de cette entité.",400);if(e?.isAdmin&&(e?.isInviting||e?.isAdminInviting))throw new ApiError("Cet utilisateur est déjà en cours d'invitation en tant qu'admin.",400);if(e?.isAdmin&&!e?.isInviting&&!e?.isAdminInviting)throw new ApiError("Cet utilisateur est déjà admin.",400);const t=this.getEntityType(),n=["organizations","projects"];if(!n.includes(t))throw new ApiError(`L'entité doit être de type : ${n.join(", ")}, reçu : ${t}`,400);const r=t,o={childId:this.userId,childType:"citoyens",parentType:r,parentId:this.id,connectType:"admin"},i=await this.callIsMe((()=>this.endpointApi.connect(o)));return await(this.userContext?.refresh()),i}async acceptInvitation(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);return this._checkLinkableEntity(),this._acceptLinkRequest()}async leave(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour envoyer une demande de participation.",401);return this._checkLinkableEntity(),this._leaveLinkRequest()}async follow(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour suivre cette entité.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("Utilisateur non connecté.",401);this._assertNotEntityType("follow",["badges","news","poi","comments"]);const e=this.getEntityType();if(!(this.userContext?.serverData?.links?.follows?.[this.id]||null)){const t={childId:this.userId,childType:"citoyens",parentType:e,parentId:this.id},n=await this.callIsMe((()=>this.endpointApi.follow(t)));return await(this.userContext?.refresh()),n}throw new ApiError("Vous êtes déjà abonné à cette entité.",409)}async unfollow(){if(!this.isMe)throw new ApiError("Vous devez être connecté pour vous désabonner.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("Utilisateur non connecté.",401);const e=this.userContext?.serverData?.links?.follows?.[this.id]||null;this._assertNotEntityType("unfollow",["badges","news","poi"]);const t=this.getEntityType();if(e){const e={childId:this.userId,childType:"citoyens",parentType:t,parentId:this.id,connectType:"followers"},n=await this.callIsMe((()=>this.endpointApi.disconnect(e)));return await(this.userContext?.refresh()),n}throw new ApiError("Vous n'êtes pas abonné à cette entité.",404)}_checkAccess(e="effectuer cette action"){if(!this.isMe)throw new ApiError(`Vous devez être connecté pour ${e}.`,401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404)}_validateUserLink(e){if(!e)return!1;const{toBeValidated:t,isInviting:n,isAdminInviting:r,isAdminPending:o}=e;return!(t||n||r||o)}_assertEntityType(...e){const t=Array.isArray(e[0])?e[0]:e;if(!t.includes(this.getEntityType()))throw new ApiError(`L'entité doit être de type : ${t.join(", ")}, reçu : ${this.getEntityType()}`,400)}_assertNotEntityType(e,...t){const n=Array.isArray(t[0])?t[0]:t,r=this.getEntityType();if(n.includes(r))throw new ApiError(`Le type d'entité "${r}" n'est pas supporté par ${e}.`,400)}_getValidatedUserLink(e,t,n){const r=n?.silent??!0;try{this._checkAccess(e),this._assertEntityType(...t)}catch(e){if(r)return null;throw e}return this._getLinkFromConnectedUser()}_isLinked(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t=this.userContext?.serverData?.links;return!!t&&!!t[e]?.[this.id]}isAuthor(e){const t=e?.silent??!0;try{if(this._checkAccess("vérifier l'auteur"),!this.serverData)throw new ApiError("Aucune donnée serveur disponible.",404);if(!this.userId)throw new ApiError("Utilisateur non connecté.",401)}catch(e){if(t)return!1;throw e}const n=this.serverData;return!!n.creator&&Boolean(this.userId&&"string"==typeof n.creator&&n.creator===this.userId)}isAdmin(e){const t=this._getValidatedUserLink("vérifier l'administrateur",["organizations","projects","events"],{silent:e?.silent});return!(!this._validateUserLink(t)||!0!==t?.isAdmin||t?.isAdminPending)||!!e?.checkHierarchy&&this._isAdminViaHierarchy()}isAuthorOrAdmin(e){return this.isAuthor()||this.isAdmin(e)}isMember(e){const t=this._getValidatedUserLink("vérifier le membre",["organizations"],{silent:e?.silent});return this._validateUserLink(t)}isContributor(e){const t=this._getValidatedUserLink("vérifier le contributeur",["projects"],{silent:e?.silent});return this._validateUserLink(t)}isAttendee(e){const t=this._getValidatedUserLink("vérifier le participant",["events"],{silent:e?.silent});return this._validateUserLink(t)}isFollower(e){const t=e?.silent??!0,n=["citoyens","organizations","projects","events","poi"];try{this._checkAccess("vérifier si il vous suit"),this._assertEntityType(...n)}catch(e){if(t)return!1;throw e}return this._isLinked("followers")}isFollowing(e){const t=e?.silent??!0,n=["citoyens","organizations","projects","events","poi"];try{this._checkAccess("vérifier si vous le suivez"),this._assertEntityType(...n)}catch(e){if(t)return!1;throw e}return this._isLinked("follows")}isToBeValidated(e){const t=this._getValidatedUserLink("vérifier si il est à valider",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.toBeValidated}isInviting(e){const t=this._getValidatedUserLink("vérifier si il est invité",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.isInviting}isInvitingAdmin(e){const t=this._getValidatedUserLink("vérifier si il est invité admin",["organizations","projects","events"],{silent:e?.silent});return!!t&&((!0===t.isAdminInviting||!0===t.isInviting)&&!0===t.isAdmin)}isAdminPending(e){const t=this._getValidatedUserLink("vérifier si il est en attente admin",["organizations","projects","events"],{silent:e?.silent});return!!t&&(!0===t.isAdmin&&!0===t.isAdminPending)}async getCostumJson(){if(!this.serverData)throw new ApiError("Aucune donnée serveur disponible.",404);const e=this.serverData;if(!e||"string"!=typeof e.slug||""===e.slug.trim())throw new ApiError("slug de l'entité non défini",400);const t={pathParams:{slug:e.slug}};return this.endpointApi.getCostumJson(t)}_generateRanges(e,t,n={}){const r={};for(const o of e){const e=n[o]||{indexMax:0};r[o]={indexMin:e.indexMax||0,indexMax:e.indexMax+t}}return r}_normalizeCount(e={}){return delete e.spam,e.total=Object.values(e).reduce(((e,t)=>e+("number"==typeof t?t:0)),0),e}_getDefaultFromEndpoint(e,t){const n=this.apiClient.getRequestSchema(e);if(n?.properties?.[t])return n.properties[t].default}_createPaginatorEngine({initialData:e,finalizer:t,methodName:n,restoredState:r}){const o=this,i=r?{...r}:{cursor:null,count:0,index:0,history:[],sizes:[]},s=e=>Boolean(e?.indexStep&&e.indexStep>0);async function a(r=!1){const c={...e};i.cursor&&(r||0!==i.history.length)||(i.count=0,i.index=0,i.history=[],i.sizes=[],c.countType=c.searchType,!c.searchBy&&s(c)?(c.ranges=o._generateRanges(c.searchType,c.indexStep),c.indexMin=c.indexMin??0,c.indexMax=c.indexMax??c.indexStep):"ALL"===c.searchBy&&s(c)&&(c.indexMin=c.indexMin??0,c.indexMax=c.indexMax??c.indexStep),i.cursor={...c});const p=i.cursor;r&&p&&(i.history.push({...p}),!p.searchBy&&s(p)?(p.ranges=o._generateRanges(p.searchType,p.indexStep,p.ranges),p.indexMin=p.indexMax??0,p.indexMax=(p.indexMax??0)+p.indexStep):"ALL"===p.searchBy&&s(p)&&(p.indexMin=p.indexMax??0,p.indexMax=(p.indexMax??0)+p.indexStep),i.cursor={...p});const d={...i.cursor||{}};if(!r){const e=d.searchType;if(!Array.isArray(e)||0===e.length)throw new Error("searchType non défini")}const m=await t(d);if(!Array.isArray(m.results))throw new Error("Les résultats doivent être un tableau");i.count+=m.results.length,i.sizes.push(m.results.length),r&&i.index++;const l=o._normalizeCount(m.count),u=o._linkEntities(m.results),h=s(d)&&i.count<l.total,y=i.history.length>0;return{count:l,results:u,pageIndex:i.index,pageNumber:i.index+1,hasNext:h,hasPrev:y,next:h?()=>a(!0):void 0,prev:y?async()=>{const e=i.history.pop(),t=i.sizes.pop()??0;return i.count-=t,i.index=Math.max(0,i.index-1),i.cursor={...e},a(!1)}:void 0,_initialData:{...e},_state:i,_entity:o,_methodName:n}}return{next:()=>a(!1)}}_withCostumContext(e){return async t=>{if(!this.serverData)throw new ApiError("Aucune donnée serveur disponible.",404);const n=this.serverData;if(!n||"string"!=typeof n.slug||""===n.slug.trim())throw new ApiError("slug de l'entité non défini",400);if(!n.id||"string"!=typeof n.id)throw new ApiError("id de l'entité non défini",400);const r=Array.isArray(t?.sourceKey)?t.sourceKey:[],o={...t||{},costumSlug:n.slug,contextId:n.id,contextType:this.getEntityType(),sourceKey:[...r,n.slug]};return e(o)}}async searchCostum(e={},t){return this._createPaginatorEngine({initialData:e,methodName:"searchCostum",restoredState:t?.restoredState,finalizer:this._withCostumContext((e=>this.endpointApi.globalAutocompleteCostum(e)))}).next()}async costumEventRequestActors(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e},n=this._withCostumContext((e=>this.endpointApi.costumEventRequestActors(e)));return await n(t)}async costumEventRequestSubevents(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestSubevents(e)))(t)}async costumEventRequestDates(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestDates(e)))(t)}async costumEventRequestElementEvent(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestElementEvent(e)))(t)}async costumEventRequestCategories(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestCategories(e)))(t)}async costumEventRequestEvent(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestEvent(e)))(t)}async costumEventRequestLinkTlToEvent(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!e.tl&&!e.event)throw new ApiError("Les paramètres 'tl' et 'event' sont requis.",400);if("string"!=typeof e.tl||"string"!=typeof e.event)throw new ApiError("Les paramètres 'tl' et 'event' doivent être des chaînes de caractères.",400);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestLinkTlToEvent(e)))(t)}async costumEventRequestLoadContextTag(e={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={pathParams:{id:this.id,type:this.getEntityType()},...e};return this._withCostumContext((e=>this.endpointApi.costumEventRequestLoadContextTag(e)))(t)}async coformAnswersSearch(e={},t){return this._createPaginatorEngine({initialData:e,methodName:"coformAnswersSearch",restoredState:t?.restoredState,finalizer:this._withCostumContext((e=>this.endpointApi.coformAnswersSearch(e)))}).next()}async coformFiltersSearch(e={}){return this._withCostumContext((e=>this.endpointApi.costumFilterCoform(e)))(e)}async searchZone(e){if(!e.countryCode?.length||!e.level?.length)throw new ApiError("countryCode et level sont requis.",400);return this._withCostumContext((e=>this.endpointApi.searchZones(e)))(e)}static restorePaginationFromJSON(e,t){const n=t instanceof BaseEntity?t:g(e._entity,t),r=e.results.map((e=>g(e,n))),o=e._methodName,i=e._initialData,s=e._state;return{results:r,count:e.count,hasNext:e.hasNext,hasPrev:e.hasPrev,pageIndex:e.pageIndex,pageNumber:e.pageNumber,next:e.hasNext?async()=>{const e=n[o];if("function"!=typeof e)throw new Error(`Méthode ${o} non trouvée sur l'entité`);const t=await e.call(n,i,{restoredState:s});return t.next?.()??t}:void 0,prev:e.hasPrev?async()=>{const e=n[o];if("function"!=typeof e)throw new Error(`Méthode ${o} non trouvée sur l'entité`);const t=await e.call(n,i,{restoredState:s});return t.prev?.()??t}:void 0,_initialData:i,_state:s,_entity:n,_methodName:o}}}class Answer extends BaseEntity{static entityType="answers";static entityTag="Answer";static SCHEMA_CONSTANTS=[];static ADD_BLOCKS=new Map([]);static UPDATE_BLOCKS=new Map([]);defaultFields={};removeFields=[];_transformServerData(e){return e.user&&"object"==typeof e.user&&"id"in e.user&&(e.user=this._linkNestedEntity({type:"citoyens",collection:"citoyens",...e.user})),e}async get(){if(!this.id)throw new ApiError("Impossible de rafraîchir sans ID.",400);const e=this.id,t=await this.endpointApi.coformAnswersById({answerId:e});if(t?.data?.id)return this._setData(t.data,{forceInitialDraftReset:!0}),this.serverData;throw new ApiError(`Aucune réponse trouvée pour l'ID ${this.id}`,404)}}class Badge extends BaseEntity{static entityType="badges";static entityTag="Badge";static SCHEMA_CONSTANTS=["ADD_BADGES"];static ADD_BLOCKS=new Map([["ADD_BADGES","addBadges"]]);static UPDATE_BLOCKS=new Map([]);defaultFields={};removeFields=[];_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Badge.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this[n](r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;for(const[n,r]of Array.from(Badge.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this[r](o),t=!0)}return t};async getOrganizations(){throw new ApiError(`getOrganizations n'existe pas dans ${this.constructor.name}`,501)}async getProjects(){throw new ApiError(`getProjects n'existe pas dans ${this.constructor.name}`,501)}async getEvents(){throw new ApiError(`getEvents n'existe pas dans ${this.constructor.name}`,501)}async getPois(){throw new ApiError(`getPois n'existe pas dans ${this.constructor.name}`,501)}async getBadgesIssuer(){throw new ApiError(`getBadgesIssuer n'existe pas dans ${this.constructor.name}`,501)}async getNews(){throw new ApiError(`getNews n'existe pas dans ${this.constructor.name}`,501)}async getSubscribers(){throw new ApiError(`getSubscribers n'existe pas dans ${this.constructor.name}`,501)}async project(){throw new ApiError(`project n'existe pas dans ${this.constructor.name}`,501)}async poi(){throw new ApiError(`poi n'existe pas dans ${this.constructor.name}`,501)}async event(){throw new ApiError(`event n'existe pas dans ${this.constructor.name}`,501)}async badge(){throw new ApiError(`badge n'existe pas dans ${this.constructor.name}`,501)}async news(){throw new ApiError(`news n'existe pas dans ${this.constructor.name}`,501)}}class Comment extends BaseEntity{static entityType="comments";static entityTag="Comment";static SCHEMA_CONSTANTS=["ADD_COMMENTS"];static ADD_BLOCKS=new Map([["ADD_COMMENTS","addComments"]]);static UPDATE_BLOCKS=new Map([["ADD_COMMENTS","updateComments"]]);defaultFields={};removeFields=["contextId","contextType","parentCommentId","argval"];_transformServerData(e){return e.author&&(e.author=this._linkNestedEntity(e.author)),Array.isArray(e.replies)&&(e.replies=e.replies.map((e=>(e&&"object"==typeof e&&!e.type&&(e.type="comments",e.collection="comments"),this._linkNestedEntity(e))))),e}async get(){throw new ApiError(`get n'existe pas dans ${this.constructor.name}`,501)}async save(){const e=this.refresh;this.refresh=async()=>this._serverData;try{return await super.save()}finally{this.refresh=e}}_add=async e=>{if(!this._calledFromSave)throw new Error("utilisation invalide de _add, utilisez save");if(!this.parent?.id)throw new Error("Le parent doit être défini pour ajouter un commentaire.");if(""===e.text&&(e.text=" "),"comments"===this.parent.getEntityType()){e.parentCommentId=this.parent.id;let t=this.parent.parent;for(;t&&t.getEntityType&&"comments"===t.getEntityType();)t=t.parent;if(!t)throw new Error("Impossible de trouver l'entité racine pour le commentaire.");e.contextId=t.id,e.contextType=t.getEntityType()}else e.parentCommentId=e.parentCommentId||"",e.contextId=this.parent.id,e.contextType=this.parent.getEntityType();for(const[t,n]of Array.from(Comment.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}),[]);if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Comment.ADD_BLOCKS,n,r),t=e?.object?.id||e?.id?.$id||e?.id;!this.id&&t&&(this._draftData.id=t,this._setData(e.newComment,{forceInitialDraftReset:!0}))}}};_update=async e=>{if(!this._calledFromSave)throw new Error("utilisation invalide de _update, utilisez save");if(!this.parent?.id)throw new Error("Le parent doit être défini pour ajouter un commentaire.");""===e?.text&&(e.text=" "),e.params={text:e.text},delete e.text;let t=!1;const n=await this.callIsConnected((()=>this.endpointApi.updateComments(e)));return n?.comment&&this._setData(n.comment,{forceInitialDraftReset:!0}),t=!0,true};async addComments(e={}){return this.callIsConnected((()=>this.endpointApi.addComments(e)))}async updateComments(e={}){return this.callIsConnected((()=>this.endpointApi.updateComments(e)))}async delete(){if(!this.id)throw new ApiError("Vous devez fournir un id pour supprimer un commentaire.",400);const e={pathParams:{id:this.id}};await this.callIsConnected((()=>this.endpointApi.deleteComments(e))),Object.keys(this._draftData).forEach((e=>delete this._draftData[e])),Object.keys(this._serverData).forEach((e=>delete this._serverData[e])),this._isDeleted=!0}async comment(e={}){if(!this.isConnected)throw new ApiError("Vous devez être connecté.",401);return await this.entity("comments",e)}async addVote(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={collection:"comments",id:this.id,action:"vote",details:{status:e}};return await this.callIsConnected((()=>this.endpointApi.addVote(t)))}async addReportAbuse({reason:e,comment:t}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const n={collection:"comments",id:this.id,action:"reportAbuse",details:{reason:e,comment:t}};return await this.callIsConnected((()=>this.endpointApi.addReportAbuse(n)))}}class EndpointApi{apiClient;constructor(e){this.apiClient=e}get isConnected(){return this.apiClient.isConnected}get userId(){return this.apiClient.userId}async call(e,t={}){return this.apiClient.safeCall((async()=>{const n=await this.apiClient.callEndpoint(e,t);return this.apiClient.checkAndThrowApiResponseError(n),n.data}))}async callNoConnected(e,t={}){if(this.isConnected)throw new ApiAuthenticationError("Vous ne devez pas être connecté pour faire cette action.",403);return this.call(e,t)}async callIsConnected(e,t={}){if(!this.isConnected)throw new ApiAuthenticationError("Vous devez être connecté pour effectuer cette action.",401);return this.call(e,t)}async personRegister(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callNoConnected("PERSON_REGISTER",e)}async authenticateUrl(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callNoConnected("AUTHENTICATE_URL",e)}async refreshTokenUrl(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("REFRESH_TOKEN_URL",e)}async meInfoUrl(){return this.callIsConnected("ME_INFO_URL")}async passwordRecovery(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callNoConnected("PASSWORD_RECOVERY",e)}async serverExchangeToken(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("SERVER_EXCHANGE_TOKEN",e)}async changePassword(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("CHANGE_PASSWORD",e)}async deleteAccount(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_ACCOUNT",e)}async updateSettings(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_SETTINGS",e)}async updateBlockDescription(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_DESCRIPTION",e)}async updateBlockInfo(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_INFO",e)}async updateBlockSocial(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_SOCIAL",e)}async updateBlockLocality(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_LOCALITY",e)}async updateBlockSlug(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_BLOCK_SLUG",e)}async check(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("CHECK",e)}async profilImage(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("PROFIL_IMAGE",e)}async profilBanner(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("PROFIL_BANNER",e)}async getElementsAbout(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_ELEMENTS_ABOUT",e)}async multiconnect(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("MULTICONNECT",e)}async getNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_NEWS",e)}async getNewsById(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_NEWS_BY_ID",e)}async addNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_NEWS",e)}async addImageNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_IMAGE_NEWS",e)}async addFileNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_FILE_NEWS",e)}async deleteNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_NEWS",e)}async updateNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_NEWS",e)}async shareNews(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("SHARE_NEWS",e)}async getComments(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_COMMENTS",e)}async addComments(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_COMMENTS",e)}async deleteComments(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_COMMENTS",e)}async updateComments(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_COMMENTS",e)}async searchTags(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("SEARCH_TAGS",e)}async showVote(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("SHOW_VOTE",e)}async globalAutocomplete(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GLOBAL_AUTOCOMPLETE",e)}async cityAutocomplete(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("CITY_AUTOCOMPLETE",e)}async cityAutocompleteByCountry(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("CITY_AUTOCOMPLETE_BY_COUNTRY",e)}async suggestionInput(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("SUGGESTION_INPUT",e)}async getProjectsNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_PROJECTS_NO_ADMIN",e)}async getProjectsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_PROJECTS_ADMIN",e)}async getPoisNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_POIS_NO_ADMIN",e)}async getPoisAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_POIS_ADMIN",e)}async getOrganizationsNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_ORGANIZATIONS_NO_ADMIN",e)}async getOrganizationsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_ORGANIZATIONS_ADMIN",e)}async getMembersNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_MEMBERS_NO_ADMIN",e)}async getMembersAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_MEMBERS_ADMIN",e)}async getFriendsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_FRIENDS_ADMIN",e)}async getSubscriptions(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_SUBSCRIPTIONS",e)}async getSubscriptionsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_SUBSCRIPTIONS_ADMIN",e)}async getSubscribers(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_SUBSCRIBERS",e)}async getSubscribersAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_SUBSCRIBERS_ADMIN",e)}async getContributorsNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_CONTRIBUTORS_NO_ADMIN",e)}async getContributorsAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_CONTRIBUTORS_ADMIN",e)}async getBadges(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_BADGES",e)}async getBadgesFilters(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_BADGES_FILTERS",e)}async connect(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("CONNECT",e)}async disconnect(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DISCONNECT",e)}async getElementsKey(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_ELEMENTS_KEY",e)}async getFavoris(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_FAVORIS",e)}async deleteFavoris(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_FAVORIS",e)}async addFavoris(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_FAVORIS",e)}async addOrganization(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_ORGANIZATION",e)}async addProject(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_PROJECT",e)}async addPoi(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_POI",e)}async addEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_EVENT",e)}async deletePoi(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_POI",e)}async deleteEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_EVENT",e)}async deleteElement(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_ELEMENT",e)}async addImageElement(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_IMAGE_ELEMENT",e)}async linkValidate(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("LINK_VALIDATE",e)}async searchMemberAutocomplete(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("SEARCH_MEMBER_AUTOCOMPLETE",e)}async getNotifications(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_NOTIFICATIONS",e)}async getNotificationsCount(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_NOTIFICATIONS_COUNT",e)}async notificationUpdate(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("NOTIFICATION_UPDATE",e)}async removeAllNotifications(){return this.callIsConnected("REMOVE_ALL_NOTIFICATIONS")}async markNotificationAsRead(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("MARK_NOTIFICATION_AS_READ",e)}async activitypubSearch(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("ACTIVITYPUB_SEARCH",e)}async activitypubLink(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ACTIVITYPUB_LINK",e)}async activitypubGetCommunity(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("ACTIVITYPUB_GET_COMMUNITY",e)}async getBadge(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_BADGE",e)}async getEmetteurBadges(){return this.call("GET_EMETTEUR_BADGES")}async addBadges(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_BADGES",e)}async assignBadges(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ASSIGN_BADGES",e)}async getEvents(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_EVENTS",e)}async shareEvents(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("SHARE_EVENTS",e)}async inviteEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("INVITE_EVENT",e)}async follow(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("FOLLOW",e)}async getCostumJson(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_COSTUM_JSON",e)}async globalAutocompleteCostum(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GLOBAL_AUTOCOMPLETE_COSTUM",e)}async costumEventRequestActors(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_ACTORS",e)}async costumEventRequestSubevents(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_SUBEVENTS",e)}async costumEventRequestElementEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_ELEMENT_EVENT",e)}async costumEventRequestCategories(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_CATEGORIES",e)}async costumEventRequestDates(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_DATES",e)}async costumEventRequestEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_EVENT",e)}async costumEventRequestLinkTlToEvent(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_LINK_TL_TO_EVENT",e)}async costumEventRequestLoadContextTag(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_EVENT_REQUEST_LOAD_CONTEXT_TAG",e)}async getGallery(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_GALLERY",e)}async getAttendeesNoAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("GET_ATTENDEES_NO_ADMIN",e)}async getAttendeesAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("GET_ATTENDEES_ADMIN",e)}async coformAnswersSearch(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COFORM_ANSWERS_SEARCH",e)}async coformAnswersById(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COFORM_ANSWERS_BY_ID",e)}async addVote(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_VOTE",e)}async addReportAbuse(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("ADD_REPORT_ABUSE",e)}async updatePathValue(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("UPDATE_PATH_VALUE",e)}async deleteDocumentByContext(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DELETE_DOCUMENT_BY_CONTEXT",e)}async demoteAdmin(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.callIsConnected("DEMOTE_ADMIN",e)}async costumFilterCoform(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("COSTUM_FILTER_COFORM",e)}async searchZones(e){if(!e||"object"!=typeof e)throw new TypeError("Le paramètre data doit être un objet.");return this.call("SEARCH_ZONES",e)}}function V(e){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,{type:t?.type??"",name:t?.name}]))):{}}function G(e){return(t,n)=>n?.socialNetwork?.[e]}class Event extends BaseEntity{static entityType="events";static entityTag="Event";static SCHEMA_CONSTANTS=["ADD_EVENT","UPDATE_BLOCK_SLUG","PROFIL_IMAGE"];static ADD_BLOCKS=new Map([["ADD_EVENT","addEvent"],["PROFIL_IMAGE","updateImageProfil"]]);static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];transforms={parent:V,organizer:V};_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Event.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Event.ADD_BLOCKS,n,r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this.isAdmin({checkHierarchy:!0}))throw new ApiError("Vous n'avez pas les droits pour modifier cet événement",403);if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);let t=!1;const n=this._extractAllValidFieldsFromSchema(this.apiClient,"ADD_EVENT",{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);n&&Object.keys(n).length>0&&(await this.addEvent(n),t=!0),e.id&&delete e.id;for(const[n,r]of Array.from(Event.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(Event.UPDATE_BLOCKS,r,o),t=!0)}return t};async addEvent(e={}){return this.isMe||e.organizer||!this.parent||(e.organizer={},e.organizer[`${this.parent.id}`]={type:this.parent.getEntityType(),name:this.parent.name}),this.callIsConnected((()=>this.endpointApi.addEvent(e)))}async getOrganizations(){throw new ApiError(`getOrganizations n'existe pas dans ${this.constructor.name}`,501)}async getProjects(){throw new ApiError(`getProjects n'existe pas dans ${this.constructor.name}`,501)}async getEvents(){throw new ApiError(`getEvents - les sous-events ne sont pas encore implémentés dans ${this.constructor.name}`,501)}async getPois(){throw new ApiError(`getPois n'existe pas dans ${this.constructor.name}`,501)}async getBadgesIssuer(){throw new ApiError(`getBadgesIssuer n'existe pas dans ${this.constructor.name}`,501)}async getNews(e={}){return super.getNews(e)}async getSubscribers(e={}){return super.getSubscribers(e)}async getAttendees(e={},t={}){e.searchType=this._getDefaultFromEndpoint("GET_ATTENDEES_NO_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getAttendees",restoredState:t?.restoredState,finalizer:async e=>{const{toBeValidated:n,isAdmin:r,isInviting:o,isAdminPending:i,roles:s=[]}=t;this.isMe?(e.pathParams={id:this.id},e.filters=this._buildLinkFilters(this.id,{linkType:"events",toBeValidated:n,isAdmin:r,isAdminPending:i,isInviting:o,roles:s})):(delete e?.pathParams,e.filters=this._buildLinkFilters(this.id,{linkType:"events",toBeValidated:!1,isAdmin:r,isInviting:o,roles:s}));return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getAttendeesAdmin(e))):()=>this.endpointApi.getAttendeesNoAdmin(e))()}}).next()}async project(){throw new ApiError(`project n'existe pas dans ${this.constructor.name}`,501)}async poi(){throw new ApiError(`poi n'existe pas dans ${this.constructor.name}`,501)}async event(){throw new ApiError(`les sous-events ne sont pas encore implémentés dans ${this.constructor.name}`,501)}async badge(){throw new ApiError(`badge n'existe pas dans ${this.constructor.name}`,501)}async news(e={}){return super.news(e)}async requestToJoin(){return super.requestToJoin()}async acceptInvitation(){return super.acceptInvitation()}async leave(){return super.leave()}async follow(){return super.follow()}async unfollow(){return super.unfollow()}}class News extends BaseEntity{static entityType="news";static entityTag="News";static SCHEMA_CONSTANTS=["ADD_NEWS"];static ADD_BLOCKS=new Map([["ADD_NEWS","addNews"]]);static UPDATE_BLOCKS=new Map([["ADD_NEWS","updateNews"]]);defaultFields={};removeFields=["parentId","parentType"];transforms={scope:e=>e?.type,mentions:e=>Array.isArray(e)?e.map((e=>({...e,count:parseInt(e.count)}))):[],mediaImg:e=>{const t=e?.images?.map((e=>e.id)).filter(Boolean)||[];return t.length>0?{countImages:t.length,images:t}:{countImages:0,images:[]}},mediaFile:e=>{const t=e?.files?.map((e=>e.id)).filter(Boolean)||[];return t.length>0?{countFiles:t.length,files:t}:{countFiles:0,files:[]}}};_transformServerData(e){return e.author&&(e.author=this._linkNestedEntity(e.author)),e.target&&(e.target=this._linkNestedEntity(e.target)),e.lastAuthorShare&&(e.lastAuthorShare=this._linkNestedEntity(e.lastAuthorShare)),Array.isArray(e.sharedBy)&&(e.sharedBy=e.sharedBy.map((e=>this._linkNestedEntity(e)))),e}async get(){if(!this.id)throw new ApiError("Impossible de rafraîchir sans ID.",400);const e=this.id,t=await this.endpointApi.getNewsById({ids:[e]});if(t&&Array.isArray(t)&&1===t.length){const e=t[0];return this._setData(e,{forceInitialDraftReset:!0}),this.serverData}throw new ApiError(`Aucune actualité trouvée pour l'ID ${this.id}`,404)}_add=async e=>{if(!this._calledFromSave)throw new Error("utilisation invalide de _add, utilisez save");""===e.text&&(e.text=" "),this.parent&&(e.parentId=this.parent.id,e.parentType=this.parent.getEntityType());for(const[t,n]of Array.from(News.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}),[]);if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(News.ADD_BLOCKS,n,r);!this.id&&e?.object?.id&&(this._draftData.id=e.object.id)}}};_update=async e=>{if(!this._calledFromSave)throw new Error("utilisation invalide de _update, utilisez save");e.id&&delete e.id,""===e?.text&&(e.text=" "),this.parent&&(e.parentId=this.parent.id,e.parentType=this.parent.getEntityType()),e.idNews=this.id;let t=!1;return await this.callIsConnected((()=>this.endpointApi.updateNews(e))),t=!0,true};async addNews(e={}){return this.callIsConnected((()=>this.endpointApi.addNews(e)))}async updateNews(e={}){return this.callIsConnected((()=>this.endpointApi.updateNews(e)))}async addMention({slug:e,id:t}){try{if(!e&&!t)throw new ApiError("Vous devez fournir un slug ou un id pour ajouter une mention.",400);const n=await this.entity("citoyens",{id:t,slug:e}),r=n.serverData;if(this._draftData.mentions||(this._draftData.mentions=[]),this._draftData.mentions.find((e=>e.id===r.id)))return this._draftData.mentions=this._draftData.mentions.map((e=>(e.id===r.id&&(e.count+=1),e))),this._draftData.mentions;const o={id:r.id,slug:r.slug,type:n.getEntityType(),name:r.name,value:r.name,count:1};return this._draftData.mentions.push(o),this._draftData.mentions}catch(e){throw this.apiClient._logger.error("Erreur lors de l'ajout de la mention :",e),e}}async addImage(e){const t=await this._validateImage(e),n={pathParams:{folder:this.parent?.getEntityType(),ownerId:this.parent?.id},newsImage:t},r=await this.callIsConnected((()=>this.endpointApi.addImageNews(n)));return this._draftData.mediaImg?(this._draftData.mediaImg.countImages=this._draftData.mediaImg.countImages+1,this._draftData.mediaImg.images.push(r.id)):this._draftData.mediaImg={countImages:1,images:[r.id]},r}async addFile(e){const t=await this._validateFile(e),n={pathParams:{folder:this.parent?.getEntityType(),ownerId:this.parent?.id},newsFile:t},r=await this.callIsConnected((()=>this.endpointApi.addFileNews(n)));return this._draftData.mediaFile?(this._draftData.mediaFile.countFiles=this._draftData.mediaFile.countFiles+1,this._draftData.mediaFile.files.push(r.id)):this._draftData.mediaFile={countFiles:1,files:[r.id]},r}async delete(){if(!this.id)throw new ApiError("Vous devez fournir un id pour supprimer une news.",400);const e={pathParams:{id:this.id},isLive:!1};await this.callIsConnected((()=>this.endpointApi.deleteNews(e))),Object.keys(this._draftData).forEach((e=>delete this._draftData[e])),Object.keys(this._serverData).forEach((e=>delete this._serverData[e])),this._isDeleted=!0}async comment(e={}){if(!this.isConnected)throw new ApiError("Vous devez être connecté.",401);return await this.entity("comments",e)}async getComments(){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const e={pathParams:{type:"news",id:this.id}},t=await this.endpointApi.getComments(e);if(!Array.isArray(t))throw new ApiResponseError("Erreur lors de la récupération des commentaires.",500,t);const n=this._linkEntities(t);return this._createFilteredProxy(n)}async addVote(e){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const t={collection:"news",id:this.id,action:"vote",details:{status:e}};return await this.callIsConnected((()=>this.endpointApi.addVote(t)))}async addReportAbuse({reason:e,comment:t}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const n={collection:"news",id:this.id,action:"reportAbuse",details:{reason:e,comment:t}};return await this.callIsConnected((()=>this.endpointApi.addReportAbuse(n)))}async shareNews({childId:e,childType:t,comment:n}={}){if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.userId)throw new ApiError("L'utilisateur connecté n'est pas défini.",400);if(!this.parent?.id)throw new ApiError("Le parent doit être défini pour partager une news",400);const r=e??this.userId,o=t??"citoyens",i=["citoyens","projects","organizations"];if(!i.includes(o))throw new ApiError(`Le type de cible "${o}" n'est pas valide. Types autorisés: ${i.join(", ")}`,400);if(this.parent.id===this.userId&&r===this.userId)throw new ApiError("Vous ne pouvez pas partager votre propre news à vous-même",400);const s={parentId:this.id,parentType:"news",connectType:"share",childType:o,childId:r,comment:n};return await this.callIsConnected((()=>this.endpointApi.shareNews(s)))}isAuthor(e){const t=e?.silent??!0;try{if(!this.isMe)throw new ApiError("Vous devez être connecté pour vérifier l'auteur.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.serverData)throw new ApiError("Aucune donnée serveur disponible.",404);if(!this.userId)throw new ApiError("Utilisateur non connecté.",401)}catch(e){if(t)return!1;throw e}const n=this.serverData.author;if(!n)return!1;let r;return"serverData"in n&&n.serverData&&"object"==typeof n.serverData&&"id"in n.serverData?r=n.serverData.id:"id"in n&&(r=n.id),Boolean(r&&this.userId===r)}}class Organization extends BaseEntity{static entityType="organizations";static entityTag="Organization";static SCHEMA_CONSTANTS=["ADD_ORGANIZATION","UPDATE_BLOCK_DESCRIPTION","UPDATE_BLOCK_INFO","UPDATE_BLOCK_SOCIAL","UPDATE_BLOCK_LOCALITY","UPDATE_BLOCK_SLUG","PROFIL_IMAGE","VIRTUAL_OPENING_HOURS"];static VIRTUAL_SCHEMAS={VIRTUAL_OPENING_HOURS:{type:"object",properties:{openingHours:{type:"array",description:"Horaires d'ouverture (7 jours de la semaine)",minItems:7,maxItems:7,items:{oneOf:[{type:"string",const:""},{type:"object",properties:{dayOfWeek:{type:"string",enum:["Mo","Tu","We","Th","Fr","Sa","Su"],description:"Jour de la semaine"},hours:{type:"array",description:"Liste des créneaux horaires",items:{type:"object",properties:{opens:{type:"string",pattern:"^([01]\\d|2[0-3]):[0-5]\\d$",description:"Heure d'ouverture (HH:MM)"},closes:{type:"string",pattern:"^([01]\\d|2[0-3]):[0-5]\\d$",description:"Heure de fermeture (HH:MM)"}},required:["opens","closes"],additionalProperties:!1}}},required:["dayOfWeek","hours"],additionalProperties:!1}]}}}}};static CUSTOM_FIELD_HANDLERS=new Map([["openingHours",{updateMethod:"updateOpeningHours",schemaConstant:"VIRTUAL_OPENING_HOURS"}]]);static ADD_BLOCKS=new Map([["ADD_ORGANIZATION","addOrganization"],["PROFIL_IMAGE","updateImageProfil"]]);static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_DESCRIPTION","updateDescription"],["UPDATE_BLOCK_SOCIAL","updateSocial"],["UPDATE_BLOCK_LOCALITY","updateLocality"],["UPDATE_BLOCK_INFO","updateInfo"],["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];transforms={github:G("github"),gitlab:G("gitlab"),facebook:G("facebook"),twitter:G("twitter"),instagram:G("instagram"),diaspora:G("diaspora"),mastodon:G("mastodon"),telegram:G("telegram"),signal:G("signal")};_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Organization.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Organization.ADD_BLOCKS,n,r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour modifier cette organisation",403);if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;const n=Organization.CUSTOM_FIELD_HANDLERS;if(n){const r=new Set;for(const[o,i]of n)o in e&&this._hasFieldChanged(o)&&(await this._invokeCustomFieldHandler(i.updateMethod,e[o],o),r.add(o),t=!0);r.forEach((t=>delete e[t]))}for(const[n,r]of Array.from(Organization.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(Organization.UPDATE_BLOCKS,r,o),t=!0)}return t};async addOrganization(e){return this.callIsConnected((()=>this.endpointApi.addOrganization(e)))}async getOrganizations(){throw new ApiError("getOrganizations n'existe pas dans Organization",404)}async getProjects(e={}){return super.getProjects(e)}async getEvents(e={}){return super.getEvents(e)}async getPois(e={}){return super.getPois(e)}async getBadgesIssuer(e={}){return super.getBadgesIssuer(e)}async getNews(e={}){return super.getNews(e)}async getSubscribers(e={}){return super.getSubscribers(e)}async getMembers(e={},t={}){if(!this.id)throw new ApiError("L'organisation n'est pas définie, impossible de récupérer les membres",400);const n=this.id;e.searchType=this._getDefaultFromEndpoint("GET_MEMBERS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getMembers",restoredState:t?.restoredState,finalizer:async e=>{const{toBeValidated:r,isAdmin:o,isAdminPending:i,isInviting:s,roles:a=[]}=t;this.isMe?(e.pathParams={id:this.id},e.filters=this._buildLinkFilters(n,{linkType:"memberOf",toBeValidated:r,isAdmin:o,isAdminPending:i,isInviting:s,roles:a})):(delete e?.pathParams,e.filters=this._buildLinkFilters(n,{linkType:"memberOf",toBeValidated:!1,isAdmin:o,isInviting:s,roles:a}));return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getMembersAdmin(e))):()=>this.endpointApi.getMembersNoAdmin(e))()}}).next()}async getGallery(e={}){return super.getGallery(e)}async project(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un projet dans cette organisation",403);return super.project(e)}async poi(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un poi dans cette organisation",403);return super.poi(e)}async event(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un event dans cette organisation",403);return super.event(e)}async badge(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un badge dans cette organisation",403);return super.badge(e)}async news(e={}){return super.news(e)}async updateOpeningHours(e){if(!this.id)throw new ApiError("L'organisation n'a pas d'ID, impossible de mettre à jour les horaires d'ouverture.",400);return this.endpointApi.updatePathValue({id:this.id,collection:"organizations",path:"openingHours",value:e})}async requestToJoin(){return super.requestToJoin()}async requestToJoinAdmin(){return super.requestToJoinAdmin()}async acceptInvitation(){return super.acceptInvitation()}requestPromoteToAdmin(){return super.requestPromoteToAdmin()}async leave(){return super.leave()}async follow(){return super.follow()}async unfollow(){return super.unfollow()}async getCostumJson(){return super.getCostumJson()}async searchCostum(e){return super.searchCostum(e)}async coformAnswersSearch(e){return super.coformAnswersSearch(e)}}class Poi extends BaseEntity{static entityType="poi";static entityTag="Poi";static SCHEMA_CONSTANTS=["ADD_POI","UPDATE_BLOCK_DESCRIPTION","UPDATE_BLOCK_INFO","UPDATE_BLOCK_LOCALITY","UPDATE_BLOCK_SLUG","PROFIL_IMAGE"];static ADD_BLOCKS=new Map([["ADD_POI","addPoi"],["PROFIL_IMAGE","updateImageProfil"]]);static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_DESCRIPTION","updateDescription"],["UPDATE_BLOCK_LOCALITY","updateLocality"],["UPDATE_BLOCK_INFO","updateInfo"],["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Poi.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Poi.ADD_BLOCKS,n,r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this.isAuthor())throw new ApiError("Vous n'avez pas les droits pour modifier ce POI",403);if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;for(const[n,r]of Array.from(Poi.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(Poi.UPDATE_BLOCKS,r,o),t=!0)}return t};async addPoi(e={}){return!this.isMe&&this.parent&&(e.parent={},e.parent[`${this.parent.id}`]={type:this.parent.getEntityType(),name:this.parent.name}),this.callIsConnected((()=>this.endpointApi.addPoi(e)))}async getOrganizations(){throw new ApiError(`getOrganizations n'existe pas dans ${this.constructor.name}`,501)}async getProjects(){throw new ApiError(`getProjects n'existe pas dans ${this.constructor.name}`,501)}async getEvents(){throw new ApiError(`getEvents n'existe pas dans ${this.constructor.name}`,501)}async getPois(){throw new ApiError(`getPois n'existe pas dans ${this.constructor.name}`,501)}async getBadgesIssuer(){throw new ApiError(`getBadgesIssuer n'existe pas dans ${this.constructor.name}`,501)}async getNews(){throw new ApiError(`getNews n'existe pas dans ${this.constructor.name}`,501)}async getSubscribers(e={}){return super.getSubscribers(e)}async project(){throw new ApiError(`project n'existe pas dans ${this.constructor.name}`,501)}async poi(){throw new ApiError(`poi n'existe pas dans ${this.constructor.name}`,501)}async event(){throw new ApiError(`event n'existe pas dans ${this.constructor.name}`,501)}async badge(){throw new ApiError(`badge n'existe pas dans ${this.constructor.name}`,501)}async news(){throw new ApiError(`news n'existe pas dans ${this.constructor.name}`,501)}async follow(){return super.follow()}async unfollow(){return super.unfollow()}}class Project extends BaseEntity{static entityType="projects";static entityTag="Project";static SCHEMA_CONSTANTS=["ADD_PROJECT","UPDATE_BLOCK_DESCRIPTION","UPDATE_BLOCK_INFO","UPDATE_BLOCK_SOCIAL","UPDATE_BLOCK_LOCALITY","UPDATE_BLOCK_SLUG","PROFIL_IMAGE"];static ADD_BLOCKS=new Map([["ADD_PROJECT","addProject"],["PROFIL_IMAGE","updateImageProfil"]]);static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_DESCRIPTION","updateDescription"],["UPDATE_BLOCK_SOCIAL","updateSocial"],["UPDATE_BLOCK_LOCALITY","updateLocality"],["UPDATE_BLOCK_INFO","updateInfo"],["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];transforms={github:G("github"),gitlab:G("gitlab"),facebook:G("facebook"),twitter:G("twitter"),instagram:G("instagram"),diaspora:G("diaspora"),mastodon:G("mastodon"),telegram:G("telegram"),signal:G("signal"),parent:V};_add=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _add, utilisez save",400);e.id=this._newId?.(),e.slug&&delete e.slug;for(const[t,n]of Array.from(Project.ADD_BLOCKS)){const r=this._extractChangedFieldsFromSchema(this.apiClient,t,{...e,...this.defaultFields},(()=>{}));if(r&&Object.keys(r).length>0){const e=await this._invokeBlockMethod(Project.ADD_BLOCKS,n,r);!this.id&&e?.map?.id&&(this._draftData.id=e.map.id,this._draftData.slug=e.map.slug)}}};_update=async e=>{if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour modifier ce projet",403);if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;for(const[n,r]of Array.from(Project.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(Project.UPDATE_BLOCKS,r,o),t=!0)}return t};async addProject(e={}){return!this.isMe&&this.parent&&(e.parent={},e.parent[`${this.parent.id}`]={type:this.parent.getEntityType(),name:this.parent.name}),this.callIsConnected((()=>this.endpointApi.addProject(e)))}async getOrganizations(){throw new ApiError(`getOrganizations n'existe pas dans ${this.constructor.name}`,501)}async getProjects(e={}){return super.getProjects(e)}async getEvents(e={}){return super.getEvents(e)}async getPois(e={}){return super.getPois(e)}async getBadgesIssuer(e={}){return super.getBadgesIssuer(e)}async getNews(e={}){return super.getNews(e)}async getSubscribers(e={}){return super.getSubscribers(e)}async getContributors(e={},t={}){e.searchType=this._getDefaultFromEndpoint("GET_CONTRIBUTORS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getContributors",restoredState:t?.restoredState,finalizer:async e=>{const{toBeValidated:n,isAdmin:r,isInviting:o,isAdminPending:i,roles:s=[]}=t;this.isMe?(e.pathParams={id:this.id},e.filters=this._buildLinkFilters(this.id,{linkType:"projects",toBeValidated:n,isAdmin:r,isAdminPending:i,isInviting:o,roles:s})):(delete e?.pathParams,e.filters=this._buildLinkFilters(this.id,{linkType:"projects",toBeValidated:!1,isAdmin:r,isInviting:o,roles:s}));return(this.isMe?()=>this.callIsMe((()=>this.endpointApi.getContributorsAdmin(e))):()=>this.endpointApi.getContributorsNoAdmin(e))()}}).next()}async getGallery(e={}){return super.getGallery(e)}async project(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un projet dans ce projet",403);return super.project(e)}async poi(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un POI dans ce projet",403);return super.poi(e)}async event(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un événement dans ce projet",403);return super.event(e)}async badge(e={}){if(!this.isAdmin())throw new ApiError("Vous n'avez pas les droits pour créer un badge dans ce projet",403);return super.badge(e)}async news(e={}){return super.news(e)}async requestToJoin(){return super.requestToJoin()}async requestToJoinAdmin(){return super.requestToJoinAdmin()}async acceptInvitation(){return super.acceptInvitation()}requestPromoteToAdmin(){return super.requestPromoteToAdmin()}async leave(){return super.leave()}async follow(){return super.follow()}async unfollow(){return super.unfollow()}}class User extends BaseEntity{static entityType="citoyens";static entityTag="User";static SCHEMA_CONSTANTS=["UPDATE_BLOCK_DESCRIPTION","UPDATE_BLOCK_INFO","UPDATE_BLOCK_SOCIAL","UPDATE_BLOCK_LOCALITY","UPDATE_BLOCK_SLUG","PROFIL_IMAGE"];static UPDATE_BLOCKS=new Map([["UPDATE_BLOCK_DESCRIPTION","updateDescription"],["UPDATE_BLOCK_SOCIAL","updateSocial"],["UPDATE_BLOCK_LOCALITY","updateLocality"],["UPDATE_BLOCK_INFO","updateInfo"],["UPDATE_BLOCK_SLUG","updateSlug"],["PROFIL_IMAGE","updateImageProfil"]]);defaultFields={typeElement:this.getEntityType()};removeFields=["typeElement"];transforms={github:G("github"),gitlab:G("gitlab"),facebook:G("facebook"),twitter:G("twitter"),instagram:G("instagram"),diaspora:G("diaspora"),mastodon:G("mastodon"),telegram:G("telegram"),signal:G("signal")};constructor(e,t,n){if(!n.EndpointApi)throw new ApiError("EndpointApi class must be injected to avoid circular dependency.",500);if(!t?.id&&!t?.slug)throw new ApiError("Vous devez fournir un id ou un slug pour créer un User.",400);if(!n.Organization)throw new ApiError("Organization class must be injected.",500);if(!n.Project)throw new ApiError("Project class must be injected.",500);if(!n.Event)throw new ApiError("Event class must be injected.",500);if(!n.Poi)throw new ApiError("Poi class must be injected.",500);if(!n.Badge)throw new ApiError("Badge class must be injected.",500);if(!n.News)throw new ApiError("News class must be injected.",500);super(e,t,n)}get slug(){return this._draftData.slug||null}get isMe(){return this.isConnected&&this.userId===this.id}get parentIsMe(){return super.isMe}get isActingUser(){return this.parentIsMe&&!this.isMe}getEntityType(){return"citoyens"}async get(){return this.apiClient.safeCall((async()=>{if(this.isMe){const e=await this.endpointApi.meInfoUrl();return this._setData(e,{forceInitialDraftReset:!0}),e}{const e=await this._getPublicProfile();return this._setData(e,{forceInitialDraftReset:!0}),e}}))}async changePassword(e){return this.callIsMe((()=>this.endpointApi.changePassword(e)))}async delete(e){return this.callIsMe((()=>this.endpointApi.deleteAccount(e)))}async save(){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour sauvegarder.",401);return await super.save()}_add=async()=>{throw new ApiError("Vous ne pouvez pas ajouter un utilisateur par ce moyen.",403)};_update=async e=>{if(!this._calledFromSave)throw new ApiError("utilisation invalide de _update, utilisez save",400);e.id&&delete e.id;let t=!1;for(const[n,r]of Array.from(User.UPDATE_BLOCKS)){const o=this._extractChangedFieldsFromSchema(this.apiClient,n,{...e,...this.defaultFields},(()=>this.initialDraftData),this.removeFields);o&&Object.keys(o).length>0&&(await this._invokeBlockMethod(User.UPDATE_BLOCKS,r,o),t=!0)}return t};static fromServerData(e,t,n){const r=new this(t,e,n);return e&&"object"==typeof e&&Object.keys(e).length>0&&"function"==typeof r._setData&&r._setData(e),r}async updateSettings(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour les paramètres.",401);const t=await super.updateSettings(e);return await this.refresh(),t}async updateDescription(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour la description.",401);return super.updateDescription(e)}async updateInfo(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour les informations.",401);return super.updateInfo(e)}async updateSocial(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour les réseaux sociaux.",401);return super.updateSocial(e)}async updateLocality(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour la localité.",401);return super.updateLocality(e)}async updateSlug(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour le slug.",401);return super.updateSlug(e)}async updateImageProfil(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour l'image de profil.",401);return super.updateImageProfil(e)}async updateImageBanner(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour mettre à jour l'image de bannière.",401);return super.updateImageBanner(e)}async getOrganizations(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_ORGANIZATIONS_NO_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getOrganizations",restoredState:t?.restoredState,finalizer:async e=>{delete e?.pathParams;const t=this.isMe?()=>this.callIsMe((()=>this.endpointApi.getOrganizationsAdmin(e))):()=>this.endpointApi.getOrganizationsNoAdmin(e);return this.isMe||e.filters||(e.filters={[`links.members.${this.id}`]:{$exists:!0},[`links.members.${this.id}.toBeValidated`]:{$exists:!1},[`links.members.${this.id}.isInviting`]:{$exists:!1}}),t()}}).next()}async getProjects(e={}){return super.getProjects(e)}async getEvents(e={}){return super.getEvents(e)}async getPois(e={}){return super.getPois(e)}async getNews(e={}){return super.getNews(e)}async getFriends(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_FRIENDS_ADMIN","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getFriends",restoredState:t?.restoredState,finalizer:async e=>(delete e?.pathParams,!this.isMe&&this.id&&(e.pathParams={id:this.id}),this.endpointApi.getFriendsAdmin(e))}).next()}async getSubscriptions(e={},t){e.searchType=this._getDefaultFromEndpoint("GET_SUBSCRIPTIONS","searchType");return this._createPaginatorEngine({initialData:e,methodName:"getSubscriptions",restoredState:t?.restoredState,finalizer:async e=>{delete e?.pathParams;const t=this.isMe?()=>this.callIsMe((()=>this.endpointApi.getSubscriptionsAdmin(e))):()=>this.endpointApi.getSubscriptions(e);return this.isMe||e.filters||(e.filters={[`links.followers.${this.id}`]:{$exists:!0}}),t()}}).next()}async getSubscribers(e={}){return super.getSubscribers(e)}async getBadgesIssuer(e={}){return super.getBadgesIssuer(e)}async getBadges(e={}){return await this.linkEntitiesFromServerData("badges",e)}async getGallery(e={}){return super.getGallery(e)}async user(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur",401);if(!e.id&&!e.slug)throw new ApiError("Vous devez fournir un id ou un slug pour créer un User.",400);const t=this.deps,n=new User(this,e,t);return await n.get(),n}async organization(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer une organisation.",401);return super.organization(e)}async project(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un projet.",401);return super.project(e)}async news(e={}){if(!("id"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer une actualité.",401);return super.news(e)}async poi(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un POI.",401);return super.poi(e)}async event(e={}){if(!("id"in e)&&!("slug"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un événement.",401);return super.event(e)}async badge(e={}){if(!("id"in e)&&!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer un badge.",401);return super.badge(e)}async sendFriendRequest(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour envoyer une demande d'amis.",401);if(this._checkLinkableEntity(),!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const{connectTypeConnect:e}=this._getLinkMeta(),t=this._getLinkFromConnectedUser();if(!t){const t={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id,connectType:e},n=await this.endpointApi.connect(t);return await(this.userContext?.refresh()),n}if(t.isInviting&&t.invitorId===this.id)return this.acceptFriendRequest();if(t.isInviting&&t.invitorId===this.userId)throw new ApiError("Vous avez déjà envoyé une demande d'amis à cet utilisateur.",403);throw new ApiError("Vous êtes déjà connecté à cette entité.",409)}async acceptFriendRequest(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour accepter une demande d'amitié.",401);if(this._checkLinkableEntity(),!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const e=this._getLinkFromConnectedUser();if(e?.isInviting&&e.invitorId===this.id){const e={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id,linkOption:"isInviting"},t=await this.endpointApi.linkValidate(e);return await(this.userContext?.refresh()),t}throw new ApiError("Vous n'avez pas d'invitation à valider.",404)}async removeFriend(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour supprimer un ami.",401);if(this._checkLinkableEntity(),!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);const{connectTypeDisconnect:e}=this._getLinkMeta();if(!this._getLinkFromConnectedUser())throw new ApiError("Vous n'êtes pas connecté à cette entité.",404);const t={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id,connectType:e},n=await this.endpointApi.disconnect(t);return await(this.userContext?.refresh()),n}async requestToJoin(){throw new ApiError("l'utilisation de requestToJoin n'est pas autorisée sur un utilisateur.",403)}async requestToJoinAdmin(){throw new ApiError("l'utilisation de requestToJoinAdmin n'est pas autorisée sur un utilisateur.",403)}async acceptInvitation(){throw new ApiError("l'utilisation de acceptInvitation n'est pas autorisée sur un utilisateur.",403)}async leave(){throw new ApiError("l'utilisation de leave n'est pas autorisée sur un utilisateur.",403)}async follow(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour suivre un utilisateur.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!(this.userContext?.serverData?.links?.follows?.[this.id]||null)){const e={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id},t=await this.endpointApi.follow(e);return await(this.userContext?.refresh()),t}throw new ApiError("Vous êtes déjà abonné à cet utilisateur.",409)}async unfollow(){if(!this.isActingUser||!this.userId)throw new ApiError("Vous devez être connecté pour vous désabonner d'un utilisateur.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(this.userContext?.serverData?.links?.follows?.[this.id]||null){const e={childId:this.userId,childType:"citoyens",parentType:this.getEntityType(),parentId:this.id,connectType:"followers"},t=await this.endpointApi.disconnect(e);return await(this.userContext?.refresh()),t}throw new ApiError("Vous n'êtes pas abonné à cet utilisateur.",404)}isFriend(e){const t=e?.silent??!0;try{if(!this.isActingUser)throw new ApiError("Vous devez être connecté pour vérifier si vous êtes ami.",401)}catch(e){if(t)return!1;throw e}this._assertEntityType("citoyens");const n=this._getLinkFromConnectedUser();return!!n&&this._validateUserLink(n)}isFollower(e){const t=e?.silent??!0;try{if(!this.isActingUser)throw new ApiError("Vous devez être connecté pour vérifier si il vous suit.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404)}catch(e){if(t)return!1;throw e}return this._assertEntityType("citoyens"),this._isLinked("followers")}isFollowing(e){const t=e?.silent??!0;try{if(!this.isActingUser)throw new ApiError("Vous devez être connecté pour vérifier si vous le suivez.",401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404)}catch(e){if(t)return!1;throw e}return this._assertEntityType("citoyens"),this._isLinked("follows")}async entityBySlug(e){if(!this.isMe)throw new ApiError("Vous devez être connecté et être l'utilisateur pour créer cet entité.",401);return super.entityBySlug(e)}_validateBasePreconditions(e,t){if(!this.userId)throw new ApiError(`Vous devez être connecté pour ${e}.`,401);if(!this.id)throw new ApiError(`${this.constructor.name} non enregistrée.`,404);if(!this.parent?.id)throw new ApiError("L'entité parente n'est pas enregistrée.",404);if(!t.includes(this.parent.getEntityType()))throw new ApiError(`L'entité doit être de type : ${t.join(", ")}, reçu : ${this.parent.getEntityType()}`,400)}_validateMemberPreconditions(e,t){if(this._validateBasePreconditions(e,t),!this.parent?.id)throw new ApiError("L'entité parente n'est pas enregistrée.",404);const n=this.parent.getEntityType();if("events"===n)return;let r=!1;switch(n){case"organizations":r=this.parent.isMember();break;case"projects":r=this.parent.isContributor();break;default:r=!1}if(!r){throw new ApiError(`Vous devez être ${{organizations:"membre",projects:"contributeur"}[n]||"membre"} pour effectuer cette action.`,401)}}_validateAdminPreconditions(e,t){if(this._validateMemberPreconditions(e,t),!this.parent?.isAdmin())throw new ApiError("Vous devez être administrateur pour effectuer cette action.",401)}_getParentLinkForUser(){const{connectTypeDisconnect:e}=this.parent._getLinkMeta(),t=this.id;return t&&this.parent?.serverData?.links?.[e]?.[t]||null}_getValidatedParentLink(e,t,n){const r=n?.silent??!0;try{this._validateBasePreconditions(e,t)}catch(e){if(r)return null;throw e}return this._getParentLinkForUser()}async _refreshWithParent(){await this.refresh(),this.parent&&await this.parent.refresh()}isAdmin(e){const t=this._getValidatedParentLink("isAdmin",["organizations","projects"],{silent:e?.silent});return this._validateUserLink(t)&&!0===t?.isAdmin}isMember(e){const t=this._getValidatedParentLink("isMember",["organizations"],{silent:e?.silent});return this._validateUserLink(t)}isContributor(e){const t=this._getValidatedParentLink("isContributor",["projects"],{silent:e?.silent});return this._validateUserLink(t)}isAttendee(e){const t=this._getValidatedParentLink("isAttendee",["events"],{silent:e?.silent});return this._validateUserLink(t)}isInviting(e){const t=this._getValidatedParentLink("isInviting",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.isInviting}isInvitingFriend(e){const t=this._getValidatedUserLink("isInvitingFriend",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.isInviting}isInvitingAdmin(e){const t=this._getValidatedParentLink("isInvitingAdmin",["organizations","projects"],{silent:e?.silent});return!!t&&((!0===t.isAdminInviting||!0===t.isInviting)&&!0===t.isAdmin)}isAdminPending(e){const t=this._getValidatedParentLink("isAdminPending",["organizations","projects"],{silent:e?.silent});return!!t&&(!0===t.isAdmin&&!0===t.isAdminPending)}isToBeValidated(e){const t=this._getValidatedParentLink("isToBeValidated",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.toBeValidated}isToBeValidatedFriend(e){const t=this._getValidatedUserLink("isToBeValidatedFriend",["citoyens","organizations","projects","events"],{silent:e?.silent});return!!t&&!0===t.toBeValidated}async sendRequestToJoinParent({admin:e}={admin:!1}){e?this._validateAdminPreconditions("sendRequestToJoinParent",["organizations","projects"]):this._validateMemberPreconditions("sendRequestToJoinParent",["organizations","projects","events"]);const{connectTypeConnect:t}=this.parent._getLinkMeta(),n=this._getParentLinkForUser();if(!n){const n=this.parent.getEntityType(),r={childId:this.id,childType:"citoyens",parentType:n,parentId:this.parent.id,connectType:e?"admin":t},o=await this.callIsConnected((()=>this.endpointApi.connect(r)));return await this._refreshWithParent(),o}if(n.isInviting||n?.isAdminInviting)throw new ApiError("Une invitation est déjà en attente d'acceptation.",400);throw new ApiError("Vous êtes déjà connecté à cette entité.",400)}async validateMemberRequest(){this._validateAdminPreconditions("validateMemberRequest",["organizations","projects"]);const e=this._getParentLinkForUser();if(!e?.toBeValidated)throw new ApiError("Cet utilisateur n'a pas de demande en attente de validation.",400);const t=this.parent.getEntityType(),n={childId:this.id,childType:"citoyens",parentType:t,parentId:this.parent.id,linkOption:"toBeValidated"},r=await this.callIsConnected((()=>this.endpointApi.linkValidate(n)));return await this._refreshWithParent(),r}async validateAdminRequest(){this._validateAdminPreconditions("validateAdminRequest",["organizations","projects"]);const e=this._getParentLinkForUser();if(!e?.isAdminPending)throw new ApiError("Cet utilisateur n'a pas de demande d'admin en attente.",400);const t=this.parent.getEntityType(),n={childId:this.id,childType:"citoyens",parentType:t,parentId:this.parent.id,linkOption:"isAdminPending"},r=await this.callIsConnected((()=>this.endpointApi.linkValidate(n)));return await this._refreshWithParent(),r}async removeFromParent(){this._validateAdminPreconditions("removeFromParent",["organizations","projects"]);if(!this._getParentLinkForUser())throw new ApiError("Cet utilisateur n'est pas connecté à cette entité.",400);const e=this.parent.getEntityType(),{connectTypeDisconnect:t}=this.parent._getLinkMeta(),n={childId:this.id,childType:"citoyens",parentType:e,parentId:this.parent.id,connectType:t},r=await this.callIsConnected((()=>this.endpointApi.disconnect(n)));return await this._refreshWithParent(),r}async promoteToAdmin(){this._validateAdminPreconditions("promoteToAdmin",["organizations","projects"]);const e=this._getParentLinkForUser();if(!e)throw new ApiError("Cet utilisateur n'est pas membre de cette entité.",400);if(e?.isAdmin&&(e?.isInviting||e?.isAdminInviting))throw new ApiError("Cet utilisateur est déjà en cours d'invitation en tant qu'admin.",400);if(e?.isAdmin&&!e?.isInviting&&!e?.isAdminInviting)throw new ApiError("Cet utilisateur est déjà admin.",400);const t=this.parent.getEntityType(),n={childId:this.id,childType:"citoyens",parentType:t,parentId:this.parent.id,connectType:"admin"},r=await this.callIsConnected((()=>this.endpointApi.connect(n)));return await this._refreshWithParent(),r}async demoteFromAdmin(){this._validateAdminPreconditions("demoteFromAdmin",["organizations","projects"]);const e=this._getParentLinkForUser();if(!e?.isAdmin||e.isAdminPending)throw new ApiError("Cet utilisateur n'est pas admin de cette entité.",400);const t=this.parent.getEntityType(),{connectTypeDisconnect:n}=this.parent._getLinkMeta(),r=t,o={childId:this.id,childType:"citoyens",parentType:r,parentId:this.parent.id,connect:n,isAdmin:!1},i=await this.callIsConnected((()=>this.endpointApi.demoteAdmin(o)));return await this._refreshWithParent(),i}}Object.assign(User.prototype,{});class ObjectID{_str;constructor(e){if(this._str=void 0,e){if(e=e.toLowerCase(),24!==(t=e).length||!/^[0-9a-f]*$/.test(t))throw new Error("Invalid hexadecimal string for creating an ObjectID");this._str=e}var t}equals(e){return e instanceof ObjectID&&this.valueOf()===e.valueOf()}toString(){return`ObjectID("${this._str}")`}clone(){return new ObjectID(this._str)}typeName(){return"oid"}getTimestamp(){return Number.parseInt(this._str?.substr(0,8)??"",16)}valueOf(){return this._str}toJSONValue(){return this.valueOf()}toHexString(){return this.valueOf()}}const K=ObjectID,Z={common1:{type:"string"},common2:{format:"email",type:"string"},common3:{type:"boolean"},common4:{format:"uri",type:"string"},common5:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$",type:"string"},common6:{additionalProperties:!1,properties:{id:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$",type:"string"}},required:["id"],type:"object"},common8:{additionalProperties:!1,properties:{reason:{default:"",type:"string"}},required:["reason"],type:"object"},common10:{default:"",type:"string"},common11:{pattern:"^[a-f0-9]{24}$",type:"string"},common12:{const:"citoyens"},common13:{properties:{value:{type:"boolean"}}},common15:{enum:["isOpenData","isOpenEdition","private","feedback"]},common16:{const:"organizations"},common17:{const:"projects"},common18:{const:"events"},common19:{default:"citoyens",enum:["citoyens","projects","organizations","events"],type:"string"},common20:{},common21:{else:{properties:{id:{pattern:"^[a-f0-9]{24}$",type:"string"}}},if:{properties:{typeElement:{const:"citoyens"}}},then:{properties:{id:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$",type:"string"}}}},common24:{properties:{typeElement:{const:"citoyens"}}},common27:{not:{type:"null"}},common29:{default:"citoyens",enum:["citoyens","projects","organizations","poi","events"],type:"string"},common30:{anyOf:[{format:"email",type:"string"},{const:"",type:"string"}]},common31:{const:"",type:"string"},common32:{anyOf:[{items:{type:"string"},type:"array"},{enum:[""],type:"string"}]},common33:{items:{type:"string"},type:"array"},common34:{enum:[""],type:"string"},common35:{anyOf:[{format:"uri",type:"string"},{const:"",type:"string"}]},common36:{properties:{name:{not:{type:"null"}}},required:["name"]},common38:{properties:{url:{not:{type:"null"}}},required:["url"]},common40:{properties:{tags:{not:{type:"null"}}},required:["tags"]},common42:{properties:{email:{not:{type:"null"}}},required:["email"]},common44:{format:"date",type:"string"},common45:{const:"info",default:"info",type:"string"},common46:{anyOf:[{type:"string"},{const:"",type:"string"}]},common47:{$ref:"#/$defs/sharedFields/name"},common48:{$ref:"#/$defs/sharedFields/tags"},common49:{default:"citoyens",enum:["citoyens"],type:"string"},common50:{$ref:"#/$defs/sharedFields/url"},common51:{properties:{avancement:{not:{type:"null"}}},required:["avancement"]},common53:{properties:{parent:{not:{type:"null"}}},required:["parent"]},common55:{$ref:"#/$defs/sharedFields/emailNullable"},common56:{additionalProperties:!1,patternProperties:{"^[a-fA-F0-9]{24}$":{additionalProperties:!1,properties:{name:{type:"string"},type:{type:"string"}},required:["type","name"],type:"object"}},type:"object"},common58:{additionalProperties:!1,properties:{name:{type:"string"},type:{type:"string"}},required:["type","name"],type:"object"},common59:{name:{type:"string"},type:{type:"string"}},common60:{properties:{type:{not:{type:"null"}}},required:["type"]},common62:{additionalProperties:!1,patternProperties:{"^(?:[a-f0-9]{24}|@userId)$":{additionalProperties:!1,properties:{name:{type:"string"},type:{type:"string"}},required:["type"],type:"object"}},type:"object"},common65:{enum:["workshop","competition","concert","contest","conference","debate","exhibition","festival","crowdfunding","fair","course","protest","market","film","getTogether","meeting","spectacle","internship","stand","others"],type:"string"},common66:{enum:["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],type:"string"},common67:{enum:["link","tool","machine","software","rh","Resource material","Financial Ressource","ficheBlanche","geoJson","compostPickup","video","sharedLibrary","recoveryCenter","trash","history","something2See","funPlace","place","artPiece","streetArts","openScene","stand","parking","other"],type:"string"},common68:{enum:["poi"],type:"string"},common69:{$ref:"#/$defs/socialField"},common70:{default:"citoyens",enum:["citoyens","projects","organizations"],type:"string"},common71:{properties:{id:{pattern:"^[a-f0-9]{24}$"}}},common74:{oneOf:[{const:"",type:"string"},{additionalProperties:!1,properties:{"@type":{const:"PostalAddress",type:"string"},addressCountry:{type:"string"},addressLocality:{type:"string"},codeInsee:{type:"string"},level1:{type:"string"},level1Name:{type:"string"},level3:{minLength:0,type:"string"},level3Name:{minLength:0,type:"string"},level4:{minLength:0,type:"string"},level4Name:{minLength:0,type:"string"},localityId:{type:"string"},postalCode:{type:"string"},streetAddress:{type:"string"}},required:["@type","addressCountry","codeInsee","addressLocality","localityId","level1","level1Name"],type:"object"}]},common75:{additionalProperties:!1,properties:{"@type":{const:"PostalAddress",type:"string"},addressCountry:{type:"string"},addressLocality:{type:"string"},codeInsee:{type:"string"},level1:{type:"string"},level1Name:{type:"string"},level3:{minLength:0,type:"string"},level3Name:{minLength:0,type:"string"},level4:{minLength:0,type:"string"},level4Name:{minLength:0,type:"string"},localityId:{type:"string"},postalCode:{type:"string"},streetAddress:{type:"string"}},required:["@type","addressCountry","codeInsee","addressLocality","localityId","level1","level1Name"],type:"object"},common79:{additionalProperties:!1,properties:{"@type":{const:"GeoCoordinates",type:"string"},latitude:{type:["string","number"]},longitude:{type:["string","number"]}},required:["latitude","longitude"],type:"object"},common83:{additionalProperties:!0,properties:{coordinates:{items:{type:"number"},maxItems:2,minItems:2,type:"array"},float:{const:!0,default:!0,type:"boolean"},type:{const:"Point",type:"string"}},required:["type","coordinates","float"],type:"object"},common86:{type:"number"},common87:{const:!0,default:!0,type:"boolean"},common89:{properties:{id:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},common92:{maxLength:100,minLength:3,pattern:"^[a-zA-Z0-9]+$",type:"string"},common93:{properties:{type:{const:"citoyens"}}},common95:{additionalProperties:!1,else:{properties:{ownerId:{pattern:"^[a-f0-9]{24}$"}}},if:{properties:{folder:{const:"citoyens"}}},properties:{folder:{default:"citoyens",enum:["citoyens","projects","organizations","events","poi"],type:"string"},ownerId:{type:"string"}},required:["folder","ownerId"],then:{properties:{ownerId:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},type:"object"},common101:{default:"citoyens",enum:["citoyens","projects","organizations","events","poi"],type:"string"},common104:{properties:{parentId:{pattern:"^[a-f0-9]{24}$"}}},common106:{properties:{parentType:{const:"citoyens"}}},common108:{properties:{parentId:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},common110:{default:!0,type:"boolean"},common111:{default:0,type:"integer"},common112:{required:["text"]},common113:{required:["mediaImg"]},common114:{required:["mediaFile"]},common115:{additionalProperties:!1,properties:{countFiles:{type:"number"},files:{items:{type:"string"},type:"array"}},required:["countFiles","files"],type:"object"},common117:{additionalProperties:!1,properties:{countImages:{type:"number"},images:{items:{type:"string"},type:"array"}},required:["countImages","images"],type:"object"},common119:{items:{properties:{count:{minimum:1,type:"integer"},id:{pattern:"^[a-f0-9]{24}$",type:"string"},name:{type:"string"},slug:{type:"string"},type:{type:"string"},value:{type:"string"}},required:["id","name","slug","type","value","count"],type:"object"},type:"array"},common123:{default:"public",enum:["public","private","restricted"],type:"string"},common124:{const:"news",default:"news",type:"string"},common125:{additionalProperties:!1,else:{properties:{ownerId:{pattern:"^[a-f0-9]{24}$"}}},if:{properties:{folder:{const:"citoyens"}}},properties:{folder:{default:"citoyens",enum:["citoyens","projects","organizations"],type:"string"},ownerId:{type:"string"}},required:["folder","ownerId"],then:{properties:{ownerId:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},type:"object"},common127:{additionalProperties:!1,properties:{id:{pattern:"^[a-f0-9]{24}$",type:"string"}},required:["id"],type:"object"},common128:{default:!1,type:"boolean"},common129:{properties:{childId:{pattern:"^[a-f0-9]{24}$"}}},common131:{properties:{childType:{const:"citoyens"}}},common133:{const:"share",default:"share",type:"string"},common134:{properties:{childId:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},common136:{default:"news",enum:["news"],type:"string"},common137:{items:{additionalProperties:!1,properties:{count:{type:"number"},id:{pattern:"^[a-f0-9]{24}$",type:"string"},name:{type:"string"},slug:{type:"string"},type:{type:"string"},value:{type:"string"}},required:["id","name","slug","type","value","count"],type:"object"},type:"array"},common140:{enum:["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects","citoyens","poi"],type:"string"},common141:{const:!1,default:!1,type:"boolean"},common142:{const:"",default:"",type:"string"},common143:{default:0,type:"number"},common144:{default:30,type:"number"},common145:{additionalProperties:!1,patternProperties:{"^[^\\s]+$":{additionalProperties:!1,properties:{id:{type:"string"},type:{enum:["cities","level1"],type:"string"}},required:["id","type"],type:"object"}},type:"object"},common150:{additionalProperties:!1,patternProperties:{"^[^\\s]+$":{additionalProperties:!1,properties:{indexMax:{type:"number"},indexMin:{type:"number"}},required:["indexMin","indexMax"],type:"object"}},type:"object"},common152:{additionalProperties:!1,properties:{indexMax:{type:"number"},indexMin:{type:"number"}},required:["indexMin","indexMax"],type:"object"},common154:{enum:["ALL"],type:"string"},common155:{default:0,minimum:0,type:"integer"},common156:{const:["projects"],default:["projects"],items:{enum:["projects"],type:"string"},type:"array"},common158:{$exists:!0},common159:{additionalProperties:!1,properties:{$exists:{const:!0}},required:["$exists"],type:"object"},common162:{additionalProperties:!1,else:{properties:{id:{pattern:"^[a-f0-9]{24}$"}}},if:{properties:{type:{const:"citoyens"}}},properties:{id:{type:"string"},type:{default:"citoyens",enum:["citoyens","projects","organizations"],type:"string"}},required:["type","id"],then:{properties:{id:{default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$"}}},type:"object"},common164:{const:["poi"],default:["poi"],items:{enum:["poi"],type:"string"},type:"array"},common165:{const:["NGO","Cooperative","LocalBusiness","Group","GovernmentOrganization"],default:["NGO","Cooperative","LocalBusiness","Group","GovernmentOrganization"],items:{enum:["NGO","Cooperative","LocalBusiness","Group","GovernmentOrganization"],type:"string"},type:"array"},common167:{$exists:!1},common168:{additionalProperties:!1,properties:{$exists:{const:!1}},required:["$exists"],type:"object"},common170:{const:!1},common171:{default:30,type:"integer"},common172:{const:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],default:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],items:{enum:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],type:"string"},type:"array"},common174:{additionalProperties:!1,properties:{$exists:{default:!1,type:"boolean"}},required:["$exists"],type:"object"},common176:{additionalProperties:!1,properties:{$in:{items:{type:"string"},minItems:1,type:"array"}},required:["$in"],type:"object"},common179:{const:["citoyens"],default:["citoyens"],items:{enum:["citoyens"],type:"string"},type:"array"},common180:{enum:["citoyens"],type:"string"},common181:{const:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects"],default:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects"],items:{enum:["citoyens","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects"],type:"string"},type:"array"},common183:{not:{propertyNames:{pattern:"^(?!links\\.followers\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}},common186:{"^links\\.followers\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":{additionalProperties:!1,properties:{$exists:{const:!0}},required:["$exists"],type:"object"},"^links\\.followers\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":{additionalProperties:!1,properties:{$exists:{const:!1}},required:["$exists"],type:"object"},"^links\\.followers\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":{additionalProperties:!1,properties:{$exists:{const:!1}},required:["$exists"],type:"object"}},common187:{not:{propertyNames:{pattern:"^(?!links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}},common190:{default:"citoyens",enum:["citoyens","organizations","projects"],type:"string"},common191:{const:["badges"],default:["badges"],items:{enum:["badges"],type:"string"},type:"array"},common193:{const:["citoyens","projects","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],default:["citoyens","projects","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],items:{enum:["citoyens","projects","NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],type:"string"},type:"array"},common195:{additionalProperties:!1,properties:{$exists:{const:!0,type:"boolean"}},required:["$exists"],type:"object"},common197:{const:!0,type:"boolean"},common198:{additionalProperties:!1,properties:{$exists:{const:!1,type:"boolean"}},required:["$exists"],type:"object"},common201:{"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteEmetteur$":{additionalProperties:!1,properties:{$exists:{const:!1,type:"boolean"}},required:["$exists"],type:"object"},"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteRecepteur$":{additionalProperties:!1,properties:{$exists:{const:!0,type:"boolean"}},required:["$exists"],type:"object"}},common202:{indexMax:30,indexMin:0},common203:{properties:{parentType:{const:"organizations"}}},common205:{properties:{parentType:{const:"projects"}}},common207:{properties:{parentType:{const:"events"}}},common209:{default:"@userId",pattern:"^([a-f0-9]{24}|@\\w+)$",type:"string"},common210:{const:"citoyens",default:"citoyens",enum:["citoyens"],type:"string"},common211:{enum:["citoyens","organizations","projects","events"],type:"string"},common212:{const:"citoyens",default:"citoyens",type:"string"},common213:{const:"@userId",default:"@userId",pattern:"^(?:[a-f0-9]{24}|@userId)$",type:"string"},common214:{default:{isOpenData:!0,isOpenEdition:!0},properties:{isOpenData:{default:!0,type:"boolean"},isOpenEdition:{default:!0,type:"boolean"}},required:["isOpenData","isOpenEdition"],type:"object"},common217:{additionalProperties:!1,default:{"@userId":{type:"citoyens"}},patternProperties:{"^(?:[a-f0-9]{24}|@userId)$":{additionalProperties:!1,properties:{name:{type:"string"},type:{type:"string"}},required:["type"],type:"object"}},type:"object"},common220:{const:"poi",default:"poi",type:"string"},common221:{const:"events",default:"events",type:"string"},common222:{format:"date-time",type:"string"},common223:{pattern:"^([01]\\d|2[0-3]):[0-5]\\d$",type:"string"},common224:{type:"integer"},common225:{additionalProperties:!1,properties:{id:{default:"@userId",pattern:"^[a-f0-9]{24}$",type:"string"},type:{const:"citoyens",default:"citoyens",type:"string"}},required:["type","id"],type:"object"},common228:{const:"badges",default:"badges",type:"string"},common229:{const:"badge",default:"badge",type:"string"},common230:{patternProperties:{"^[0-9a-f]{24}$":{additionalProperties:!1,properties:{isAdmin:{default:"",enum:["","admin"],type:"string"},name:{type:"string"},roles:{items:{type:"string"},type:"array"}},required:["name"],type:"object"}},type:"object"},common234:{default:"",enum:["","admin"],type:"string"},common235:{enum:["projects","organizations"],type:"string"},common236:{items:{enum:["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","organizations","projects","events","citoyens","poi"],type:"string"},type:"array"},common238:{default:"",oneOf:[{additionalProperties:!0,type:"object"},{const:"",type:"string"}]},common239:{additionalProperties:!0,type:"object"},common240:{additionalProperties:!0,properties:{tags:{additionalProperties:!0,properties:{verb:{type:"string"}},type:"object"}},type:"object"},common244:{additionalProperties:{enum:[1,-1],type:"integer"},type:"object"},common246:{additionalProperties:!1,properties:{id:{pattern:"^[a-f0-9]{24}$",type:"string"},type:{default:"events",type:"string"}},required:["id","type"],type:"object"},common249:{items:{properties:{id:{type:"string"}},required:["id"],type:"object"},type:"array"},common252:{additionalProperties:!1,properties:{contextId:{pattern:"^[a-f0-9]{24}$",type:"string"},contextType:{enum:["projects","organizations"],type:"string"},costumEditMode:{default:!1,type:"boolean"},costumSlug:{type:"string"},sourceKey:{items:{type:"string"},type:"array"}},type:"object"},common254:{items:{enum:["answers"],type:"string"},type:"array"},common256:{enum:["comments","news"],type:"string"},common257:{default:"citoyens",enum:["citoyens","organizations","projects","events","poi"],type:"string"},common258:{type:"array"}},J={endpoints:[{auth:"none",constant:"PERSON_REGISTER",contentType:"application/x-www-form-urlencoded",generateModule:"UserNoAuth",method:"POST",onlyAuthNone:!0,path:"/co2/person/register",request:{additionalProperties:!1,properties:{app:Z.common1,email:Z.common2,isInvitation:Z.common3,mode:Z.common1,name:Z.common1,pendingUserId:Z.common1,pwd:Z.common1,username:Z.common1},required:["name","username","email","pwd"],type:"object"}},{auth:"none",constant:"AUTHENTICATE_URL",contentType:"application/json",generateModule:"UserNoAuth",method:"POST",onlyAuthNone:!0,path:"/api/cocolight/authenticate",postActions:[{path:"accessToken",type:"setToken"},{path:"refreshToken",type:"setRefreshToken"},{event:"userLoggedIn",path:"user",type:"emitEvent"}],request:{additionalProperties:!1,properties:{email:Z.common2,password:Z.common1},required:["email","password"],type:"object"}},{auth:"none",constant:"REFRESH_TOKEN_URL",contentType:"application/json",method:"POST",path:"/api/cocolight/refreshtoken",request:{additionalProperties:!1,properties:{refreshToken:Z.common1},required:["refreshToken"],type:"object"}},{auth:"bearer",constant:"ME_INFO_URL",contentType:"application/json",method:"POST",path:"/api/cocolight/me"},{auth:"none",constant:"PASSWORD_RECOVERY",contentType:"application/x-www-form-urlencoded",generateModule:"UserNoAuth",method:"POST",onlyAuthNone:!0,path:"/co2/person/sendemail",request:{additionalProperties:!1,properties:{email:Z.common2,type:{const:"password",default:"password",type:"string"}},required:["email","type"],type:"object"}},{auth:"bearer",constant:"SERVER_EXCHANGE_TOKEN",contentType:"application/json",method:"POST",path:"/api/cocolight/exchangetoken",request:{additionalProperties:!1,properties:{serverUrl:Z.common4},required:["serverUrl"],type:"object"}},{auth:"bearer",constant:"CHANGE_PASSWORD",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/person/changepassword",request:{additionalProperties:!1,properties:{mode:{const:"changePassword",default:"changePassword",type:"string"},newPassword:Z.common1,newPassword2:Z.common1,oldPassword:Z.common1,scope:{default:"",type:["string"]},userId:Z.common5},required:["mode","userId","oldPassword","newPassword","newPassword2"],type:"object"}},{auth:"bearer",constant:"DELETE_ACCOUNT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/delete/id/{id}/type/citoyens",pathParams:Z.common6,postActions:[{type:"resetSession"},{event:"accountDeleted",path:null,type:"emitEvent"}],request:Z.common8},{auth:"bearer",constant:"UPDATE_SETTINGS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updatesettings",request:{additionalProperties:!1,allOf:[{else:{properties:{idEntity:Z.common11}},if:{properties:{typeEntity:Z.common12}},then:{properties:{idEntity:Z.common5}}},{if:{properties:{type:{enum:["birthDate","email","locality","phone","directory"]},typeEntity:Z.common12}},then:{properties:{value:{enum:["private","public","mask"],type:"string"}}}},{if:{properties:{type:{enum:["activitypub","isOpenData"]},typeEntity:Z.common12}},then:Z.common13},{if:{properties:{type:Z.common15,typeEntity:Z.common16}},then:Z.common13},{if:{properties:{type:Z.common15,typeEntity:Z.common17}},then:Z.common13},{if:{properties:{type:{enum:["isOpenData","isOpenEdition","public"]},typeEntity:Z.common18}},then:Z.common13}],properties:{idEntity:Z.common1,type:Z.common1,typeEntity:Z.common19,value:Z.common20},required:["type","value","typeEntity","idEntity"],type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_DESCRIPTION",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{additionalProperties:!1,allOf:[Z.common21,{anyOf:[{properties:{description:Z.common27},required:["description"]},{properties:{shortDescription:Z.common27},required:["shortDescription"]}]}],properties:{block:{const:"descriptions",default:"descriptions",type:"string"},descMentions:Z.common10,description:Z.common1,id:Z.common1,scope:{default:"",type:["string","null"]},shortDescription:Z.common1,typeElement:Z.common29},required:["block","typeElement","id"],type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_INFO",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{$defs:{sharedFields:{email:Z.common2,emailNullable:Z.common30,name:Z.common1,tags:Z.common32,url:Z.common35}},allOf:[{if:Z.common24,then:{additionalProperties:!1,anyOf:[Z.common36,{properties:{birthDate:Z.common27},required:["birthDate"]},{properties:{fixe:Z.common27},required:["fixe"]},{properties:{mobile:Z.common27},required:["mobile"]},Z.common38,Z.common40,Z.common42],properties:{birthDate:{anyOf:[Z.common44,Z.common31]},block:Z.common45,email:{$ref:"#/$defs/sharedFields/email"},fixe:Z.common46,id:Z.common5,mobile:Z.common46,name:Z.common47,scope:Z.common10,tags:Z.common48,typeElement:Z.common49,url:Z.common50}}},{if:{properties:{typeElement:Z.common17}},then:{additionalProperties:!1,anyOf:[Z.common36,Z.common38,Z.common40,Z.common42,Z.common51,Z.common53],properties:{avancement:{enum:["abandoned","concept","development","production","started","testing","idea","mature","qa","finished"],type:"string"},block:Z.common45,email:Z.common55,id:Z.common1,name:Z.common47,parent:Z.common56,scope:Z.common10,tags:Z.common48,typeElement:{default:"citoyens",enum:["projects"],type:"string"},url:Z.common50}}},{if:{properties:{typeElement:Z.common18}},then:{additionalProperties:!1,anyOf:[Z.common36,Z.common38,Z.common40,Z.common42,Z.common51,Z.common60,{properties:{organizer:Z.common27},required:["organizer"]},Z.common53],properties:{block:Z.common45,email:Z.common55,id:Z.common1,name:Z.common47,organizer:Z.common62,parent:Z.common56,scope:Z.common10,tags:Z.common48,type:Z.common65,typeElement:{default:"citoyens",enum:["events"],type:"string"},url:Z.common50}}},{if:{properties:{typeElement:Z.common16}},then:{additionalProperties:!1,anyOf:[Z.common36,Z.common38,Z.common40,Z.common42,Z.common60],properties:{block:Z.common45,email:Z.common55,id:Z.common1,name:Z.common47,scope:Z.common10,tags:Z.common48,type:Z.common66,typeElement:{enum:["organizations"],type:"string"},url:Z.common50}}},{if:{properties:{typeElement:{const:"poi"}}},then:{additionalProperties:!1,anyOf:[Z.common36,Z.common40,Z.common60,{properties:{urls:Z.common27},required:["urls"]}],properties:{block:Z.common45,id:Z.common1,name:Z.common47,scope:Z.common10,tags:Z.common48,type:Z.common67,typeElement:Z.common68,urls:Z.common32}}}],properties:{block:Z.common45,id:Z.common1,scope:Z.common10,typeElement:Z.common29},required:["block","typeElement","id"],type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_SOCIAL",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{$defs:{socialField:{anyOf:[Z.common34,Z.common4]}},allOf:[Z.common21,{anyOf:[{properties:{gitlab:Z.common27},required:["gitlab"]},{properties:{github:Z.common27},required:["github"]},{properties:{twitter:Z.common27},required:["twitter"]},{properties:{facebook:Z.common27},required:["facebook"]},{properties:{instagram:Z.common27},required:["instagram"]},{properties:{diaspora:Z.common27},required:["diaspora"]},{properties:{mastodon:Z.common27},required:["mastodon"]},{properties:{telegram:Z.common27},required:["telegram"]},{properties:{signal:Z.common27},required:["signal"]}]}],properties:{block:{const:"network",default:"network",type:"string"},diaspora:Z.common69,facebook:Z.common69,github:Z.common69,gitlab:Z.common69,id:Z.common1,instagram:Z.common69,mastodon:Z.common69,scope:Z.common10,signal:Z.common69,telegram:Z.common69,twitter:Z.common69,typeElement:Z.common70},required:["block","typeElement","id"],type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_LOCALITY",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{else:Z.common71,if:Z.common24,properties:{address:Z.common74,block:{const:"localities",default:"localities",type:"string"},geo:{oneOf:[Z.common31,Z.common79]},geoPosition:{oneOf:[Z.common31,Z.common83]},id:Z.common1,scope:Z.common10,typeElement:Z.common29},required:["block","typeElement","id","address"],then:Z.common89,type:"object"}},{auth:"bearer",constant:"UPDATE_BLOCK_SLUG",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updateblock/",request:{else:Z.common71,if:Z.common24,properties:{block:Z.common45,id:Z.common1,scope:Z.common10,slug:Z.common92,typeElement:Z.common29},required:["block","typeElement","id","slug"],then:Z.common89,type:"object"}},{auth:"bearer",constant:"CHECK",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/slug/check",request:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{block:Z.common45,id:Z.common1,slug:Z.common92,type:Z.common19},required:["block","type","id","slug"],then:Z.common89,type:"object"}},{auth:"bearer",constant:"PROFIL_IMAGE",contentType:"multipart/form-data",method:"POST",path:"/co2/document/upload-save/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/profil_avatar/contentKey/profil/docType/image",pathParams:Z.common95,request:{additionalProperties:!1,properties:{profil_avatar:Z.common20},required:["profil_avatar"],type:"object"}},{auth:"bearer",constant:"PROFIL_BANNER",contentType:"multipart/form-data",method:"POST",path:"/co2/document/upload-save/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/banner/docType/image/contentKey/banner",pathParams:Z.common95,request:{additionalProperties:!1,properties:{banner:Z.common20,cropH:Z.common86,cropW:Z.common86,cropX:Z.common86,cropY:Z.common86,formOrigin:{const:"banner",default:"banner"},parentId:Z.common11,parentType:Z.common101},required:["banner","parentId","parentType","formOrigin","cropW","cropH","cropX","cropY"],type:"object"}},{auth:"none",constant:"GET_ELEMENTS_ABOUT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/about/type/{type}/id/{id}/json/true",pathParams:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{id:Z.common1,type:{default:"citoyens",enum:["citoyens","projects","organizations","events","poi","badges","answers"],type:"string"}},required:["type","id"],then:Z.common89,type:"object"},request:{additionalProperties:!1,properties:{tpl:{const:"ficheInfoElement",default:"ficheInfoElement",type:"string"}},required:["tpl"],type:"object"}},{auth:"bearer",constant:"MULTICONNECT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/multiconnect",request:{additionalProperties:!1,else:Z.common104,if:Z.common106,properties:{listInvite:{additionalProperties:!1,patternProperties:{"^(citoyens|projects|organizations)$":{additionalProperties:!1,patternProperties:{"^[0-9a-fA-F]{24}$":{additionalProperties:!1,properties:{name:Z.common1},required:["name"],type:"object"}},type:"object"}},type:"object"},parentId:Z.common1,parentType:Z.common70},required:["parentId","parentType","listInvite"],then:Z.common108,type:"object"}},{auth:"none",constant:"GET_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/get/type/{type}/id/{id}/isLive/{isLive}/json/true",pathParams:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{id:Z.common1,isLive:Z.common110,type:Z.common70},required:["isLive","type","id"],then:Z.common89,type:"object"},request:{additionalProperties:!1,properties:{dateLimit:Z.common111,indexStep:{default:12,type:"integer"},search:{additionalProperties:!1,properties:{name:Z.common10},required:["name"],type:"object"}},required:["dateLimit","indexStep"],type:"object"}},{auth:"none",constant:"GET_NEWS_BY_ID",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/getbyids",request:{additionalProperties:!1,properties:{ids:{items:Z.common11,type:"array"}},required:["ids"],type:"object"}},{auth:"bearer",constant:"ADD_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/save",request:{additionalProperties:!1,anyOf:[Z.common112,Z.common113,Z.common114],else:Z.common104,if:Z.common106,properties:{json:Z.common87,markdownActive:Z.common110,mediaFile:Z.common115,mediaImg:Z.common117,mentions:Z.common119,parentId:Z.common1,parentType:Z.common70,scope:Z.common123,tags:Z.common32,text:Z.common1,type:Z.common124},required:["scope","markdownActive","parentId","parentType","type","json"],then:Z.common108,type:"object"}},{auth:"bearer",constant:"ADD_IMAGE_NEWS",contentType:"multipart/form-data",method:"POST",path:"/co2/document/uploadSave/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/newsImage/docType/image/contentKey/slider",pathParams:Z.common125,request:{additionalProperties:!1,properties:{newsImage:Z.common20},required:["newsImage"],type:"object"}},{auth:"bearer",constant:"ADD_FILE_NEWS",contentType:"multipart/form-data",method:"POST",path:"/co2/document/uploadSave/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/newsFile/docType/file",pathParams:Z.common125,request:{additionalProperties:!1,properties:{newsFile:Z.common20},required:["newsFile"],type:"object"}},{auth:"bearer",constant:"DELETE_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/delete/id/{id}",pathParams:Z.common127,request:{additionalProperties:!1,properties:{isLive:Z.common128},required:["isLive"],type:"object"}},{auth:"bearer",constant:"UPDATE_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/update",request:{additionalProperties:!1,anyOf:[Z.common112,Z.common113,Z.common114],else:Z.common104,if:Z.common106,properties:{idNews:Z.common11,markdownActive:Z.common110,mediaFile:Z.common115,mediaImg:Z.common117,mentions:Z.common119,parentId:Z.common1,parentType:Z.common70,scope:Z.common123,tags:Z.common32,text:Z.common1,type:Z.common124},required:["idNews","scope","markdownActive","parentId","parentType","type"],then:Z.common108,type:"object"}},{auth:"bearer",constant:"SHARE_NEWS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/share",request:{additionalProperties:!1,else:Z.common129,if:Z.common131,properties:{childId:Z.common11,childType:Z.common70,comment:Z.common1,connectType:Z.common133,parentId:Z.common11,parentType:Z.common124},required:["parentId","parentType","childId","childType","connectType"],then:Z.common134,type:"object"}},{auth:"none",constant:"GET_COMMENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/comment/index/type/{type}/id/{id}/json/true",pathParams:{additionalProperties:!1,properties:{id:Z.common11,type:Z.common136},required:["type","id"],type:"object"}},{auth:"bearer",constant:"ADD_COMMENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/comment/save",request:{additionalProperties:!1,properties:{argval:Z.common10,contextId:Z.common11,contextType:Z.common136,mentions:Z.common137,parentCommentId:{default:"",pattern:"^([a-f0-9]{24}|)$",type:"string"},path:Z.common10,text:Z.common1},required:["text","contextId","contextType"],type:"object"}},{auth:"bearer",constant:"DELETE_COMMENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/comment/delete/id/{id}",pathParams:Z.common127},{auth:"bearer",constant:"UPDATE_COMMENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/comment/update",request:{additionalProperties:!1,properties:{id:Z.common11,params:{properties:{mentions:Z.common137,text:Z.common1},required:["text"],type:"object"}},required:["id","params"],type:"object"}},{auth:"none",constant:"SEARCH_TAGS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/api/tags/search?q={q}",pathParams:{additionalProperties:!1,properties:{q:Z.common1},required:["q"],type:"object"}},{auth:"none",constant:"SHOW_VOTE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/action/list/type/{type}/id/{id}/actionType/vote/json/true",pathParams:{additionalProperties:!1,properties:{id:Z.common11,type:{default:"news",enum:["news","comments"],type:"string"}},required:["type","id"],type:"object"}},{auth:"none",constant:"GLOBAL_AUTOCOMPLETE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:{default:["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative","projects","citoyens","poi"],items:Z.common140,type:"array"},fediverse:Z.common141,filters:Z.common142,indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common145,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchTags:Z.common33,searchType:{items:Z.common140,type:"array"}},required:["name","searchType","countType","indexMin","indexStep","initType","count","notSourceKey","filters","fediverse"],type:"object"}},{auth:"none",constant:"CITY_AUTOCOMPLETE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{indexMax:{minimum:5,type:"integer"},indexMin:{minimum:0,type:"integer"},locality:Z.common142,name:Z.common1,searchBy:{const:"ALL",default:"ALL",type:"string"},searchType:{const:["cities"],default:["cities"],items:{enum:["cities"],type:"string"},type:"array"}},required:["name","locality","searchType"],type:"object"}},{auth:"none",constant:"CITY_AUTOCOMPLETE_BY_COUNTRY",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/city/autocompletemultiscope",request:{additionalProperties:!1,properties:{countryCode:{default:"FR",type:"string"},formInMap:Z.common128,scopeValue:Z.common1,type:{enum:["locality"],type:"string"}},required:["type","countryCode","scopeValue","formInMap"],type:"object"}},{auth:"none",constant:"SUGGESTION_INPUT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{indexMax:{default:20,minimum:20,type:"integer"},indexMin:Z.common155,name:Z.common1,searchType:{items:{enum:["organizations","projects","poi"],type:"string"},type:"array"}},required:["name","searchType","indexMin","indexMax"],type:"object"}},{auth:"none",constant:"GET_PROJECTS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common156,fediverse:Z.common141,filters:{additionalProperties:!1,default:{$or:{"links.contributors.@userId":Z.common158,"parent.@userId":Z.common158},"links.contributors.@userId":Z.common158},patternProperties:{"^links\\.contributors\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},properties:{$or:{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:{"^links\\.contributors\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^parent\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},type:"object"}},required:["$or"],type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common156},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_PROJECTS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/{type}/id/{id}/canSee/true",pathParams:Z.common162,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common156,fediverse:Z.common141,filters:{additionalProperties:!1,default:{$or:{"links.contributors.@{pathParams.id}":Z.common158,"parent.@{pathParams.id}":Z.common158},"links.contributors.@{pathParams.id}":Z.common158},patternProperties:{"^links\\.contributors\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159},properties:{$or:{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:{"^links\\.contributors\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^parent\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159},type:"object"}},required:["$or"],type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common156},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_POIS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common164,fediverse:Z.common141,filters:{additionalProperties:!1,default:{"parent.@userId":Z.common158},patternProperties:{"^parent\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common164},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_POIS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/{type}/id/{id}/canSee/true",pathParams:Z.common162,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common164,fediverse:Z.common141,filters:{additionalProperties:!1,default:{"parent.@{pathParams.id}":Z.common158},patternProperties:{"^parent\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common164},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_ORGANIZATIONS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common165,fediverse:Z.common141,filters:{additionalProperties:!1,default:{"links.members.@userId":Z.common158,"links.members.@userId.isInviting":Z.common167,"links.members.@userId.toBeValidated":Z.common167},patternProperties:{"^links\\.members\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^links\\.members\\.(?:[a-f0-9]{24}|@\\w+)\\.isInviting$":Z.common168,"^links\\.members\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common165},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_ORGANIZATIONS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/{type}/id/{id}/canSee/true",pathParams:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{id:Z.common1,type:{default:"citoyens",enum:["citoyens","organizations"],type:"string"}},required:["type","id"],then:Z.common89,type:"object"},request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common165,fediverse:Z.common141,filters:{additionalProperties:!1,default:{"links.members.@{pathParams.id}":Z.common158,"links.members.@{pathParams.id}.isInviting":Z.common167,"links.members.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.members\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.members\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common168,"^links\\.members\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common165},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_MEMBERS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common172,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)$)"}}},{not:{propertyNames:{pattern:"^(?!links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$)"}}}],patternProperties:{"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdmin$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdminPending$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.isInviting$":Z.common174,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.roles$":Z.common176,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common172},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_MEMBERS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/organizations/id/{id}/canSee/true",pathParams:Z.common127,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common172,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}}],default:{"links.memberOf.@{pathParams.id}":Z.common158,"links.memberOf.@{pathParams.id}.isInviting":Z.common167,"links.memberOf.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdmin$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdminPending$":Z.common159,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common174,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.roles$":Z.common176,"^links\\.memberOf\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common174},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common172},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_FRIENDS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/citoyens/id/{id}/canSee/true",pathParams:Z.common6,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.friends\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}}],default:{"links.friends.@{pathParams.id}":Z.common158,"links.friends.@{pathParams.id}.isInviting":Z.common167,"links.friends.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.friends\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.friends\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common174,"^links\\.friends\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common174},type:"object"},indexMax:Z.common86,indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_SUBSCRIPTIONS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common181,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[Z.common183],default:{"links.followers.@userId":Z.common158,"links.followers.@{userId}.isInviting":Z.common167,"links.followers.@{userId}.toBeValidated":Z.common167},patternProperties:Z.common186,type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common181},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_SUBSCRIPTIONS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/citoyens/id/{id}/canSee/true",pathParams:Z.common6,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common181,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[Z.common183],default:{"links.followers.@{pathParams.id}":Z.common158,"links.followers.@{pathParams.id}.isInviting":Z.common167,"links.followers.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:Z.common186,type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common181},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_SUBSCRIBERS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[Z.common187],default:{"links.follows.@userId":Z.common158,"links.follows.@{userId}.isInviting":Z.common167,"links.follows.@{userId}.toBeValidated":Z.common167},patternProperties:{"^links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common168,"^links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_SUBSCRIBERS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/{type}/id/{id}/canSee/true",pathParams:{additionalProperties:!1,allOf:[{else:Z.common71,if:Z.common93,then:Z.common89}],properties:{id:Z.common1,type:Z.common190},required:["type","id"],type:"object"},request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[Z.common187],default:{"links.follows.@{pathParams.id}":Z.common158},maxProperties:1,minProperties:1,patternProperties:{"^links\\.follows\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159},type:"object"},indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_CONTRIBUTORS_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common172,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)$)"}}},{not:{propertyNames:{pattern:"^(?!links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$)"}}}],patternProperties:{"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdmin$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdminPending$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.isInviting$":Z.common174,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.roles$":Z.common176,"^links\\.projects\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common172},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_CONTRIBUTORS_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/projects/id/{id}/canSee/true",pathParams:Z.common127,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common172,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}}],default:{"links.projects.@{pathParams.id}":Z.common158,"links.projects.@{pathParams.id}.isInviting":Z.common167,"links.projects.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdmin$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdminPending$":Z.common159,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common174,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.roles$":Z.common176,"^links\\.projects\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common174},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common172},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_BADGES",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common191,fediverse:Z.common141,filters:{properties:{$or:{additionalProperties:!1,minProperties:1,patternProperties:{"^issuer\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},type:"object"},isParcours:Z.common3,"preferences.private":Z.common141},required:["preferences.private"],type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common191},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"GET_BADGES_FILTERS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common193,fediverse:Z.common141,fields:Z.common191,filters:{oneOf:[{additionalProperties:!1,maxProperties:1,minProperties:1,patternProperties:{"badges\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common195}},{additionalProperties:!1,maxProperties:3,minProperties:3,patternProperties:{"badges\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common195,"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteEmetteur$":Z.common198,"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteRecepteur$":Z.common198}},{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:Z.common201},{additionalProperties:!1,maxProperties:1,minProperties:1,properties:{$or:{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:Z.common201,type:"object"}},required:["$or"]},{additionalProperties:!1,maxProperties:1,minProperties:1,patternProperties:{"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.revoke$":Z.common197}},{additionalProperties:!1,maxProperties:1,minProperties:1,patternProperties:{"badges\\.(?:[a-f0-9]{24}|@\\w+)\\.attenteEmetteur$":Z.common195}}],type:"object"},indexMin:Z.common155,indexStep:Z.common171,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:{additionalProperties:!1,default:{Cooperative:Z.common202,GovernmentOrganization:Z.common202,Group:Z.common202,LocalBusiness:Z.common202,NGO:Z.common202,citoyens:Z.common202,projects:Z.common202},maxProperties:7,minProperties:7,patternProperties:{"^[a-zA-Z][a-zA-Z0-9]*$":Z.common152},type:"object"},searchType:Z.common193},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"CONNECT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/connect",request:{additionalProperties:!1,allOf:[{if:Z.common106,then:{properties:{connectType:{const:"friend",default:"friend"}}}},{if:Z.common203,then:{properties:{connectType:{enum:["admin","member"]}}}},{if:Z.common205,then:{properties:{connectType:{enum:["admin","contributor"]}}}},{if:Z.common207,then:{properties:{connectType:{default:"attendee",enum:["attendee","connect"]}}}}],properties:{childId:Z.common209,childType:Z.common210,connectType:{enum:["admin","member","contributor","attendee","friend","connect"],type:"string"},parentId:Z.common11,parentType:Z.common211},required:["childId","childType","parentType","parentId","connectType"],type:"object"}},{auth:"bearer",constant:"DISCONNECT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/disconnect",request:{additionalProperties:!1,allOf:[{if:Z.common106,then:{properties:{connectType:{default:"friends",enum:["friends","followers"]}}}},{if:Z.common203,then:{properties:{connectType:{default:"members",enum:["members","followers"]}}}},{if:Z.common205,then:{properties:{connectType:{default:"contributors",enum:["contributors","followers"]}}}},{if:Z.common207,then:{properties:{connectType:{default:"attendees",enum:["attendees","followers"]}}}}],properties:{childId:Z.common209,childType:Z.common210,connectType:{enum:["members","contributors","attendees","friends","followers"],type:"string"},parentId:Z.common11,parentType:Z.common211},required:["childId","childType","parentType","parentId","connectType"],type:"object"}},{auth:"none",constant:"GET_ELEMENTS_KEY",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/slug/getinfo/key/{slug}",pathParams:{additionalProperties:!1,properties:{slug:{pattern:"^([a-zA-Z0-9-_]+)$",type:"string"}},required:["slug"],type:"object"}},{auth:"bearer",constant:"GET_FAVORIS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/app/config/type/citoyens/id/{id}/json/true",pathParams:Z.common6},{auth:"bearer",constant:"DELETE_FAVORIS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updatepathvalue?index={index}",pathParams:{properties:{index:Z.common86},type:"object"},request:{additionalProperties:!1,properties:{collection:Z.common212,id:Z.common213,path:{const:"preferences.search.@{pathParams.index}",default:"preferences.search.@{pathParams.index}",type:"string"},pull:{const:"preferences.search",type:"string"},value:Z.common142},required:["id","collection","path","pull","value"],type:"object"}},{auth:"bearer",constant:"ADD_FAVORIS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updatepathvalue",request:{additionalProperties:!1,properties:{arrayForm:Z.common197,collection:Z.common212,id:Z.common213,path:{const:"preferences.search",default:"preferences.search",type:"string"},value:{additionalProperties:!1,properties:{description:Z.common1,locality:{patternProperties:{"^[a-f0-9]{24}$":{additionalProperties:!1,properties:Z.common59,required:["name","type"]}},type:"object"},name:Z.common1,tags:Z.common33,url:Z.common1},required:["url","name"],type:"object"}},required:["id","collection","path","arrayForm","value"],type:"object"}},{auth:"bearer",constant:"ADD_ORGANIZATION",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,properties:{address:Z.common75,collection:{const:"organizations",default:"organizations",type:"string"},email:Z.common2,geo:Z.common79,geoPosition:Z.common83,id:Z.common11,key:{const:"organization",default:"organization",type:"string"},name:{minLength:3,type:"string"},preferences:Z.common214,role:{enum:["admin","member"],type:"string"},scope:Z.common142,shortDescription:Z.common1,tags:Z.common33,type:Z.common66,url:Z.common35},required:["id","collection","key","name","type","role","scope"],type:"object"}},{auth:"bearer",constant:"ADD_PROJECT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,properties:{address:Z.common75,collection:{const:"projects",default:"projects",type:"string"},geo:Z.common79,geoPosition:Z.common83,id:Z.common11,key:{const:"project",default:"project",type:"string"},name:Z.common1,parent:Z.common217,preferences:{default:{crowdfunding:!0,isOpenData:!1,isOpenEdition:!1},properties:{crowdfunding:Z.common110,isOpenData:Z.common128,isOpenEdition:Z.common128},required:["isOpenData","isOpenEdition"],type:"object"},public:Z.common110,scope:Z.common142,shortDescription:Z.common1,tags:Z.common33,url:Z.common35},required:["id","collection","key","parent","name","public","scope"],type:"object"}},{auth:"bearer",constant:"ADD_POI",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,properties:{address:Z.common75,collection:Z.common220,description:Z.common1,geo:Z.common79,geoPosition:Z.common83,id:Z.common11,key:Z.common220,name:Z.common1,parent:Z.common217,scope:Z.common142,tags:Z.common33,type:Z.common67,urls:Z.common33},required:["id","collection","key","parent","type","name"],type:"object"}},{auth:"bearer",constant:"ADD_EVENT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,else:{required:["openingHours"]},if:{properties:{recurrency:Z.common170}},properties:{address:Z.common74,collection:Z.common221,email:Z.common30,endDate:Z.common222,geo:Z.common79,geoPosition:Z.common83,id:Z.common11,key:{const:"event",default:"event",type:"string"},name:{minLength:2,type:"string"},openingHours:{default:["","","","","","",""],items:{anyOf:[Z.common31,{additionalProperties:!1,properties:{dayOfWeek:{enum:["Mo","Tu","We","Th","Fr","Sa","Su"],type:"string"},hours:{default:[],items:{additionalProperties:!1,properties:{closes:Z.common223,opens:Z.common223},required:["opens","closes"],type:"object"},type:"array"}},required:["dayOfWeek","hours"],type:"object"}]},maxItems:7,minItems:7,type:"array"},organizer:Z.common217,parent:{oneOf:[Z.common62,Z.common31]},preferences:{default:{isOpenData:!1,isOpenEdition:!1},properties:{isOpenData:Z.common128,isOpenEdition:Z.common128},required:["isOpenData","isOpenEdition"],type:"object"},public:Z.common110,recurrency:Z.common128,scope:Z.common142,shortDescription:{format:"textarea",type:"string"},startDate:Z.common222,tags:{anyOf:[Z.common33,Z.common31]},timeZone:Z.common1,type:Z.common65,url:Z.common35},required:["id","collection","key","organizer","type","name","scope"],startBeforeEnd:!0,then:{required:["startDate","endDate"]},type:"object"}},{auth:"bearer",constant:"DELETE_POI",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/delete/type/poi/id/{id}",pathParams:Z.common127,request:Z.common8},{auth:"bearer",constant:"DELETE_EVENT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/delete/type/events/id/{id}/",pathParams:Z.common127,request:Z.common8},{auth:"bearer",constant:"DELETE_ELEMENT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/delete/type/{type}/id/{id}",pathParams:{additionalProperties:!1,properties:{id:Z.common11,type:Z.common1},required:["type","id"],type:"object"},request:Z.common8},{auth:"bearer",constant:"ADD_IMAGE_ELEMENT",contentType:"multipart/form-data",method:"POST",path:"/co2/document/upload-save/dir/communecter/folder/{folder}/ownerId/{ownerId}/input/qqfile/docType/image/contentKey/profil",pathParams:{additionalProperties:!1,properties:{folder:{enum:["badges","events"],type:"string"},ownerId:Z.common11},required:["folder","ownerId"],type:"object"},request:{additionalProperties:!1,properties:{qqfile:Z.common20,qqfilename:Z.common1,qqtotalfilesize:Z.common224,qquuid:Z.common11},required:["qquuid","qqfilename","qqtotalfilesize","qqfile"],type:"object"}},{auth:"bearer",constant:"LINK_VALIDATE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/validate",request:{additionalProperties:!1,properties:{childId:Z.common5,childType:Z.common49,linkOption:{enum:["isInviting","toBeValidated","isAdminPending"],type:"string"},parentId:Z.common11,parentType:Z.common211},required:["childId","childType","parentType","parentId"],type:"object"}},{auth:"none",constant:"SEARCH_MEMBER_AUTOCOMPLETE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/searchmemberautocomplete",request:{additionalProperties:!1,properties:{search:Z.common1,searchMode:{default:"personOnly",enum:["personOnly","organizationOnly","mixte"],type:"string"}},required:["search","searchMode"],type:"object"}},{auth:"bearer",constant:"GET_NOTIFICATIONS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/getnotifications/type/{type}/id/{id}",pathParams:Z.common225,request:{additionalProperties:!1,properties:{indexMin:Z.common111},type:"object"}},{auth:"bearer",constant:"GET_NOTIFICATIONS_COUNT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/getnotifications/type/{type}/id/{id}",pathParams:Z.common225,request:{additionalProperties:!1,properties:{refreshTimestamp:Z.common224},type:"object"}},{auth:"bearer",constant:"NOTIFICATION_UPDATE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/update",request:{additionalProperties:!1,properties:{action:{enum:["seen","read"],type:"string"},all:Z.common87},required:["action","all"],type:"object"}},{auth:"bearer",constant:"REMOVE_ALL_NOTIFICATIONS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/removeall"},{auth:"bearer",constant:"MARK_NOTIFICATION_AS_READ",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/notification/marknotificationasread",request:Z.common127},{auth:"none",constant:"ACTIVITYPUB_SEARCH",contentType:"application/x-www-form-urlencoded",method:"GET",params:[Z.common20],path:"/api/activitypub/search?address={address}",pathParams:{additionalProperties:!1,properties:{address:Z.common1},required:["address"],type:"object"}},{auth:"bearer",constant:"ACTIVITYPUB_LINK",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/api/activitypub/link",request:{additionalProperties:!1,properties:{action:{enum:["undo_follow","accept_invitation","reject_invitation","undo_accept","undo_request_follow","follow","remove_follow","accept_follower","reject_follower","remove_follower","remove_invitation"],type:"string"},actor:{additionalProperties:!1,properties:{id:Z.common1,name:Z.common1,type:{enum:["person"],type:"string"}},required:["id","type","name"],type:"object"},payload:Z.common4},required:["action","payload","actor"],type:"object"}},{auth:"none",constant:"ACTIVITYPUB_GET_COMMUNITY",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/api/activitypub/getcommunity/userId/${userId}/type/${type}/actor/person",pathParams:{additionalProperties:!1,properties:{type:{enum:["follows","followers"],type:"string"},userId:Z.common11},required:["userId","type"],type:"object"}},{auth:"none",constant:"GET_BADGE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/app/page/type/badges/id/{id}/json/true",pathParams:Z.common127},{auth:"none",constant:"GET_EMETTEUR_BADGES",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/app/badge/json/true"},{auth:"bearer",constant:"ADD_BADGES",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/save",request:{additionalProperties:!1,properties:{collection:Z.common228,criteria:{additionalProperties:!1,properties:{narrative:Z.common1},required:["narrative"],type:"object"},description:Z.common1,id:Z.common11,isParcours:Z.common128,issuer:{additionalProperties:!1,patternProperties:{"^(?:[a-f0-9]{24}|@userId)$":{additionalProperties:!1,properties:{name:Z.common1,type:{enum:["citoyens","organizations","projects"],type:"string"}},required:["type"],type:"object"}},type:"object"},key:Z.common229,name:Z.common1,parent:{additionalProperties:!1,patternProperties:{"^[a-f0-9]{24}$":{additionalProperties:!1,properties:{name:Z.common1,type:Z.common228},required:["type"],type:"object"}},type:"object"},preferences:Z.common214,public:Z.common110,scope:Z.common142,tags:Z.common33},required:["id","collection","key","name","public","scope","issuer","criteria"],type:"object"}},{auth:"bearer",constant:"ASSIGN_BADGES",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/badges/assign",request:{additionalProperties:!1,properties:{award:{patternProperties:{"^[0-9a-f]{24}$":Z.common58},type:"object"},badgeId:Z.common11,collection:Z.common228,evidences:{items:{additionalProperties:!1,properties:{narative:Z.common1,url:Z.common4},required:["narative"],type:"object"},type:"array"},key:Z.common229,narative:Z.common1,scope:Z.common142},required:["key","collection","badgeId","award"],type:"object"}},{auth:"none",constant:"GET_EVENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/agenda",request:{additionalProperties:!0,properties:{count:Z.common128,countType:{const:["events"],default:["events"],type:"array"},endDateUTC:Z.common222,fediverse:Z.common128,filters:{additionalProperties:!1,default:{$or:{"links.attendees.@userId":Z.common158,"organizer.@userId":Z.common158},"links.attendees.@userId":Z.common158},patternProperties:{"^links\\.attendees\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},properties:{$or:{additionalProperties:!1,maxProperties:2,minProperties:2,patternProperties:{"^links\\.attendees\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^organizer\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159},type:"object"}},required:["$or"],type:"object"},indexMin:Z.common111,indexStep:{default:100,type:"integer"},locality:{patternProperties:{"^[^\\s]+$":{type:"object"}},type:"object"},name:Z.common1,recurrency:Z.common110,searchType:{const:["events"],default:["events"],items:{enum:["events"],type:"string"},type:"array"},startDateUTC:Z.common222,type:Z.common65},required:["searchType","indexMin","indexStep","fediverse"],type:"object"}},{auth:"bearer",constant:"SHARE_EVENTS",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/news/co/share",request:{additionalProperties:!1,else:Z.common129,if:Z.common131,properties:{childId:Z.common11,childType:Z.common70,comment:Z.common1,connectType:Z.common133,parentId:Z.common11,parentType:Z.common221},required:["parentId","childId","childType","connectType","parentType"],then:Z.common134,type:"object"}},{auth:"bearer",constant:"INVITE_EVENT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/multiconnect",request:{additionalProperties:!1,else:Z.common104,if:Z.common106,properties:{listInvite:{additionalProperties:!1,minProperties:1,properties:{citoyens:Z.common230,invites:{patternProperties:{"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$":{additionalProperties:!1,properties:{email:Z.common2,isAdmin:Z.common234,msg:Z.common1,name:Z.common1,roles:Z.common33},required:["name","email"],type:"object"}},type:"object"},organizations:Z.common230,projects:Z.common230},type:"object"},parentId:Z.common1,parentType:Z.common70},required:["parentId","parentType","listInvite"],then:Z.common108,type:"object"}},{auth:"bearer",constant:"FOLLOW",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/follow",request:{additionalProperties:!1,properties:{childId:Z.common209,childType:Z.common210,parentId:Z.common11,parentType:Z.common211},required:["childId","childType","parentType","parentId"],type:"object"}},{auth:"none",constant:"GET_COSTUM_JSON",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/cms/getcostumjson?slug={slug}",pathParams:{slug:Z.common1}},{auth:"none",constant:"GLOBAL_AUTOCOMPLETE_COSTUM",contentType:"application/x-www-form-urlencoded",functionCocostum:"globalautocomplete",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,count:Z.common87,countType:Z.common236,fediverse:Z.common128,fields:Z.common33,filters:Z.common238,indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:{additionalProperties:!1,patternProperties:{"^[^\\s]+$":{additionalProperties:!1,properties:{id:Z.common1,type:{enum:["cities","level1","level2","level3","level4","level5"],type:"string"}},required:["id","type"],type:"object"}},type:"object"},mapUsed:Z.common197,name:Z.common1,notSourceKey:Z.common197,options:Z.common240,ranges:Z.common150,searchBy:Z.common154,searchTags:Z.common33,searchType:Z.common236,sortBy:Z.common244,sourceKey:Z.common33},required:["searchType","countType","indexMin","indexStep","initType","count","fediverse","costumSlug","costumEditMode"],type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_ACTORS",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestActors",method:"POST",path:"/costum/coevent/get_events/request/actors/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,parent_only:Z.common3,sourceKey:Z.common33,types:{items:{enum:["organizer","links.attendees","creator","links.creator","links.organizer","organizerName","animator"],type:"string"},type:"array"}},type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_SUBEVENTS",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestSubevents",method:"POST",path:"/costum/coevent/get_events/request/subevents/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,allOf:[{if:{properties:{date:Z.common1},required:["date"]},then:{required:["timezone"]}}],properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,date:{oneOf:[Z.common1,{properties:{between:{properties:{end:Z.common44,start:Z.common44},required:["start","end"],type:"object"}},required:["between"],type:"object"}]},fromToday:Z.common3,regions:Z.common249,sourceKey:Z.common33,tags:Z.common33,timezone:Z.common1,type:Z.common1},type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_ELEMENT_EVENT",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestElementEvent",method:"POST",path:"/costum/coevent/get_events/request/element_event/id/{id}/type/{type}",pathParams:Z.common246,request:Z.common252},{auth:"none",constant:"COSTUM_EVENT_REQUEST_CATEGORIES",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestCategories",method:"POST",path:"/costum/coevent/get_events/request/categories/id/{id}/type/{type}",pathParams:Z.common246,request:Z.common252},{auth:"none",constant:"COSTUM_EVENT_REQUEST_DATES",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestDates",method:"POST",path:"/costum/coevent/get_events/request/dates/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,regions:Z.common249,sourceKey:Z.common33,tags:Z.common33,type:Z.common1},type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_EVENT",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestEvent",method:"POST",path:"/costum/coevent/get_events/request/event/id/{id}/type/{type}",pathParams:Z.common246,request:Z.common252},{auth:"none",constant:"COSTUM_EVENT_REQUEST_LINK_TL_TO_EVENT",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestLinkTlToEvent",method:"POST",path:"/costum/coevent/get_events/request/link_tl_to_event/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,event:Z.common1,sourceKey:Z.common33,tl:Z.common1},required:["tl","event"],type:"object"}},{auth:"none",constant:"COSTUM_EVENT_REQUEST_LOAD_CONTEXT_TAG",contentType:"application/x-www-form-urlencoded",functionCocostum:"costumEventRequestLoadContextTag",method:"POST",path:"/costum/coevent/get_events/request/load_context_tag/id/{id}/type/{type}",pathParams:Z.common246,request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,event:Z.common11,search:Z.common1,sourceKey:Z.common33},type:"object"}},{auth:"none",constant:"GET_GALLERY",contentType:"application/x-www-form-urlencoded",functionCocostum:"",method:"POST",path:"/co2/gallery/index/type/{type}/id/{id}/docType/{docType}/tpl/json",pathParams:{additionalProperties:!1,else:Z.common71,if:Z.common93,properties:{docType:{default:"image",enum:["image","file","bookmarks"],type:"string"},id:Z.common1,type:Z.common190},required:["id","type","docType"],then:Z.common89,type:"object"},request:{additionalProperties:!1,properties:{contentKey:Z.common1,folderId:Z.common1},type:"object"}},{auth:"none",constant:"GET_ATTENDEES_NO_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocomplete",request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.events\\.(?:[a-f0-9]{24}|@\\w+)$)"}}},{not:{propertyNames:{pattern:"^(?!links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$)"}}}],patternProperties:{"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdmin$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.isAdminPending$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.isInviting$":Z.common174,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.roles$":Z.common176,"^links\\.events\\.(?:[a-f0-9]{24}|@\\w+)\\.toBeValidated$":Z.common168},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"bearer",constant:"GET_ATTENDEES_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/globalautocompleteadmin/type/events/id/{id}/canSee/true",pathParams:Z.common127,request:{additionalProperties:!1,properties:{count:Z.common87,countType:Z.common179,fediverse:Z.common141,filters:{additionalProperties:!1,allOf:[{not:{propertyNames:{pattern:"^(?!links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$)"}}}],default:{"links.events.@{pathParams.id}":Z.common158,"links.events.@{pathParams.id}.isInviting":Z.common167,"links.events.@{pathParams.id}.toBeValidated":Z.common167},patternProperties:{"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdmin$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isAdminPending$":Z.common159,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.isInviting$":Z.common174,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.roles$":Z.common176,"^links\\.events\\.(?:[a-f0-9]{24}|@(?:\\{[^}]+\\}|[A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)?))\\.toBeValidated$":Z.common174},type:"object"},indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common142,name:Z.common1,notSourceKey:Z.common87,ranges:Z.common150,searchBy:Z.common154,searchType:Z.common179},required:["searchType","indexMin","initType","count","countType","indexStep","notSourceKey","filters","locality","fediverse"],type:"object"}},{auth:"none",constant:"COFORM_ANSWERS_SEARCH",contentType:"application/x-www-form-urlencoded",functionCocostum:"answerlist",method:"POST",path:"/survey/coform/answerslist",request:{additionalProperties:!1,properties:{contextId:Z.common11,contextType:Z.common235,costumEditMode:Z.common128,costumSlug:Z.common1,count:Z.common87,countType:Z.common254,fediverse:Z.common128,fields:Z.common33,filters:Z.common238,indexMax:Z.common86,indexMin:Z.common143,indexStep:Z.common144,initType:Z.common142,locality:Z.common145,mapUsed:Z.common197,name:Z.common1,notSourceKey:Z.common197,options:Z.common240,ranges:Z.common150,searchBy:Z.common154,searchTags:Z.common33,searchType:Z.common254,sortBy:Z.common244,sourceKey:Z.common33},required:["searchType","countType","indexMin","indexStep","initType","count","fediverse"],type:"object"}},{auth:"none",constant:"COFORM_ANSWERS_BY_ID",contentType:"application/x-www-form-urlencoded",functionCocostum:"findanswered",method:"POST",path:"/survey/coform/findanswered",request:{additionalProperties:!1,properties:{answerId:Z.common1,fields:Z.common33,finderPath:Z.common10},required:["answerId"],type:"object"}},{auth:"bearer",constant:"ADD_VOTE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/action/addaction",request:{additionalProperties:!1,properties:{action:{const:"vote",default:"vote",type:"string"},collection:Z.common256,details:{additionalProperties:!1,properties:{status:Z.common1},required:["status"],type:"object"},id:Z.common11},required:["id","collection","action","details"],type:"object"}},{auth:"bearer",constant:"ADD_REPORT_ABUSE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/action/addaction",request:{additionalProperties:!1,properties:{action:{const:"reportAbuse",default:"reportAbuse",type:"string"},collection:Z.common256,details:{additionalProperties:!1,properties:{comment:Z.common1,reason:Z.common1},required:["reason"],type:"object"},id:Z.common11},required:["id","collection","action","details"],type:"object"}},{auth:"bearer",constant:"UPDATE_PATH_VALUE",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/element/updatepathvalue",request:{additionalProperties:!1,properties:{arrayForm:Z.common3,collection:Z.common257,id:Z.common5,path:Z.common1,value:Z.common20},required:["id","collection","path","value"],type:"object"}},{auth:"bearer",constant:"DELETE_DOCUMENT_BY_CONTEXT",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/document/delete/dir/co2/contextType/{contextType}/contextId/{contextId}",pathParams:{additionalProperties:!1,properties:{contextId:Z.common5,contextType:Z.common257},required:["contextType","contextId"],type:"object"},request:{additionalProperties:!1,properties:{ids:Z.common11,parentId:Z.common5,parentType:Z.common257,path:{const:"communecter",default:"communecter",type:"string"}},required:["id","collection","path","value"],type:"object"}},{auth:"bearer",constant:"DEMOTE_ADMIN",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/link/updateadminlink/",request:{additionalProperties:!1,properties:{childId:Z.common11,childType:Z.common180,connect:{enum:["members","contributors"],type:"string"},isAdmin:Z.common141,parentId:Z.common11,parentType:{enum:["organizations","projects"],type:"string"}},required:["parentId","parentType","childId","childType","connect","isAdmin"],type:"object"}},{constant:"COSTUM_FILTER_COFORM",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/costum/francetierslieux/autoglobalthematicntwrk",request:{properties:{costumId:Z.common1,costumSlug:Z.common1,costumType:Z.common1,searchedData:Z.common239},type:"object"}},{constant:"SEARCH_ZONES",contentType:"application/x-www-form-urlencoded",method:"POST",path:"/co2/search/getzone",request:{properties:{costumId:Z.common1,costumSlug:Z.common1,costumType:Z.common1,countryCode:Z.common258,level:Z.common258,sortBy:Z.common1,upperLevelId:Z.common1},required:["countryCode","level"],type:"object"}}]};function H(e){return e instanceof Error}function W(e){return H(e)&&"response"in e&&"object"==typeof e.response&&"number"==typeof e.response.status}function Q(e){return H(e)?e.message:"string"==typeof e?e:e&&"object"==typeof e&&"message"in e?String(e.message):"Unknown error"}function Y(e){return function(e){return H(e)&&"status"in e&&"number"==typeof e.status}(e)?e.status:W(e)?e.response.status:e instanceof ApiError?e.status:void 0}class TokenStorageStrategy{}class MemoryStorageStrategy extends TokenStorageStrategy{_accessToken=null;_refreshToken=null;constructor(){super()}getAccessToken(){return this._accessToken}setAccessToken(e){this._accessToken=e}getRefreshToken(){return this._refreshToken}setRefreshToken(e){this._refreshToken=e}clear(){this._accessToken=null,this._refreshToken=null}}class LocalStorageStrategy extends TokenStorageStrategy{prefix;constructor(e="cocolight"){super(),this.prefix=e}getAccessToken(){return"undefined"!=typeof localStorage?localStorage.getItem(`${this.prefix}_accessToken`):null}setAccessToken(e){"undefined"!=typeof localStorage&&localStorage.setItem(`${this.prefix}_accessToken`,e??"")}getRefreshToken(){return"undefined"!=typeof localStorage?localStorage.getItem(`${this.prefix}_refreshToken`):null}setRefreshToken(e){"undefined"!=typeof localStorage&&localStorage.setItem(`${this.prefix}_refreshToken`,e??"")}clear(){"undefined"!=typeof localStorage&&(localStorage.removeItem(`${this.prefix}_accessToken`),localStorage.removeItem(`${this.prefix}_refreshToken`))}}class MultiServerTokenStorageStrategy extends TokenStorageStrategy{_currentBaseURL=null;constructor(){super()}use(e){if(!e)throw new Error("baseURL est requis");this._currentBaseURL=e.replace(/\/+$/,"")}_ensureContext(){if(!this._currentBaseURL)throw new Error("baseURL non défini. Appelez use(baseURL)")}_requireBaseURL(){return this._ensureContext(),this._currentBaseURL}}class MultiServerMemoryStorageStrategy extends MultiServerTokenStorageStrategy{_storage=new Map;constructor(){super()}getAccessToken(){const e=this._requireBaseURL();return this._storage.get(e)?.accessToken??null}setAccessToken(e){const t=this._requireBaseURL(),n=this._storage.get(t)||{};this._storage.set(t,{...n,accessToken:e})}getRefreshToken(){const e=this._requireBaseURL();return this._storage.get(e)?.refreshToken??null}setRefreshToken(e){const t=this._requireBaseURL(),n=this._storage.get(t)||{};this._storage.set(t,{...n,refreshToken:e})}clear(){const e=this._requireBaseURL();this._storage.delete(e)}getServers(){return Array.from(this._storage.keys())}exportAll(){return Object.fromEntries(this._storage.entries())}}class MultiServerLocalStorageStrategy extends MultiServerTokenStorageStrategy{prefix;constructor(e="cocolight"){super(),this.prefix=e}_key(e){return`${this.prefix}_tokens_${e}`}_getData(){if(this._ensureContext(),"undefined"==typeof localStorage)return{};const e=localStorage.getItem(this._key(this._currentBaseURL));return e?JSON.parse(e):{}}_setData(e){"undefined"!=typeof localStorage&&localStorage.setItem(this._key(this._currentBaseURL),JSON.stringify(e))}getAccessToken(){return this._getData().accessToken??null}setAccessToken(e){const t=this._getData();t.accessToken=e,this._setData(t)}getRefreshToken(){return this._getData().refreshToken??null}setRefreshToken(e){const t=this._getData();t.refreshToken=e,this._setData(t)}clear(){"undefined"!=typeof localStorage&&localStorage.removeItem(this._key(this._currentBaseURL))}getServers(){if("undefined"==typeof localStorage)return[];return Object.keys(localStorage).filter((e=>e.startsWith(`${this.prefix}_tokens_`))).map((e=>e.replace(`${this.prefix}_tokens_`,"")))}exportAll(){const e={};for(const t of this.getServers()){const n=this._key(t),r="undefined"!=typeof localStorage?localStorage.getItem(n):null;r&&(e[t]=JSON.parse(r))}return e}}const X=p;v.addType("oid",(e=>{if("string"==typeof e)return new K(e);if(void 0===e)return new K;throw new Error("Expected string value for ObjectID")}));class ApiClient extends s{__entityTag="ApiClient";userId=null;_baseURL;_refreshUrl;_endpoints;_debug;_fromJSONValue;_tokenStorage;_offlineClientManager=null;_ajv;_logger;_client;_breakerThreshold;_breakerResetTime;_breakerErrorCount=0;_breakerOpen=!1;_lastBreakerOpenTime=null;_accessToken=null;_refreshToken=null;_setUserId;constructor({baseURL:e,accessToken:t,refreshToken:n,refreshUrl:r="/api/cocolight/refreshtoken",endpoints:o=J.endpoints,timeout:i=3e4,debug:s=!1,maxRetries:a=0,circuitBreakerThreshold:p=5,circuitBreakerResetTime:d=6e4,fromJSONValue:m=!0,tokenStorageStrategy:l=null}){if(super(),!e)throw new ApiClientError('Le paramètre "baseURL" est obligatoire.',500);this._baseURL=e,this._refreshUrl=r,this._endpoints=o||J.endpoints,this._debug=s,this._fromJSONValue=m,this._breakerThreshold=p,this._breakerResetTime=d;let u=null;if(Object.defineProperty(this,"userId",{get:()=>u,set:()=>{throw new Error("Modification directe de userId non autorisée.")},enumerable:!0}),this._setUserId=e=>{u=e,this._logger?.debug(`[ApiClient] userId set: ${e}`)},this._ajv=new T({strict:!1,useDefaults:!0,allErrors:!0,verbose:!0}),A(this._ajv),this._ajv.addFormat("textarea",!0),this._ajv.addKeyword({keyword:"startBeforeEnd",type:"object",errors:!0,validate:this._startBeforeEndValidate}),this._logger=b({transport:{target:"pino-pretty",options:{colorize:!0}},level:s?"debug":"info"}),this._client=c.create({baseURL:e,timeout:i}),a>0&&(X(this._client,{retries:a,retryDelay:X.exponentialDelay,retryCondition:e=>X.isNetworkError(e)||X.isRetryableError(e),onRetry:(e,t,n)=>{this._logger.warn(`[Retry] Tentative #${e} pour ${n?.url}`),this.emit("retryAttempt",{retryCount:e,url:n?.url})}}),this._logger.info(`[ApiClient] Retry activé : ${a} max`)),l instanceof MultiServerTokenStorageStrategy&&l.use(this._baseURL),this._tokenStorage=l||new MemoryStorageStrategy,"function"!=typeof this._tokenStorage?.getAccessToken||"function"!=typeof this._tokenStorage?.setAccessToken||"function"!=typeof this._tokenStorage?.getRefreshToken||"function"!=typeof this._tokenStorage?.setRefreshToken||"function"!=typeof this._tokenStorage?.clear)throw new Error("[ApiClient] La stratégie de stockage des tokens n’est pas valide. Elle doit implémenter les méthodes requises.");n&&this.setRefreshToken(n),t&&this.setToken(t);const h=this._tokenStorage.getAccessToken();h&&this.setToken(h);const y=this._tokenStorage.getRefreshToken();y&&this.setRefreshToken(y),this._client.interceptors.response.use((e=>e),(async e=>{const t=e.config;if(t._retry)throw this._logger.error("[ApiClient] Requête déjà retentée, échec définitif."),e;if(e.response&&401===e.response.status&&this._refreshToken){t._retry=!0;try{this._logger.info("[ApiClient] Tentative de refresh du token...");if(await this._refreshAccessToken())return this._logger.info("[ApiClient] Token rafraîchi avec succès."),t.headers=t.headers??{},t.headers.Authorization="Bearer "+this.getToken(),this._logger.info("[ApiClient] Retente la requête originale avec le nouveau token."),this._client.request(t);throw this.resetSession(),new ApiClientError("Impossible de rafraîchir le token.",401)}catch(e){this.resetSession();const t={code:Y(e)||401,message:Q(e)};throw new ApiClientError("Erreur lors du rafraîchissement du token.",401,t)}}throw e}))}setToken(e){this._accessToken=e,this._tokenStorage.setAccessToken(e??""),e?this._client.defaults.headers.common.Authorization="Bearer "+e:delete this._client.defaults.headers.common.Authorization;const t=this._getIdFromToken(e);t&&(this._setUserId(t),this._logger.debug(`[ApiClient] userId extrait et défini : ${t}`)),this._logger.debug(`[ApiClient] setToken: ${e}`)}getToken(){return this._accessToken}setRefreshToken(e){if(this._refreshToken=e,this._tokenStorage.setRefreshToken(e??""),null===this.userId){const t=this._getIdFromToken(e);t&&(this._setUserId(t),this._logger.debug(`[ApiClient] userId extrait depuis refreshToken : ${t}`))}this._logger.debug(`[ApiClient] setRefreshToken: ${e}`)}getRefreshToken(){return this._refreshToken}get isConnected(){return!!this._accessToken}_getIdFromToken(e){if(!e)return null;try{const t=d(e);return this._logger.debug("[ApiClient] Payload décodé :",t),t.id||t.userId||null}catch(e){return this._logger.error("[ApiClient] Erreur lors du décodage du token :",e),null}}async _refreshAccessToken(){if(!this._refreshToken)return!1;const e=c.create({baseURL:this._baseURL,timeout:1e4,headers:{"Content-Type":"application/json"}});try{const t=await e.post(this._refreshUrl,{refreshToken:this._refreshToken});return!(!t.data||!t.data.token)&&(this.setToken(t.data.token),t.data.refreshToken&&this.setRefreshToken(t.data.refreshToken),this.emit("refreshSuccess",t.data),!0)}catch(e){return this.emit("refreshFailed",{error:Q(e)}),this.resetSession(),this._logger.error(`[ApiClient] Refresh Error : ${Q(e)}`),!1}}_checkCircuitBreaker(){if(!this._breakerOpen)return!0;const e=Date.now();return null!=this._lastBreakerOpenTime&&e-this._lastBreakerOpenTime>this._breakerResetTime&&(this._breakerOpen=!1,this._breakerErrorCount=0,this._logger.warn("[ApiClient] Circuit breaker réinitialisé"),this.emit("circuitBreakerReset"),!0)}_updateCircuitBreakerError(){this._breakerErrorCount+=1,this._logger.warn(`[ApiClient] Erreur #${this._breakerErrorCount} sur ${this._breakerThreshold}`),this._breakerErrorCount>=this._breakerThreshold&&(this._breakerOpen=!0,this._lastBreakerOpenTime=Date.now(),this._logger.error("[ApiClient] Circuit breaker ACTIVÉ - L'API est considérée indisponible"),this.emit("circuitBreakerOpen",{timestamp:this._lastBreakerOpenTime}))}_resetCircuitBreakerSuccess(){this._breakerErrorCount=0,this._breakerOpen&&(this._breakerOpen=!1,this._logger.warn("[ApiClient] Circuit breaker refermé suite à un succès"))}static stripNullsInPlace(e){if(e&&"object"==typeof e&&e.value&&"function"==typeof e.value.pipe)return e;if(Array.isArray(e))for(let t=e.length-1;t>=0;t--)null===e[t]||void 0===e[t]?e.splice(t,1):"object"==typeof e[t]&&ApiClient.stripNullsInPlace(e[t]);else if(e&&"object"==typeof e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(null===e[t]||void 0===e[t]?delete e[t]:"object"==typeof e[t]&&ApiClient.stripNullsInPlace(e[t]));return e}_resolveSpecialValuesInPlace(e,t={}){const n={userId:()=>this.userId,accessToken:()=>this._accessToken,refreshToken:()=>this._refreshToken,baseURL:()=>this._baseURL,pathParams:e=>{const n=this._getValueByPath(t,e);return null!=n?n:void 0}},r=/@(?:\{([^}]+)\}|([\w.]+))/g,o=e=>"string"!=typeof e?e:e.replace(r,((t,r,o)=>{if(r){if(r.startsWith("pathParams.")){const e=r.substring(11),t=n.pathParams(e);return null!=t?t:`@{${r}}`}{const e=n[r];if("function"==typeof e){const t=e();return null!=t?t:`@{${r}}`}return`@{${r}}`}}if(o){if(o.startsWith("pathParams.")){const e=o.match(/^pathParams\.([^.]+)(.*)$/);if(e){const t=e[1],r=e[2],i=n.pathParams(t);return null!=i?i+r:`@${o}`}return`@${o}`}{const e=n[o];if("function"==typeof e){const t=e();return null!=t?t:`@${o}`}return`@${o}`}}return e})),i=e=>{if((e=>e&&"object"==typeof e&&("function"==typeof e.pipe||"undefined"!=typeof Buffer&&e instanceof Buffer))(e))return e;if(Array.isArray(e))return e.map(i);if((e=>"[object Object]"===Object.prototype.toString.call(e))(e)){const t={};for(const[n,r]of Object.entries(e)){t[o(n)]=i(r)}return t}return"string"==typeof e?o(e):e};return i(e)}_cleanSchemaLeftoverAlias(e){const t=/@\w+/;if(Array.isArray(e))return e.map((e=>this._cleanSchemaLeftoverAlias(e)));if(e&&"object"==typeof e){const n={};for(const r of Object.keys(e)){const o=e[r];if(!t.test(r)){if("default"===r){if("string"==typeof o&&t.test(o))continue;if(o&&"object"==typeof o){const e=this._cleanSchemaLeftoverAlias(o);Object.keys(e).length>0&&(n[r]=e);continue}}"string"==typeof o&&t.test(o)||(n[r]=this._cleanSchemaLeftoverAlias(o))}}return n}return e}async safeCall(e,...t){try{return await e(...t)}catch(e){throw this._logger.error(`[ApiClient.safeCall] Erreur: ${Q(e)}`),e}}async callEndpoint(e,t={},n=!0,r=!0){const o=this._endpoints.find((t=>t.constant===e));if(!o)throw new ApiClientError(`Endpoint introuvable : ${e}`,404);const{path:i,method:s,contentType:a,auth:c,pathParams:p,request:d,responses:m}=o,l=(s||"GET").toLowerCase(),u=a||"application/json",h={"Content-Type":u};if(this._accessToken)"bearer"===c?h.Authorization=`Bearer ${this._accessToken}`:c&&"none"!==c||h.Authorization||(h.Authorization=`Bearer ${this._accessToken}`);else if("bearer"===c)throw new ApiClientError(`Token requis pour l'endpoint sécurisé : ${e}`,401);let y,f=i,g={};if(p){let n=p;"none"===c&&null===this.userId&&(n=this._cleanSchemaLeftoverAlias(p));const r=t.pathParams||{},o=this._ajv.compile(n);if(!o(r)){const t=this._ajvErrorHuman(o.errors??[]);throw this.emit("validationError",{stage:"pathParams",errors:o.errors}),new ApiValidationError(`callEndpoint: ${e} - Path parameter validation failed.`,400,t,o.errors)}g=this._resolveSpecialValuesInPlace(r),f=f.replace(/\{(\w+)\}/g,((e,t)=>{const n=g[t];if(void 0!==n)return encodeURIComponent(n);throw new ApiClientError(`Path param manquant ou non résolu : {${t}}`,400)}))}if(d){let n=d;"none"===c&&null===this.userId&&(n=this._cleanSchemaLeftoverAlias(d));let r={...t};delete r.pathParams,"application/x-www-form-urlencoded"===u&&(r=ApiClient.normalizeDatesForValidation(r),r=ApiClient.normalizeSchemaDateFields(r,n));const o=ApiClient.stripNullsInPlace(r),i=this._ajv.compile(n);if(!i(o)){const t=i.errors?this._ajvErrorHuman(i.errors):[];throw this.emit("validationError",{stage:"request",errors:i.errors}),new ApiValidationError(`callEndpoint: ${e} - Request validation failed.`,400,t,i.errors)}t=this._resolveSpecialValuesInPlace(o,g)}if(this._offlineClientManager?.isOffline()){if("function"==typeof this._offlineClientManager._enqueueOfflineAction){this._logger.warn(`[ApiClient] Mode dégradé : mise en file de ${e}`),await this._offlineClientManager._enqueueOfflineAction({constant:e,data:t,options:{transformResponseData:n,validateResponseSchema:r}}),this._logger.info(`[ApiClient] Requête ${e} mise en file (offline mode)`),this.emit("queuedOffline",{constant:e,reason:"offlineMode",data:t});return{data:null,offline:!0}}throw this._logger.warn("[ApiClient] Mode dégradé actif mais offlineManager non initialisé correctement"),new ApiClientError("Mode hors-ligne actif, mais gestionnaire offline non disponible.",503)}if(!this._checkCircuitBreaker()){if(!1===this._offlineClientManager?.isOffline?.()&&"function"==typeof this._offlineClientManager._enqueueOfflineAction){this._logger.warn(`[ApiClient] Circuit breaker actif → mise en file de ${e}`),await this._offlineClientManager._enqueueOfflineAction({constant:e,data:t,options:{transformResponseData:n,validateResponseSchema:r}}),this._logger.info(`[ApiClient] Requête ${e} mise en file (circuit breaker)`),this.emit("queuedOffline",{constant:e,reason:"circuitBreaker",data:t});return{data:null,breaker:!0}}throw new CircuitBreakerError("Le circuit breaker est activé, impossible d'appeler l'API")}"application/json"===u||"multipart/form-data"===u?y=t:"application/x-www-form-urlencoded"===u&&(y=ApiClient.toURLSearchParams(t)),this._logger.debug(`[ApiClient] callEndpoint: ${e} -> ${f}, method=${l}`);try{const e=await this._client.request({url:f,method:l,headers:h,["get"===l?"params":"data"]:y});if(r){const t=String(e.status),n=m?.[t];if(n){const t=this._ajv.compile(n);if(!t(e.data)){const n=this._ajvErrorHuman(t.errors??[]);throw this.emit("validationError",{stage:"response",errors:t.errors}),new ApiValidationError("Response validation failed.",e.status,n,t.errors)}}}return this._resetCircuitBreakerSuccess(),"function"==typeof n?e.data=n(e.data):!0===n&&(e.data=this._transformData(e.data)),Array.isArray(o.postActions)&&o.postActions.forEach((t=>{const n=t.path?this._getValueByPath(e.data,t.path):null;switch(t.type){case"setToken":this.setToken(n);break;case"setRefreshToken":this.setRefreshToken(n);break;case"resetSession":this.resetSession();break;case"emitEvent":t.event&&(this.emit(t.event,n),this._logger.debug(`[ApiClient] Event émis : ${t.event}`,n));break;case"callMethod":"function"==typeof this[t.method]?(this[t.method](),this._logger.debug(`[ApiClient] Méthode appelée : ${t.method}`)):this._logger.warn(`[ApiClient] Méthode inconnue : ${t.method}`);break;default:this._logger.warn(`[ApiClient] Action inconnue : ${t.type}`)}})),e}catch(t){if(this._updateCircuitBreakerError(),this._logger.error(`[ApiClient] Erreur lors de l'appel de ${e}: ${Q(t)}`),t instanceof ApiValidationError)throw t;{const e=W(t)?t.response.status:500,n=W(t)?t.response.data:null;throw new ApiClientError(`Erreur lors de l'appel de l'API : ${Q(t)}`,e,n)}}}_ajvErrorHuman(e){try{const t=new a(e);return t.errors.map((({message:e})=>e))}catch(t){return this._logger.error("[ApiClient] _ajvErrorHuman",t),e.map((({message:e})=>e))}}checkAndThrowApiResponseError(e){if(!("status"in e))return e;const t=e.data;if(!t||"object"!=typeof t)return e;if("boolean"==typeof t.result&&!1===t.result)throw new ApiResponseError(t.msg||"Erreur inconnue",e.status,t);if(t.resultErrors&&"object"==typeof t.resultErrors&&"boolean"==typeof t.resultErrors.result&&!1===t.resultErrors.result)throw new ApiResponseError(t.resultErrors.msg||"Erreur inconnue",e.status,t);return e}resetSession(){this.setToken(null),this.setRefreshToken(null),this._setUserId(null),this._tokenStorage.clear(),delete this._client.defaults.headers.common.Authorization,this._logger.info("[ApiClient] Session utilisateur réinitialisée."),this.emit("sessionReset")}_getValueByPath(e,t){if(!t)return;return t.split(".").reduce(((e,t)=>e&&e[t]),e)}static normalizeDatesForValidation(e){if(null==e)return e;if(e&&"object"==typeof e&&e.__isReactive&&e.__raw)return ApiClient.normalizeDatesForValidation(e.__raw);if(e instanceof Date)return e.toISOString().replace(/\.\d{3}Z$/,"+0000");if(Array.isArray(e))return e.map((e=>ApiClient.normalizeDatesForValidation(e)));if("object"==typeof e){const t={};for(const n of Object.keys(e))t[n]=ApiClient.normalizeDatesForValidation(e[n]);return t}return e}static normalizeSchemaDateFields(e,t){if(!e||!t||"object"!=typeof e)return e;const n={...e};let r=t.properties||{};if(t.allOf&&Array.isArray(t.allOf))for(const e of t.allOf)e.properties&&(r={...r,...e.properties}),e.then&&e.then.properties&&(r={...r,...e.then.properties});t.then&&t.then.properties&&(r={...r,...t.then.properties});for(const[e,t]of Object.entries(r)){const r=t;if("date"===r?.format&&n[e]){const t=n[e];"string"==typeof t&&t.includes("T")&&(n[e]=t.split("T")[0])}}return n}static toURLSearchParams(e,t={}){return this._buildParams(e,new URLSearchParams,t)}static _buildParams(e,t,n={}){if("object"!=typeof e||null===e)throw new TypeError("La donnée doit être un objet non nul.");const{dots:r=!1,indexes:o=!1,metaTokens:i=!0}=n,s=[];function a(e){return"[object Object]"===Object.prototype.toString.call(e)||Array.isArray(e)}function c(e){return e.endsWith("[]")?e.slice(0,-2):e}function p(e,t,n=!1){return e?e.concat(t).map(((e,t)=>(e=c(e),!n&&t?`[${e}]`:e))).join(n?".":""):t}function d(e){return null==e?"":e instanceof Date?e.toISOString():(e instanceof Blob||e instanceof File||e instanceof ArrayBuffer||ArrayBuffer.isView(e),e)}return function e(n,m=[]){null==n||s.includes(n)||(s.push(n),Object.entries(n).forEach((([n,s])=>{void 0!==s&&function(e,n,s){if(e&&"object"==typeof e){if(n.endsWith("{}"))return n=i?n:n.slice(0,-2),t.append(p(s,n,r),JSON.stringify(e)),!1;if(Array.isArray(e)&&!e.some(a)||n.endsWith("[]"))return n=c(n),e.forEach(((e,i)=>{if(null!=e){const a=o?p(s.concat(n),i,r):`${p(s,n,r)}[]`;t.append(a,d(e))}})),!1}return!!a(e)||(t.append(p(s,n,r),d(e)),!1)}(s,n.trim(),m)&&e(s,m.concat(c(n)))})),s.pop())}(e),t}_transformData(e){if(e&&"object"==typeof e)if(e.resultGoods?.msg)e=this._normalizeJsonData({msg:e.resultGoods.msg,...e});else if(e.resultErrors?.msg)e=this._normalizeJsonData({msg:e.resultErrors.msg,...e});else if(e.results&&"object"==typeof e.results&&!Array.isArray(e.results))e.results=Object.keys(e.results).map((t=>this._normalizeJsonData({id:t,...e.results[t]})));else if(Array.isArray(e.results)&&e.results.length>0)e.results=e.results.map((e=>this._normalizeJsonData(e)));else if(e.news&&Array.isArray(e.news)&&0===e.news.length)e=e.news;else if(e.news&&"object"==typeof e.news&&!Array.isArray(e.news))e=Object.keys(e.news).map((t=>this._normalizeJsonData({id:t,...e.news[t]})));else if(e.notif&&"object"==typeof e.notif&&!Array.isArray(e.notif))e.notif=Object.keys(e.notif).map((t=>this._normalizeJsonData({id:t,...e.notif[t]})));else if(e.citoyens&&"object"==typeof e.citoyens&&!Array.isArray(e.citoyens)&&e.organizations&&"object"==typeof e.organizations&&!Array.isArray(e.organizations))e=[...Object.keys(e.citoyens).map((t=>this._normalizeJsonData({id:t,...e.citoyens[t]}))),...Object.keys(e.organizations).map((t=>this._normalizeJsonData({id:t,...e.organizations[t]})))];else if(e.citoyens&&"object"==typeof e.citoyens&&!Array.isArray(e.citoyens))e=Object.keys(e.citoyens).map((t=>this._normalizeJsonData({id:t,...e.citoyens[t]})));else if(e.cities&&"object"==typeof e.cities&&!Array.isArray(e.cities))e=Object.keys(e.cities).map((t=>this._normalizeJsonData({id:t,...e.cities[t]})));else if(e.cities&&Array.isArray(e.cities)&&0===e.cities.length)e=e.cities;else if(e.newComment&&"object"==typeof e.newComment)e.newComment=this._normalizeJsonData({...e.newComment});else if(Array.isArray(e))e=e.map((e=>this._normalizeJsonData(e)));else if(e.map&&"object"==typeof e.map)e.map=this._normalizeJsonData(e.map);else if(e.object&&"object"==typeof e.object)e.object=this._normalizeJsonData(e.object);else if("object"==typeof e&&Object.keys(e).length>0){const t=Object.keys(e).every((e=>/^[0-9a-fA-F]{24}$/.test(e)));e=t?Object.keys(e).map((t=>({id:t,...this._normalizeJsonData(e[t])}))):this._normalizeJsonData(e)}return e}_normalizeJsonData(e){if(!e||"object"!=typeof e)return e;if(e=this._normalizeRecursively(e),e?.mediaImg?.images&&Array.isArray(e.mediaImg.images)&&e.mediaImg.images.length>0&&(e.mediaImg.countImages=e.mediaImg.images.length),e?.mediaFile?.files&&Array.isArray(e.mediaFile.files)&&e.mediaFile.files.length>0&&(e.mediaFile.countFiles=e.mediaFile.files.length),e?.src?.changes&&"object"==typeof e.src.changes&&Object.keys(e.src.changes).length>0&&Object.keys(e.src.changes).forEach((t=>{e.src.changes[t]&&(e.src.changes[t]=this._ensureFullURL(e.src.changes[t]))})),e?.openingHours&&Array.isArray(e.openingHours)&&e.openingHours.length>0&&(e.openingHours=e.openingHours.filter((e=>e.dayOfWeek&&e.hours&&e.hours[0]&&e.hours[0].opens))),e.replies&&"object"==typeof e.replies&&Object.keys(e.replies).length>0&&(e.replies=Object.keys(e.replies).map((t=>this._normalizeJsonData({id:t,...e.replies[t]})))),e?.author&&"object"==typeof e.author&&Object.keys(e.author).length>0&&!("profilThumbImageUrl"in e.author)){const t=Object.keys(e.author)[0];e.author={...e.author[t]}}return e?.timeAgo&&delete e.timeAgo,"people"===e?.author?.typeSig&&(e.author.type="citoyens"),"people"===e?.typeSig&&(e.collection="citoyens"),"organizations"===e?.typeSig&&(e.collection="organizations"),this._fromJSONValue?v.fromJSONValue(e):e}_ensureFullURL(e){if(!e)return e;if(!(e=e.trim())||/^https?:\/\//i.test(e))return e;let t="/";return t=this._baseURL.endsWith("/")&&e.startsWith("/")||this._baseURL.endsWith("/")||e.startsWith("/")?"":"/",`${this._baseURL}${t}${e}`}_normalizeString(e){return"true"===e||"false"!==e&&e}_normalizeId(e){return e._id&&e._id.$id&&/^[0-9a-fA-F]{24}$/.test(e._id.$id)&&(e.id=e._id.$id,e._id={$type:"oid",$value:e._id.$id}),e.id&&e.id.$id&&/^[0-9a-fA-F]{24}$/.test(e.id.$id)&&(e._id={$type:"oid",$value:e.id.$id},e.id=e.id.$id),e}_normalizeDate(e){if(e&&"object"==typeof e&&"number"==typeof e.sec)return{$date:1e3*e.sec};if("number"==typeof e)return{$date:1e3*e};if("string"==typeof e&&""!==e.trim()){const t=new Date(e);if(!isNaN(t.getTime()))return v.toJSONValue(t)}return e}_normalizeImage(e){return"string"==typeof e&&""!==e.trim()?this._ensureFullURL(e):e}_imageFields=["profilImageUrl","profilThumbImageUrl","profilMediumImageUrl","profilMarkerImageUrl","profilBannerUrl","profilRealBannerUrl","imagePath","imageThumbPath","docPath","imageThumb","imageMediumPath"];_dateFields=["modified","created","updated","birthDate","lastLoginDate","startDate","endDate","date","issuedOn"];_normalizeRecursively(e){if("string"==typeof e)return this._normalizeString(e);if(Array.isArray(e))return e.map((e=>this._normalizeRecursively(e)));if(null!==e&&"object"==typeof e){const t={};return Object.keys(e).forEach((n=>{let r=this._normalizeRecursively(e[n]);this._dateFields.includes(n)&&(r=this._normalizeDate(r)),this._imageFields.includes(n)&&(r=this._normalizeImage(r)),"content"===n&&r&&"object"==typeof r&&r.image&&(r.image=this._normalizeImage(r.image)),t[n]=r})),this._normalizeId(t)}return e}_startBeforeEndValidate=(e,t)=>{if(!t.startDate||!t.endDate)return!0;const n=new Date(t.startDate)<new Date(t.endDate);return n||(this._startBeforeEndValidate.errors=[{instancePath:"/startDate",schemaPath:"#/startBeforeEnd",keyword:"startBeforeEnd",params:{},message:"startDate must be before endDate"}]),n};getRequestSchema(e){const t=this._endpoints.find((t=>t.constant===e));return t?.request||null}getPathSchema(e){return this._endpoints.find((t=>t.constant===e))?.pathParams||null}onEvent(e={}){const t=["retryAttempt","queuedOffline","circuitBreakerOpen","circuitBreakerReset","refreshSuccess","refreshFailed","sessionReset","validationError","offlineModeChanged","userLoggedIn"];for(const n of t)"function"==typeof e[n]&&this.on(n,e[n])}getDeclaredEvents(){const e=new Set;for(const t of this._endpoints)if(Array.isArray(t.postActions))for(const n of t.postActions)"emitEvent"===n.type&&n.event&&e.add(n.event);return Array.from(e)}}function ee(e){return e&&"object"==typeof e&&"status"in e&&"data"in e}class UserApi{client;loggedUser=null;constructor(e){this.client=e instanceof ApiClient?e:new ApiClient(e)}get isConnected(){return this.client.isConnected}get userId(){return this.client.userId}async login(e,t){return this.client.safeCall((async()=>{const n=await this.client.callEndpoint("AUTHENTICATE_URL",{email:e,password:t});return this.loggedUser=new User(this.client,n.data.user,{EndpointApi:EndpointApi,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment}),this.loggedUser}))}async meIsconnected(){if(!this.client.isConnected||!this.client.userId)throw new ApiError("User not connected",401);return this.client._logger.debug("UserApi","meIsconnected",this.client.userId),this.loggedUser=new User(this.client,{id:this.client.userId},{EndpointApi:EndpointApi,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment}),this.loggedUser}async register({name:e,username:t,email:n,pwd:r}){return this.client.safeCall((async()=>{const o=await this.client.callEndpoint("PERSON_REGISTER",{name:e,username:t,email:n,pwd:r});if(!ee(o))throw new ApiError("Requête mise en file (offline/circuit breaker)",503,o);if(!1===o?.data?.result)throw new ApiResponseError(o.data.msg,o.status,o.data);return o.data}))}async recoverPassword(e){return this.client.safeCall((async()=>{const t=await this.client.callEndpoint("PASSWORD_RECOVERY",{email:e});if(!ee(t))throw new ApiError("Requête mise en file (offline/circuit breaker)",503,t);if(!1===t?.data?.result)throw new ApiResponseError(t.data.msg,t.status,t.data);return t.data}))}}f("User",User),f("Organization",Organization),f("Project",Project),f("Event",Event),f("Poi",Poi),f("Badge",Badge),f("EndpointApi",EndpointApi),f("News",News),f("Comment",Comment),f("Answer",Answer);class Api{_loggedUser;_client;static async userLogin(e,t,n){const r=Api.userApi(n);return await Api.userApiLogin(r,e,t)}static userApi(e){try{return new UserApi(e)}catch(e){throw console.error("[Api.userApi] Erreur lors de la création d'un objet utilisateur :",e.message),e}}static async userApiLogin(e,t,n){try{if(!e)throw new ApiError("userApi is not defined",500);if(!e.client)throw new ApiError("userApi.client is not defined",500);if(e.client.isConnected){const t=await e.meIsconnected();return new Api(t,e.client)}{if(!t||!n)throw new ApiError("email and password are required",400);const r=await e.login(t,n);return new Api(r,e.client)}}catch(e){if(e instanceof ApiClientError&&e?.details?.error)throw new ApiAuthenticationError(e.details.error,e.status,e.details);throw e}}constructor(e,t){this._loggedUser=e,this._client=t}async me(){if(!this._loggedUser)throw new ApiAuthenticationError("Accès refusé : utilisateur non authentifié.",401);return await this._loggedUser.get(),this._loggedUser}async user(e){try{if(e.id||e.slug){const t=new User(this._client,e,{EndpointApi:EndpointApi,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment});return await t.get(),t}return new User(this._client,e,{EndpointApi:EndpointApi,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment})}catch(e){throw console.error("[Api.user] Erreur lors de la création d'un objet utilisateur public :",e.message),e}}async organization(e){try{const t=new Organization(this._client,e,{EndpointApi:EndpointApi,User:User,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment,Answer:Answer});if(!e.id&&!e.slug)throw new Error("Vous devez fournir un id ou un slug pour créer une instance Organization.");return await t.get(),t}catch(e){throw console.error("[Api.organization] Erreur lors de la création d'un objet organisation :",e.message),e}}async project(e){try{const t=new Project(this._client,e,{EndpointApi:EndpointApi,User:User,Organization:Organization,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment});if(!e.id&&!e.slug)throw new Error("Vous devez fournir un id ou un slug pour créer une instance Project.");return await t.get(),t}catch(e){throw console.error("[Api.project] Erreur lors de la création d'un objet projet :",e.message),e}}async event(e){try{const t=new Event(this._client,e,{EndpointApi:EndpointApi,User:User,Organization:Organization,Project:Project,Poi:Poi,Badge:Badge,News:News,Comment:Comment});if(!e.id&&!e.slug)throw new Error("Vous devez fournir un id ou un slug pour créer une instance Event.");return await t.get(),t}catch(e){throw console.error("[Api.event] Erreur lors de la création d'un objet événement :",e.message),e}}async poi(e){try{const t=new Poi(this._client,e,{EndpointApi:EndpointApi,User:User,Organization:Organization,Project:Project,Poi:Poi,Badge:Badge,News:News,Comment:Comment});if(!e.id&&!e.slug)throw new Error("Vous devez fournir un id ou un slug pour créer une instance Poi.");return await t.get(),t}catch(e){throw console.error("[Api.poi] Erreur lors de la création d'un objet poi :",e.message),e}}async answer(e){try{const t=new Answer(this._client,e,{EndpointApi:EndpointApi,User:User,Organization:Organization,Project:Project,Event:Event,Poi:Poi,Badge:Badge,News:News,Comment:Comment});if(!e.id)throw new Error("Vous devez fournir un id pour créer une instance Answer.");return await t.get(),t}catch(e){throw console.error("[Api.answer] Erreur lors de la création d'un objet Answer :",e.message),e}}async entitySlug(e){if(!e)throw new ApiError("slug requis",400);try{const t=await this.endpointApi.getElementsKey({pathParams:{slug:e}});if(t.contextId&&t.contextType){const n=w(t.contextType,this._client,{id:t.contextId});if(!n)throw new ApiResponseError(`Le type d'entité pour le slug ${e} n'est pas reconnu`,200,t);return await n.get(),n}throw new ApiResponseError(`Le slug ${e} n'est pas valide`,200,t)}catch(t){throw t instanceof ApiResponseError?new ApiResponseError(`Impossible de récupérer l'identifiant pour le slug ${e}`,t.status,t.responseData):t}}get client(){return this._client}get endpointApi(){return new EndpointApi(this._client)}logout(){this._loggedUser=null,this._client.resetSession(),this._client._logger.info("UserApi: User logged out")}}class OfflineQueueStorageStrategy{}class MemoryOfflineStorage extends OfflineQueueStorageStrategy{_queue=[];constructor(){super()}async loadQueue(){return this._queue}async saveQueue(e){this._queue=[...e]}}class LocalStorageOfflineStorage extends OfflineQueueStorageStrategy{key;constructor(e="cocolight-api-offline-queue"){super(),this.key=e}async loadQueue(){try{const e=localStorage.getItem(this.key);return(e?JSON.parse(e):null)??[]}catch{return[]}}async saveQueue(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch(e){console.warn("[Offline] Échec du stockage localStorage",e)}}}class OfflineClientManager{_clients;_client;_offlineMode;_pingInterval;_offlineQueueStorage;_offlineQueue;_monitoringStarted;constructor(e){if(!(e&&e instanceof ApiClient))throw new Error("[OfflineClientManager] apiClient doit être une instance de ApiClient");this._clients=new Map,this._client=e,this._offlineMode=void 0,this._pingInterval=void 0,this._offlineQueueStorage=void 0,this._offlineQueue=[],this._monitoringStarted=void 0}static async attachTo(e,t={}){e._offlineClientManager=new OfflineClientManager(e);const n=await async function(e="auto"){if("memory"===e)return new MemoryOfflineStorage;if("localStorage"===e){if("undefined"!=typeof window&&window.localStorage)return new LocalStorageOfflineStorage;throw new Error("localStorage is not available in this environment.")}if("file"===e){if("undefined"!=typeof window&&window.localStorage)throw new Error("file storage is not available in this environment.");const{FileOfflineStorage:e}=await Promise.resolve().then((function(){return pe}));return new e}if("auto"===e){if("undefined"!=typeof window&&window.localStorage)return new LocalStorageOfflineStorage;{const{FileOfflineStorage:e}=await Promise.resolve().then((function(){return pe}));return new e}}throw new Error(`Unsupported offline storage strategy: ${e}`)}(t?.offlineStorageStrategy||"auto");await e._offlineClientManager._initOfflineQueue(n),t?.disableOfflineMonitoring||e._offlineClientManager.startOfflineMonitoring(t)}async getClient(e){const t=`${e.baseURL}|${e.accessToken}`;if(this._clients.has(t))return this._clients.get(t);const n=new ApiClient({baseURL:e.baseURL,accessToken:e.accessToken,refreshToken:e.refreshToken,debug:this._client._debug});return this._clients.set(t,n),n}async replayAction(e){const t=await this.getClient(e.meta);try{const n=await t.callEndpoint(e.constant,e.data,e.options?.transformResponseData??!0,e.options?.validateResponseSchema??!0);return this._client._logger.info(`[OfflineReplay] Succès ${e.constant} sur ${e.meta.baseURL}`),n}catch(t){throw this._client._logger.error(`[OfflineReplay] Échec ${e.constant}`,t.message),t}}startOfflineMonitoring({interval:e=3e4,disableOfflineMonitoring:t=!1}={}){t||this._monitoringStarted||(this._monitoringStarted=!0,this._offlineMode="undefined"!=typeof window&&"undefined"!=typeof navigator&&!navigator.onLine,"undefined"!=typeof window&&(window.addEventListener("online",(()=>this.setOfflineMode(!1))),window.addEventListener("offline",(()=>this.setOfflineMode(!0)))),this._pingInterval=setInterval((async()=>{const e=this._offlineMode;try{await this._client._client.head("/api/cocolight/infoserver",{timeout:5e3}),e&&this.setOfflineMode(!1)}catch{this._client._logger.error("[OfflineMonitor] ping() échoué → passage en offline"),this.setOfflineMode(!0)}}),e))}setOfflineMode(e){this._offlineMode!==e&&(this._offlineMode=e,"function"==typeof this._client.emit&&this._client.emit("offlineModeChanged",e),this._client._logger.info(`[ApiClient] Mode offline : ${e} (set depuis monitoring)`),e||"function"!=typeof this._replayOfflineQueue||this._replayOfflineQueue())}isOffline(){return!!this._offlineMode}async _enqueueOfflineAction({constant:e,data:t,options:n={}}){if(!this._offlineQueueStorage)throw new Error("[OfflineClientManager] _offlineQueueStorage non initialisé");const r=this._client.getToken()||this._client.getRefreshToken(),o=this._client._endpoints.find((t=>t.constant===e));if("required"===(o?.authPolicy||("none"===o?.auth?"none":"required"))&&!r)return void this._client._logger.warn(`[Offline] Action ignorée : token requis mais absent (${e})`);const i={constant:e,data:t,options:n,meta:{baseURL:this._client._baseURL,accessToken:this._client.getToken(),refreshToken:this._client.getRefreshToken(),timestamp:Date.now()}};this._offlineQueue.push(i),await this._offlineQueueStorage.saveQueue(this._offlineQueue),this._client._logger.info(`[Offline] Action mise en file : ${e}`)}async _replayOfflineQueue(){if(!this._offlineQueueStorage)throw new Error("[OfflineClientManager] _offlineQueueStorage non initialisé");const e=[...this._offlineQueue];this._offlineQueue=[],await this._offlineQueueStorage.saveQueue([]);for(const t of e){const e=this._client._endpoints.find((e=>e.constant===t.constant)),n=e?.authPolicy||("none"===e?.auth?"none":"required"),r=t.meta.accessToken||t.meta.refreshToken;if("required"!==n||r)try{await this.replayAction(t)}catch(e){this._client._logger.error("[Offline] Relecture échouée :",e.message),this._offlineQueue.push(t)}else this._client._logger.warn(`[Offline] Rejetée : token requis manquant (${t.constant})`)}await this._offlineQueueStorage.saveQueue(this._offlineQueue)}async _initOfflineQueue(e){if(!(e&&e instanceof OfflineQueueStorageStrategy))throw new Error("[OfflineClientManager] storageStrategy doit être une instance de OfflineQueueStorageStrategy");this._offlineQueueStorage=e,this._offlineQueue=await e.loadQueue()}}const te=["NGO","LocalBusiness","Group","GovernmentOrganization","Cooperative"],ne=["abandoned","concept","development","production","started","testing","idea","mature","qa","finished"],re=["workshop","competition","concert","contest","conference","debate","exhibition","festival","crowdfunding","fair","course","protest","market","film","getTogether","meeting","spectacle","internship","stand","others"],oe=["link","tool","machine","software","rh","Resource material","Financial Ressource","ficheBlanche","geoJson","compostPickup","video","sharedLibrary","recoveryCenter","trash","history","something2See","funPlace","place","artPiece","streetArts","openScene","stand","parking","other"],ie={ApiClient:ApiClient,Api:Api,error:h,reactive:q,effect:j,batch:k,isSignal:x,reactiveObject:N,isReactive:M,computed:B,watch:$,getSignals:z,subscribeTo:R,tokenStorageStrategy:{createDefaultTokenStorageStrategy:async function(e="auto"){if("memory"===e)return new MemoryStorageStrategy;if("localStorage"===e){if("undefined"!=typeof window&&window.localStorage)return new LocalStorageStrategy;throw new Error("localStorage is not available in this environment.")}if("file"===e){if("undefined"!=typeof window&&window.localStorage)throw new Error("file storage is not available in this environment.");const{FileStorageStrategy:e}=await Promise.resolve().then((function(){return ce}));return new e}if("undefined"!=typeof window&&window.localStorage)return new LocalStorageStrategy;const{FileStorageStrategy:t}=await Promise.resolve().then((function(){return ce}));return new t},TokenStorageStrategy:TokenStorageStrategy,createDefaultMultiServerTokenStorageStrategy:async function(e="auto"){if("memory"===e)return new MultiServerMemoryStorageStrategy;if("localStorage"===e){if("undefined"!=typeof window&&void 0!==window.localStorage)return new MultiServerLocalStorageStrategy;throw new Error("localStorage n'est pas disponible dans cet environnement.")}if("file"===e){if("undefined"!=typeof window&&void 0!==window.localStorage)throw new Error("Le stockage fichier n'est pas disponible côté navigateur.");const{MultiServerFileStorageStrategy:e}=await Promise.resolve().then((function(){return ae}));return new e}if("undefined"!=typeof window&&void 0!==window.localStorage)return new MultiServerLocalStorageStrategy;const{MultiServerFileStorageStrategy:t}=await Promise.resolve().then((function(){return ae}));return new t},MultiServerTokenStorageStrategy:MultiServerTokenStorageStrategy},helper:{fromEntityJSON:g,restorePaginationFromJSON:BaseEntity.restorePaginationFromJSON},OfflineClientManager:OfflineClientManager};var se=Object.freeze({__proto__:null,bufferToReadable:async function(e){const{Readable:t}=await import("stream");return t.from(e)},createPassThrough:async function(){const{PassThrough:e}=await import("stream");return new e}});var ae=Object.freeze({__proto__:null,MultiServerFileStorageStrategy:class MultiServerFileStorageStrategy extends MultiServerTokenStorageStrategy{filePath;constructor(e="tokens.json",t=u.join(l.homedir(),".config","cocolight")){super(),this.filePath=u.join(t,e),m.existsSync(t)||m.mkdirSync(t,{recursive:!0})}_readFile(){if(!m.existsSync(this.filePath))return{};try{return JSON.parse(m.readFileSync(this.filePath,"utf8"))}catch{return{}}}_writeFile(e){m.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf8")}getAccessToken(){const e=this._requireBaseURL();return this._readFile()[e]?.accessToken??null}setAccessToken(e){const t=this._requireBaseURL(),n=this._readFile();n[t]={...n[t]||{},accessToken:e},this._writeFile(n)}getRefreshToken(){const e=this._requireBaseURL();return this._readFile()[e]?.refreshToken??null}setRefreshToken(e){const t=this._requireBaseURL(),n=this._readFile();n[t]={...n[t]||{},refreshToken:e},this._writeFile(n)}clear(){const e=this._requireBaseURL(),t=this._readFile();delete t[e],this._writeFile(t)}getServers(){return Object.keys(this._readFile())}exportAll(){return this._readFile()}}});var ce=Object.freeze({__proto__:null,FileStorageStrategy:class FileStorageStrategy extends TokenStorageStrategy{dir;filePath;constructor(e="tokens.json",t=u.join(l.homedir(),".config","cocolight")){super(),this.dir=t,this.filePath=u.join(t,e),this._ensureDirectoryExists()}_ensureDirectoryExists(){m.existsSync(this.dir)||m.mkdirSync(this.dir,{recursive:!0})}_readFile(){if(!m.existsSync(this.filePath))return{};try{return JSON.parse(m.readFileSync(this.filePath,"utf8"))}catch(e){return console.error("Error reading token file:",e),{}}}_writeFile(e){m.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf8")}getAccessToken(){return this._readFile().accessToken||null}setAccessToken(e){const t=this._readFile();t.accessToken=e,this._writeFile(t)}getRefreshToken(){return this._readFile().refreshToken||null}setRefreshToken(e){const t=this._readFile();t.refreshToken=e,this._writeFile(t)}clear(){this._writeFile({})}}});var pe=Object.freeze({__proto__:null,FileOfflineStorage:class FileOfflineStorage extends OfflineQueueStorageStrategy{dir;filePath;constructor(e="offline-queue.json",t=u.join(l.homedir(),".config","cocolight")){super(),this.dir=t,this.filePath=u.join(t,e),this._ensureDirectoryExists()}_ensureDirectoryExists(){m.existsSync(this.dir)||m.mkdirSync(this.dir,{recursive:!0})}_readFile(){if(!m.existsSync(this.filePath))return[];try{return JSON.parse(m.readFileSync(this.filePath,"utf8"))}catch(e){return console.error("Erreur lecture offline queue :",e),[]}}_writeFile(e){try{m.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf8")}catch(e){console.warn("[OfflineQueue] Erreur d'écriture:",e)}}async loadQueue(){return this._readFile()}async saveQueue(e){this._writeFile(e)}}});export{re as EVENT_TYPES,te as ORGANIZATION_TYPES,oe as POI_TYPES,ne as PROJECT_AVANCEMENTS,ie as default};
2
2
  //# sourceMappingURL=cocolight-api-client.vite.mjs.js.map