@open-commune/core 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1178,7 +1178,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1178
1178
  data: {
1179
1179
  name: string;
1180
1180
  label: string;
1181
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1181
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
1182
1182
  required: boolean;
1183
1183
  hidden: boolean;
1184
1184
  options?: string[] | undefined;
@@ -1198,7 +1198,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1198
1198
  $type: {
1199
1199
  name: string;
1200
1200
  label: string;
1201
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1201
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
1202
1202
  required: boolean;
1203
1203
  hidden: boolean;
1204
1204
  options?: string[] | undefined;
@@ -1892,13 +1892,13 @@ declare class UsersService {
1892
1892
  verifyApiToken(token: string): Promise<boolean>;
1893
1893
  revokeApiToken(id: string): Promise<void>;
1894
1894
  listApiTokens(): Promise<Pick<{
1895
- id: string;
1896
1895
  name: string;
1896
+ id: string;
1897
1897
  createdAt: string;
1898
1898
  revokedAt: string | null;
1899
1899
  tokenHash: string;
1900
1900
  lastUsedAt: string | null;
1901
- }, "id" | "name" | "createdAt" | "revokedAt" | "lastUsedAt">[]>;
1901
+ }, "name" | "id" | "createdAt" | "revokedAt" | "lastUsedAt">[]>;
1902
1902
  }
1903
1903
 
1904
1904
  /**
@@ -1920,9 +1920,9 @@ declare const organizationInitDto: z.ZodObject<{
1920
1920
  syndicate: "syndicate";
1921
1921
  other: "other";
1922
1922
  }>>;
1923
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1924
1923
  name: z.ZodString;
1925
1924
  slug: z.ZodString;
1925
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1926
1926
  address: z.ZodOptional<z.ZodNullable<z.ZodType<{
1927
1927
  street?: string | undefined;
1928
1928
  postalCode?: string | undefined;
@@ -1953,9 +1953,9 @@ declare const organizationUpdateDto: z.ZodObject<{
1953
1953
  syndicate: "syndicate";
1954
1954
  other: "other";
1955
1955
  }>>;
1956
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1957
1956
  name: z.ZodOptional<z.ZodString>;
1958
1957
  slug: z.ZodOptional<z.ZodString>;
1958
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1959
1959
  address: z.ZodOptional<z.ZodNullable<z.ZodType<{
1960
1960
  street?: string | undefined;
1961
1961
  postalCode?: string | undefined;
@@ -2042,15 +2042,6 @@ type MediaUpdateDto = z.infer<typeof mediaUpdateDto>;
2042
2042
 
2043
2043
  /** Closed allowlist. SVG is excluded on purpose: it is an XSS surface. */
2044
2044
  declare const ALLOWED_MIME: Set<string>;
2045
- /** The media shape existing clients consume: `objects` values are public URLs. */
2046
- interface LegacyMedia {
2047
- _id: string;
2048
- id: string;
2049
- originalName: string;
2050
- mime: string;
2051
- metaData?: Record<string, unknown>;
2052
- objects: Record<string, string>;
2053
- }
2054
2045
  /**
2055
2046
  * Media library. The API hands out a pre-signed PUT URL, the client uploads
2056
2047
  * DIRECTLY to storage, then `finalize` verifies the object and records the row.
@@ -2088,10 +2079,6 @@ declare class MediaService {
2088
2079
  remove(id: string): Promise<void>;
2089
2080
  /** Public GET URL of a media's original object (null if the media is unknown). */
2090
2081
  url(id: string): Promise<string | null>;
2091
- /** The media record public payloads carry, with its URLs resolved. */
2092
- toLegacyMedia(id: string): Promise<LegacyMedia | null>;
2093
- /** Walks any JSON value, replacing `_media:<id>` strings with media records. */
2094
- resolveMediaPlaceholders(node: unknown): Promise<unknown>;
2095
2082
  private objectUrls;
2096
2083
  }
2097
2084
 
@@ -2136,8 +2123,8 @@ declare class EntryRepository {
2136
2123
  }
2137
2124
 
2138
2125
  declare const definitionCreateDto: z.ZodObject<{
2139
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2140
2126
  name: z.ZodString;
2127
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2141
2128
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2142
2129
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2143
2130
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -2147,14 +2134,14 @@ declare const definitionCreateDto: z.ZodObject<{
2147
2134
  type: z.ZodEnum<{
2148
2135
  number: "number";
2149
2136
  boolean: "boolean";
2150
- date: "date";
2151
- media: "media";
2152
- json: "json";
2153
2137
  text: "text";
2154
- select: "select";
2155
2138
  "rich-text": "rich-text";
2139
+ date: "date";
2140
+ media: "media";
2156
2141
  relation: "relation";
2142
+ select: "select";
2157
2143
  steps: "steps";
2144
+ json: "json";
2158
2145
  }>;
2159
2146
  required: z.ZodDefault<z.ZodBoolean>;
2160
2147
  hidden: z.ZodDefault<z.ZodBoolean>;
@@ -2167,9 +2154,9 @@ declare const definitionCreateDto: z.ZodObject<{
2167
2154
  in: {};
2168
2155
  }>;
2169
2156
  declare const definitionUpdateDto: z.ZodObject<{
2170
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2171
2157
  name: z.ZodOptional<z.ZodString>;
2172
2158
  slug: z.ZodOptional<z.ZodString>;
2159
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2173
2160
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2174
2161
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2175
2162
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -2179,14 +2166,14 @@ declare const definitionUpdateDto: z.ZodObject<{
2179
2166
  type: z.ZodEnum<{
2180
2167
  number: "number";
2181
2168
  boolean: "boolean";
2182
- date: "date";
2183
- media: "media";
2184
- json: "json";
2185
2169
  text: "text";
2186
- select: "select";
2187
2170
  "rich-text": "rich-text";
2171
+ date: "date";
2172
+ media: "media";
2188
2173
  relation: "relation";
2174
+ select: "select";
2189
2175
  steps: "steps";
2176
+ json: "json";
2190
2177
  }>;
2191
2178
  required: z.ZodDefault<z.ZodBoolean>;
2192
2179
  hidden: z.ZodDefault<z.ZodBoolean>;
@@ -2263,21 +2250,6 @@ declare class CollectionsService {
2263
2250
  /** PARTIAL update: `data` is merged field by field with what already exists. */
2264
2251
  updateEntry(id: string, input: EntryUpdateDto, actorId?: string): Promise<Entry>;
2265
2252
  removeEntry(id: string): Promise<void>;
2266
- /**
2267
- * Hidden fields excluded; rich text resolved then STRINGIFIED; media fields
2268
- * turned into arrays of media records.
2269
- */
2270
- private resolveEntryData;
2271
- /** Image and file nodes get their `mediaRecord` and a resolved `src`. */
2272
- private resolveRichTextMedia;
2273
- /** Events with no scheduled period are never published. */
2274
- private hasEmptySchedules;
2275
- /**
2276
- * ONE flat map of every published entry across all collections, keyed by id.
2277
- */
2278
- legacyRecordsPayload(): Promise<Record<string, Record<string, unknown>>>;
2279
- /** Public slugs of every published entry (`/collection/entry`), for the deployment payload. */
2280
- publishedSlugs(): Promise<string[]>;
2281
2253
  private mapSlugConflict;
2282
2254
  /** Incremental suffix -1/-2… until the slug is unique within the collection. */
2283
2255
  private uniqueEntrySlug;
@@ -2375,14 +2347,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2375
2347
  input: void;
2376
2348
  output: {
2377
2349
  type: "commune" | "intercommunality" | "syndicate" | "other";
2378
- description: string | null;
2379
- id: number;
2380
2350
  name: string;
2381
- updatedBy: string | null;
2382
- legacyExtra: Record<string, unknown> | null;
2383
- createdAt: string;
2384
- updatedAt: string;
2351
+ id: number;
2385
2352
  slug: string;
2353
+ description: string | null;
2386
2354
  address: {
2387
2355
  street?: string | undefined;
2388
2356
  postalCode?: string | undefined;
@@ -2390,6 +2358,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2390
2358
  } | null;
2391
2359
  deployment: Record<string, unknown> | null;
2392
2360
  settings: Record<string, unknown> | null;
2361
+ updatedBy: string | null;
2362
+ legacyExtra: Record<string, unknown> | null;
2363
+ createdAt: string;
2364
+ updatedAt: string;
2393
2365
  } | null;
2394
2366
  meta: object;
2395
2367
  }>;
@@ -2409,14 +2381,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2409
2381
  };
2410
2382
  output: {
2411
2383
  type: "commune" | "intercommunality" | "syndicate" | "other";
2412
- description: string | null;
2413
- id: number;
2414
2384
  name: string;
2415
- updatedBy: string | null;
2416
- legacyExtra: Record<string, unknown> | null;
2417
- createdAt: string;
2418
- updatedAt: string;
2385
+ id: number;
2419
2386
  slug: string;
2387
+ description: string | null;
2420
2388
  address: {
2421
2389
  street?: string | undefined;
2422
2390
  postalCode?: string | undefined;
@@ -2424,15 +2392,19 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2424
2392
  } | null;
2425
2393
  deployment: Record<string, unknown> | null;
2426
2394
  settings: Record<string, unknown> | null;
2395
+ updatedBy: string | null;
2396
+ legacyExtra: Record<string, unknown> | null;
2397
+ createdAt: string;
2398
+ updatedAt: string;
2427
2399
  };
2428
2400
  meta: object;
2429
2401
  }>;
2430
2402
  update: _trpc_server.TRPCMutationProcedure<{
2431
2403
  input: {
2432
2404
  type?: "commune" | "intercommunality" | "syndicate" | "other" | undefined;
2433
- description?: string | null | undefined;
2434
2405
  name?: string | undefined;
2435
2406
  slug?: string | undefined;
2407
+ description?: string | null | undefined;
2436
2408
  address?: {
2437
2409
  street?: string | undefined;
2438
2410
  postalCode?: string | undefined;
@@ -2443,14 +2415,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2443
2415
  };
2444
2416
  output: {
2445
2417
  type: "commune" | "intercommunality" | "syndicate" | "other";
2446
- description: string | null;
2447
- id: number;
2448
2418
  name: string;
2449
- updatedBy: string | null;
2450
- legacyExtra: Record<string, unknown> | null;
2451
- createdAt: string;
2452
- updatedAt: string;
2419
+ id: number;
2453
2420
  slug: string;
2421
+ description: string | null;
2454
2422
  address: {
2455
2423
  street?: string | undefined;
2456
2424
  postalCode?: string | undefined;
@@ -2458,6 +2426,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2458
2426
  } | null;
2459
2427
  deployment: Record<string, unknown> | null;
2460
2428
  settings: Record<string, unknown> | null;
2429
+ updatedBy: string | null;
2430
+ legacyExtra: Record<string, unknown> | null;
2431
+ createdAt: string;
2432
+ updatedAt: string;
2461
2433
  };
2462
2434
  meta: object;
2463
2435
  }>;
@@ -2820,13 +2792,13 @@ declare const apiTokensRouter: _trpc_server.TRPCBuiltRouter<{
2820
2792
  list: _trpc_server.TRPCQueryProcedure<{
2821
2793
  input: void;
2822
2794
  output: Pick<{
2823
- id: string;
2824
2795
  name: string;
2796
+ id: string;
2825
2797
  createdAt: string;
2826
2798
  revokedAt: string | null;
2827
2799
  tokenHash: string;
2828
2800
  lastUsedAt: string | null;
2829
- }, "id" | "name" | "createdAt" | "revokedAt" | "lastUsedAt">[];
2801
+ }, "name" | "id" | "createdAt" | "revokedAt" | "lastUsedAt">[];
2830
2802
  meta: object;
2831
2803
  }>;
2832
2804
  /** The plaintext token is returned ONCE — only its hash is stored. */
@@ -2972,18 +2944,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2972
2944
  };
2973
2945
  output: {
2974
2946
  filename: string;
2975
- mime: string;
2976
- metaData: Record<string, unknown> | null;
2977
- alt: string | null;
2978
2947
  id: string;
2979
- size: number;
2980
- caption: string | null;
2981
- objects: Record<string, unknown>;
2982
- createdBy: string | null;
2983
2948
  updatedBy: string | null;
2984
2949
  legacyExtra: Record<string, unknown> | null;
2985
2950
  createdAt: string;
2986
2951
  updatedAt: string;
2952
+ mime: string;
2953
+ size: number;
2954
+ alt: string | null;
2955
+ caption: string | null;
2956
+ objects: Record<string, unknown>;
2957
+ metaData: Record<string, unknown> | null;
2958
+ createdBy: string | null;
2987
2959
  };
2988
2960
  meta: object;
2989
2961
  }>;
@@ -2991,18 +2963,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2991
2963
  input: void;
2992
2964
  output: ({
2993
2965
  filename: string;
2994
- mime: string;
2995
- metaData: Record<string, unknown> | null;
2996
- alt: string | null;
2997
2966
  id: string;
2998
- size: number;
2999
- caption: string | null;
3000
- objects: Record<string, unknown>;
3001
- createdBy: string | null;
3002
2967
  updatedBy: string | null;
3003
2968
  legacyExtra: Record<string, unknown> | null;
3004
2969
  createdAt: string;
3005
2970
  updatedAt: string;
2971
+ mime: string;
2972
+ size: number;
2973
+ alt: string | null;
2974
+ caption: string | null;
2975
+ objects: Record<string, unknown>;
2976
+ metaData: Record<string, unknown> | null;
2977
+ createdBy: string | null;
3006
2978
  } & {
3007
2979
  objects: Record<string, string>;
3008
2980
  })[];
@@ -3014,18 +2986,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3014
2986
  };
3015
2987
  output: {
3016
2988
  filename: string;
3017
- mime: string;
3018
- metaData: Record<string, unknown> | null;
3019
- alt: string | null;
3020
2989
  id: string;
3021
- size: number;
3022
- caption: string | null;
3023
- objects: Record<string, unknown>;
3024
- createdBy: string | null;
3025
2990
  updatedBy: string | null;
3026
2991
  legacyExtra: Record<string, unknown> | null;
3027
2992
  createdAt: string;
3028
2993
  updatedAt: string;
2994
+ mime: string;
2995
+ size: number;
2996
+ alt: string | null;
2997
+ caption: string | null;
2998
+ objects: Record<string, unknown>;
2999
+ metaData: Record<string, unknown> | null;
3000
+ createdBy: string | null;
3029
3001
  } & {
3030
3002
  objects: Record<string, string>;
3031
3003
  };
@@ -3042,18 +3014,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3042
3014
  };
3043
3015
  output: {
3044
3016
  filename: string;
3045
- mime: string;
3046
- metaData: Record<string, unknown> | null;
3047
- alt: string | null;
3048
3017
  id: string;
3049
- size: number;
3050
- caption: string | null;
3051
- objects: Record<string, unknown>;
3052
- createdBy: string | null;
3053
3018
  updatedBy: string | null;
3054
3019
  legacyExtra: Record<string, unknown> | null;
3055
3020
  createdAt: string;
3056
3021
  updatedAt: string;
3022
+ mime: string;
3023
+ size: number;
3024
+ alt: string | null;
3025
+ caption: string | null;
3026
+ objects: Record<string, unknown>;
3027
+ metaData: Record<string, unknown> | null;
3028
+ createdBy: string | null;
3057
3029
  };
3058
3030
  meta: object;
3059
3031
  }>;
@@ -3136,19 +3108,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3136
3108
  list: _trpc_server.TRPCQueryProcedure<{
3137
3109
  input: void;
3138
3110
  output: {
3139
- description: string | null;
3140
- id: string;
3141
3111
  name: string;
3142
- createdBy: string | null;
3112
+ id: string;
3113
+ slug: string;
3114
+ description: string | null;
3143
3115
  updatedBy: string | null;
3144
3116
  legacyExtra: Record<string, unknown> | null;
3145
3117
  createdAt: string;
3146
3118
  updatedAt: string;
3147
- slug: string;
3119
+ createdBy: string | null;
3148
3120
  fields: {
3149
3121
  name: string;
3150
3122
  label: string;
3151
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3123
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3152
3124
  required: boolean;
3153
3125
  hidden: boolean;
3154
3126
  options?: string[] | undefined;
@@ -3165,19 +3137,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3165
3137
  idOrSlug: string;
3166
3138
  };
3167
3139
  output: {
3168
- description: string | null;
3169
- id: string;
3170
3140
  name: string;
3171
- createdBy: string | null;
3141
+ id: string;
3142
+ slug: string;
3143
+ description: string | null;
3172
3144
  updatedBy: string | null;
3173
3145
  legacyExtra: Record<string, unknown> | null;
3174
3146
  createdAt: string;
3175
3147
  updatedAt: string;
3176
- slug: string;
3148
+ createdBy: string | null;
3177
3149
  fields: {
3178
3150
  name: string;
3179
3151
  label: string;
3180
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3152
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3181
3153
  required: boolean;
3182
3154
  hidden: boolean;
3183
3155
  options?: string[] | undefined;
@@ -3195,7 +3167,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3195
3167
  fields: {
3196
3168
  name: string;
3197
3169
  label: string;
3198
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3170
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3199
3171
  required?: boolean | undefined;
3200
3172
  hidden?: boolean | undefined;
3201
3173
  options?: string[] | undefined;
@@ -3208,19 +3180,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3208
3180
  slug?: string | undefined;
3209
3181
  };
3210
3182
  output: {
3211
- description: string | null;
3212
- id: string;
3213
3183
  name: string;
3214
- createdBy: string | null;
3184
+ id: string;
3185
+ slug: string;
3186
+ description: string | null;
3215
3187
  updatedBy: string | null;
3216
3188
  legacyExtra: Record<string, unknown> | null;
3217
3189
  createdAt: string;
3218
3190
  updatedAt: string;
3219
- slug: string;
3191
+ createdBy: string | null;
3220
3192
  fields: {
3221
3193
  name: string;
3222
3194
  label: string;
3223
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3195
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3224
3196
  required: boolean;
3225
3197
  hidden: boolean;
3226
3198
  options?: string[] | undefined;
@@ -3236,16 +3208,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3236
3208
  input: {
3237
3209
  id: string;
3238
3210
  data: {
3239
- description?: string | null | undefined;
3240
3211
  name?: string | undefined;
3241
3212
  slug?: string | undefined;
3213
+ description?: string | null | undefined;
3242
3214
  editor?: Record<string, unknown> | null | undefined;
3243
3215
  display?: Record<string, unknown> | null | undefined;
3244
3216
  headings?: Record<string, unknown> | null | undefined;
3245
3217
  fields?: {
3246
3218
  name: string;
3247
3219
  label: string;
3248
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3220
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3249
3221
  required?: boolean | undefined;
3250
3222
  hidden?: boolean | undefined;
3251
3223
  options?: string[] | undefined;
@@ -3254,19 +3226,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3254
3226
  };
3255
3227
  };
3256
3228
  output: {
3257
- description: string | null;
3258
- id: string;
3259
3229
  name: string;
3260
- createdBy: string | null;
3230
+ id: string;
3231
+ slug: string;
3232
+ description: string | null;
3261
3233
  updatedBy: string | null;
3262
3234
  legacyExtra: Record<string, unknown> | null;
3263
3235
  createdAt: string;
3264
3236
  updatedAt: string;
3265
- slug: string;
3237
+ createdBy: string | null;
3266
3238
  fields: {
3267
3239
  name: string;
3268
3240
  label: string;
3269
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3241
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3270
3242
  required: boolean;
3271
3243
  hidden: boolean;
3272
3244
  options?: string[] | undefined;
@@ -3310,12 +3282,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3310
3282
  output: {
3311
3283
  id: string;
3312
3284
  data: Record<string, unknown>;
3313
- createdBy: string | null;
3285
+ slug: string;
3314
3286
  updatedBy: string | null;
3315
3287
  legacyExtra: Record<string, unknown> | null;
3316
3288
  createdAt: string;
3317
3289
  updatedAt: string;
3318
- slug: string;
3290
+ createdBy: string | null;
3319
3291
  collectionId: string;
3320
3292
  title: string;
3321
3293
  related: string[] | null;
@@ -3333,12 +3305,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3333
3305
  output: {
3334
3306
  id: string;
3335
3307
  data: Record<string, unknown>;
3336
- createdBy: string | null;
3308
+ slug: string;
3337
3309
  updatedBy: string | null;
3338
3310
  legacyExtra: Record<string, unknown> | null;
3339
3311
  createdAt: string;
3340
3312
  updatedAt: string;
3341
- slug: string;
3313
+ createdBy: string | null;
3342
3314
  collectionId: string;
3343
3315
  title: string;
3344
3316
  related: string[] | null;
@@ -3361,12 +3333,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3361
3333
  output: {
3362
3334
  id: string;
3363
3335
  data: Record<string, unknown>;
3364
- createdBy: string | null;
3336
+ slug: string;
3365
3337
  updatedBy: string | null;
3366
3338
  legacyExtra: Record<string, unknown> | null;
3367
3339
  createdAt: string;
3368
3340
  updatedAt: string;
3369
- slug: string;
3341
+ createdBy: string | null;
3370
3342
  collectionId: string;
3371
3343
  title: string;
3372
3344
  related: string[] | null;
@@ -3390,12 +3362,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3390
3362
  output: {
3391
3363
  id: string;
3392
3364
  data: Record<string, unknown>;
3393
- createdBy: string | null;
3365
+ slug: string;
3394
3366
  updatedBy: string | null;
3395
3367
  legacyExtra: Record<string, unknown> | null;
3396
3368
  createdAt: string;
3397
3369
  updatedAt: string;
3398
- slug: string;
3370
+ createdBy: string | null;
3399
3371
  collectionId: string;
3400
3372
  title: string;
3401
3373
  related: string[] | null;
package/dist/index.d.ts CHANGED
@@ -1178,7 +1178,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1178
1178
  data: {
1179
1179
  name: string;
1180
1180
  label: string;
1181
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1181
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
1182
1182
  required: boolean;
1183
1183
  hidden: boolean;
1184
1184
  options?: string[] | undefined;
@@ -1198,7 +1198,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1198
1198
  $type: {
1199
1199
  name: string;
1200
1200
  label: string;
1201
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1201
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
1202
1202
  required: boolean;
1203
1203
  hidden: boolean;
1204
1204
  options?: string[] | undefined;
@@ -1892,13 +1892,13 @@ declare class UsersService {
1892
1892
  verifyApiToken(token: string): Promise<boolean>;
1893
1893
  revokeApiToken(id: string): Promise<void>;
1894
1894
  listApiTokens(): Promise<Pick<{
1895
- id: string;
1896
1895
  name: string;
1896
+ id: string;
1897
1897
  createdAt: string;
1898
1898
  revokedAt: string | null;
1899
1899
  tokenHash: string;
1900
1900
  lastUsedAt: string | null;
1901
- }, "id" | "name" | "createdAt" | "revokedAt" | "lastUsedAt">[]>;
1901
+ }, "name" | "id" | "createdAt" | "revokedAt" | "lastUsedAt">[]>;
1902
1902
  }
1903
1903
 
1904
1904
  /**
@@ -1920,9 +1920,9 @@ declare const organizationInitDto: z.ZodObject<{
1920
1920
  syndicate: "syndicate";
1921
1921
  other: "other";
1922
1922
  }>>;
1923
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1924
1923
  name: z.ZodString;
1925
1924
  slug: z.ZodString;
1925
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1926
1926
  address: z.ZodOptional<z.ZodNullable<z.ZodType<{
1927
1927
  street?: string | undefined;
1928
1928
  postalCode?: string | undefined;
@@ -1953,9 +1953,9 @@ declare const organizationUpdateDto: z.ZodObject<{
1953
1953
  syndicate: "syndicate";
1954
1954
  other: "other";
1955
1955
  }>>;
1956
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1957
1956
  name: z.ZodOptional<z.ZodString>;
1958
1957
  slug: z.ZodOptional<z.ZodString>;
1958
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
1959
1959
  address: z.ZodOptional<z.ZodNullable<z.ZodType<{
1960
1960
  street?: string | undefined;
1961
1961
  postalCode?: string | undefined;
@@ -2042,15 +2042,6 @@ type MediaUpdateDto = z.infer<typeof mediaUpdateDto>;
2042
2042
 
2043
2043
  /** Closed allowlist. SVG is excluded on purpose: it is an XSS surface. */
2044
2044
  declare const ALLOWED_MIME: Set<string>;
2045
- /** The media shape existing clients consume: `objects` values are public URLs. */
2046
- interface LegacyMedia {
2047
- _id: string;
2048
- id: string;
2049
- originalName: string;
2050
- mime: string;
2051
- metaData?: Record<string, unknown>;
2052
- objects: Record<string, string>;
2053
- }
2054
2045
  /**
2055
2046
  * Media library. The API hands out a pre-signed PUT URL, the client uploads
2056
2047
  * DIRECTLY to storage, then `finalize` verifies the object and records the row.
@@ -2088,10 +2079,6 @@ declare class MediaService {
2088
2079
  remove(id: string): Promise<void>;
2089
2080
  /** Public GET URL of a media's original object (null if the media is unknown). */
2090
2081
  url(id: string): Promise<string | null>;
2091
- /** The media record public payloads carry, with its URLs resolved. */
2092
- toLegacyMedia(id: string): Promise<LegacyMedia | null>;
2093
- /** Walks any JSON value, replacing `_media:<id>` strings with media records. */
2094
- resolveMediaPlaceholders(node: unknown): Promise<unknown>;
2095
2082
  private objectUrls;
2096
2083
  }
2097
2084
 
@@ -2136,8 +2123,8 @@ declare class EntryRepository {
2136
2123
  }
2137
2124
 
2138
2125
  declare const definitionCreateDto: z.ZodObject<{
2139
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2140
2126
  name: z.ZodString;
2127
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2141
2128
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2142
2129
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2143
2130
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -2147,14 +2134,14 @@ declare const definitionCreateDto: z.ZodObject<{
2147
2134
  type: z.ZodEnum<{
2148
2135
  number: "number";
2149
2136
  boolean: "boolean";
2150
- date: "date";
2151
- media: "media";
2152
- json: "json";
2153
2137
  text: "text";
2154
- select: "select";
2155
2138
  "rich-text": "rich-text";
2139
+ date: "date";
2140
+ media: "media";
2156
2141
  relation: "relation";
2142
+ select: "select";
2157
2143
  steps: "steps";
2144
+ json: "json";
2158
2145
  }>;
2159
2146
  required: z.ZodDefault<z.ZodBoolean>;
2160
2147
  hidden: z.ZodDefault<z.ZodBoolean>;
@@ -2167,9 +2154,9 @@ declare const definitionCreateDto: z.ZodObject<{
2167
2154
  in: {};
2168
2155
  }>;
2169
2156
  declare const definitionUpdateDto: z.ZodObject<{
2170
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2171
2157
  name: z.ZodOptional<z.ZodString>;
2172
2158
  slug: z.ZodOptional<z.ZodString>;
2159
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2173
2160
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2174
2161
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2175
2162
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -2179,14 +2166,14 @@ declare const definitionUpdateDto: z.ZodObject<{
2179
2166
  type: z.ZodEnum<{
2180
2167
  number: "number";
2181
2168
  boolean: "boolean";
2182
- date: "date";
2183
- media: "media";
2184
- json: "json";
2185
2169
  text: "text";
2186
- select: "select";
2187
2170
  "rich-text": "rich-text";
2171
+ date: "date";
2172
+ media: "media";
2188
2173
  relation: "relation";
2174
+ select: "select";
2189
2175
  steps: "steps";
2176
+ json: "json";
2190
2177
  }>;
2191
2178
  required: z.ZodDefault<z.ZodBoolean>;
2192
2179
  hidden: z.ZodDefault<z.ZodBoolean>;
@@ -2263,21 +2250,6 @@ declare class CollectionsService {
2263
2250
  /** PARTIAL update: `data` is merged field by field with what already exists. */
2264
2251
  updateEntry(id: string, input: EntryUpdateDto, actorId?: string): Promise<Entry>;
2265
2252
  removeEntry(id: string): Promise<void>;
2266
- /**
2267
- * Hidden fields excluded; rich text resolved then STRINGIFIED; media fields
2268
- * turned into arrays of media records.
2269
- */
2270
- private resolveEntryData;
2271
- /** Image and file nodes get their `mediaRecord` and a resolved `src`. */
2272
- private resolveRichTextMedia;
2273
- /** Events with no scheduled period are never published. */
2274
- private hasEmptySchedules;
2275
- /**
2276
- * ONE flat map of every published entry across all collections, keyed by id.
2277
- */
2278
- legacyRecordsPayload(): Promise<Record<string, Record<string, unknown>>>;
2279
- /** Public slugs of every published entry (`/collection/entry`), for the deployment payload. */
2280
- publishedSlugs(): Promise<string[]>;
2281
2253
  private mapSlugConflict;
2282
2254
  /** Incremental suffix -1/-2… until the slug is unique within the collection. */
2283
2255
  private uniqueEntrySlug;
@@ -2375,14 +2347,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2375
2347
  input: void;
2376
2348
  output: {
2377
2349
  type: "commune" | "intercommunality" | "syndicate" | "other";
2378
- description: string | null;
2379
- id: number;
2380
2350
  name: string;
2381
- updatedBy: string | null;
2382
- legacyExtra: Record<string, unknown> | null;
2383
- createdAt: string;
2384
- updatedAt: string;
2351
+ id: number;
2385
2352
  slug: string;
2353
+ description: string | null;
2386
2354
  address: {
2387
2355
  street?: string | undefined;
2388
2356
  postalCode?: string | undefined;
@@ -2390,6 +2358,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2390
2358
  } | null;
2391
2359
  deployment: Record<string, unknown> | null;
2392
2360
  settings: Record<string, unknown> | null;
2361
+ updatedBy: string | null;
2362
+ legacyExtra: Record<string, unknown> | null;
2363
+ createdAt: string;
2364
+ updatedAt: string;
2393
2365
  } | null;
2394
2366
  meta: object;
2395
2367
  }>;
@@ -2409,14 +2381,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2409
2381
  };
2410
2382
  output: {
2411
2383
  type: "commune" | "intercommunality" | "syndicate" | "other";
2412
- description: string | null;
2413
- id: number;
2414
2384
  name: string;
2415
- updatedBy: string | null;
2416
- legacyExtra: Record<string, unknown> | null;
2417
- createdAt: string;
2418
- updatedAt: string;
2385
+ id: number;
2419
2386
  slug: string;
2387
+ description: string | null;
2420
2388
  address: {
2421
2389
  street?: string | undefined;
2422
2390
  postalCode?: string | undefined;
@@ -2424,15 +2392,19 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2424
2392
  } | null;
2425
2393
  deployment: Record<string, unknown> | null;
2426
2394
  settings: Record<string, unknown> | null;
2395
+ updatedBy: string | null;
2396
+ legacyExtra: Record<string, unknown> | null;
2397
+ createdAt: string;
2398
+ updatedAt: string;
2427
2399
  };
2428
2400
  meta: object;
2429
2401
  }>;
2430
2402
  update: _trpc_server.TRPCMutationProcedure<{
2431
2403
  input: {
2432
2404
  type?: "commune" | "intercommunality" | "syndicate" | "other" | undefined;
2433
- description?: string | null | undefined;
2434
2405
  name?: string | undefined;
2435
2406
  slug?: string | undefined;
2407
+ description?: string | null | undefined;
2436
2408
  address?: {
2437
2409
  street?: string | undefined;
2438
2410
  postalCode?: string | undefined;
@@ -2443,14 +2415,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2443
2415
  };
2444
2416
  output: {
2445
2417
  type: "commune" | "intercommunality" | "syndicate" | "other";
2446
- description: string | null;
2447
- id: number;
2448
2418
  name: string;
2449
- updatedBy: string | null;
2450
- legacyExtra: Record<string, unknown> | null;
2451
- createdAt: string;
2452
- updatedAt: string;
2419
+ id: number;
2453
2420
  slug: string;
2421
+ description: string | null;
2454
2422
  address: {
2455
2423
  street?: string | undefined;
2456
2424
  postalCode?: string | undefined;
@@ -2458,6 +2426,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2458
2426
  } | null;
2459
2427
  deployment: Record<string, unknown> | null;
2460
2428
  settings: Record<string, unknown> | null;
2429
+ updatedBy: string | null;
2430
+ legacyExtra: Record<string, unknown> | null;
2431
+ createdAt: string;
2432
+ updatedAt: string;
2461
2433
  };
2462
2434
  meta: object;
2463
2435
  }>;
@@ -2820,13 +2792,13 @@ declare const apiTokensRouter: _trpc_server.TRPCBuiltRouter<{
2820
2792
  list: _trpc_server.TRPCQueryProcedure<{
2821
2793
  input: void;
2822
2794
  output: Pick<{
2823
- id: string;
2824
2795
  name: string;
2796
+ id: string;
2825
2797
  createdAt: string;
2826
2798
  revokedAt: string | null;
2827
2799
  tokenHash: string;
2828
2800
  lastUsedAt: string | null;
2829
- }, "id" | "name" | "createdAt" | "revokedAt" | "lastUsedAt">[];
2801
+ }, "name" | "id" | "createdAt" | "revokedAt" | "lastUsedAt">[];
2830
2802
  meta: object;
2831
2803
  }>;
2832
2804
  /** The plaintext token is returned ONCE — only its hash is stored. */
@@ -2972,18 +2944,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2972
2944
  };
2973
2945
  output: {
2974
2946
  filename: string;
2975
- mime: string;
2976
- metaData: Record<string, unknown> | null;
2977
- alt: string | null;
2978
2947
  id: string;
2979
- size: number;
2980
- caption: string | null;
2981
- objects: Record<string, unknown>;
2982
- createdBy: string | null;
2983
2948
  updatedBy: string | null;
2984
2949
  legacyExtra: Record<string, unknown> | null;
2985
2950
  createdAt: string;
2986
2951
  updatedAt: string;
2952
+ mime: string;
2953
+ size: number;
2954
+ alt: string | null;
2955
+ caption: string | null;
2956
+ objects: Record<string, unknown>;
2957
+ metaData: Record<string, unknown> | null;
2958
+ createdBy: string | null;
2987
2959
  };
2988
2960
  meta: object;
2989
2961
  }>;
@@ -2991,18 +2963,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2991
2963
  input: void;
2992
2964
  output: ({
2993
2965
  filename: string;
2994
- mime: string;
2995
- metaData: Record<string, unknown> | null;
2996
- alt: string | null;
2997
2966
  id: string;
2998
- size: number;
2999
- caption: string | null;
3000
- objects: Record<string, unknown>;
3001
- createdBy: string | null;
3002
2967
  updatedBy: string | null;
3003
2968
  legacyExtra: Record<string, unknown> | null;
3004
2969
  createdAt: string;
3005
2970
  updatedAt: string;
2971
+ mime: string;
2972
+ size: number;
2973
+ alt: string | null;
2974
+ caption: string | null;
2975
+ objects: Record<string, unknown>;
2976
+ metaData: Record<string, unknown> | null;
2977
+ createdBy: string | null;
3006
2978
  } & {
3007
2979
  objects: Record<string, string>;
3008
2980
  })[];
@@ -3014,18 +2986,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3014
2986
  };
3015
2987
  output: {
3016
2988
  filename: string;
3017
- mime: string;
3018
- metaData: Record<string, unknown> | null;
3019
- alt: string | null;
3020
2989
  id: string;
3021
- size: number;
3022
- caption: string | null;
3023
- objects: Record<string, unknown>;
3024
- createdBy: string | null;
3025
2990
  updatedBy: string | null;
3026
2991
  legacyExtra: Record<string, unknown> | null;
3027
2992
  createdAt: string;
3028
2993
  updatedAt: string;
2994
+ mime: string;
2995
+ size: number;
2996
+ alt: string | null;
2997
+ caption: string | null;
2998
+ objects: Record<string, unknown>;
2999
+ metaData: Record<string, unknown> | null;
3000
+ createdBy: string | null;
3029
3001
  } & {
3030
3002
  objects: Record<string, string>;
3031
3003
  };
@@ -3042,18 +3014,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3042
3014
  };
3043
3015
  output: {
3044
3016
  filename: string;
3045
- mime: string;
3046
- metaData: Record<string, unknown> | null;
3047
- alt: string | null;
3048
3017
  id: string;
3049
- size: number;
3050
- caption: string | null;
3051
- objects: Record<string, unknown>;
3052
- createdBy: string | null;
3053
3018
  updatedBy: string | null;
3054
3019
  legacyExtra: Record<string, unknown> | null;
3055
3020
  createdAt: string;
3056
3021
  updatedAt: string;
3022
+ mime: string;
3023
+ size: number;
3024
+ alt: string | null;
3025
+ caption: string | null;
3026
+ objects: Record<string, unknown>;
3027
+ metaData: Record<string, unknown> | null;
3028
+ createdBy: string | null;
3057
3029
  };
3058
3030
  meta: object;
3059
3031
  }>;
@@ -3136,19 +3108,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3136
3108
  list: _trpc_server.TRPCQueryProcedure<{
3137
3109
  input: void;
3138
3110
  output: {
3139
- description: string | null;
3140
- id: string;
3141
3111
  name: string;
3142
- createdBy: string | null;
3112
+ id: string;
3113
+ slug: string;
3114
+ description: string | null;
3143
3115
  updatedBy: string | null;
3144
3116
  legacyExtra: Record<string, unknown> | null;
3145
3117
  createdAt: string;
3146
3118
  updatedAt: string;
3147
- slug: string;
3119
+ createdBy: string | null;
3148
3120
  fields: {
3149
3121
  name: string;
3150
3122
  label: string;
3151
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3123
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3152
3124
  required: boolean;
3153
3125
  hidden: boolean;
3154
3126
  options?: string[] | undefined;
@@ -3165,19 +3137,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3165
3137
  idOrSlug: string;
3166
3138
  };
3167
3139
  output: {
3168
- description: string | null;
3169
- id: string;
3170
3140
  name: string;
3171
- createdBy: string | null;
3141
+ id: string;
3142
+ slug: string;
3143
+ description: string | null;
3172
3144
  updatedBy: string | null;
3173
3145
  legacyExtra: Record<string, unknown> | null;
3174
3146
  createdAt: string;
3175
3147
  updatedAt: string;
3176
- slug: string;
3148
+ createdBy: string | null;
3177
3149
  fields: {
3178
3150
  name: string;
3179
3151
  label: string;
3180
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3152
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3181
3153
  required: boolean;
3182
3154
  hidden: boolean;
3183
3155
  options?: string[] | undefined;
@@ -3195,7 +3167,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3195
3167
  fields: {
3196
3168
  name: string;
3197
3169
  label: string;
3198
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3170
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3199
3171
  required?: boolean | undefined;
3200
3172
  hidden?: boolean | undefined;
3201
3173
  options?: string[] | undefined;
@@ -3208,19 +3180,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3208
3180
  slug?: string | undefined;
3209
3181
  };
3210
3182
  output: {
3211
- description: string | null;
3212
- id: string;
3213
3183
  name: string;
3214
- createdBy: string | null;
3184
+ id: string;
3185
+ slug: string;
3186
+ description: string | null;
3215
3187
  updatedBy: string | null;
3216
3188
  legacyExtra: Record<string, unknown> | null;
3217
3189
  createdAt: string;
3218
3190
  updatedAt: string;
3219
- slug: string;
3191
+ createdBy: string | null;
3220
3192
  fields: {
3221
3193
  name: string;
3222
3194
  label: string;
3223
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3195
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3224
3196
  required: boolean;
3225
3197
  hidden: boolean;
3226
3198
  options?: string[] | undefined;
@@ -3236,16 +3208,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3236
3208
  input: {
3237
3209
  id: string;
3238
3210
  data: {
3239
- description?: string | null | undefined;
3240
3211
  name?: string | undefined;
3241
3212
  slug?: string | undefined;
3213
+ description?: string | null | undefined;
3242
3214
  editor?: Record<string, unknown> | null | undefined;
3243
3215
  display?: Record<string, unknown> | null | undefined;
3244
3216
  headings?: Record<string, unknown> | null | undefined;
3245
3217
  fields?: {
3246
3218
  name: string;
3247
3219
  label: string;
3248
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3220
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3249
3221
  required?: boolean | undefined;
3250
3222
  hidden?: boolean | undefined;
3251
3223
  options?: string[] | undefined;
@@ -3254,19 +3226,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3254
3226
  };
3255
3227
  };
3256
3228
  output: {
3257
- description: string | null;
3258
- id: string;
3259
3229
  name: string;
3260
- createdBy: string | null;
3230
+ id: string;
3231
+ slug: string;
3232
+ description: string | null;
3261
3233
  updatedBy: string | null;
3262
3234
  legacyExtra: Record<string, unknown> | null;
3263
3235
  createdAt: string;
3264
3236
  updatedAt: string;
3265
- slug: string;
3237
+ createdBy: string | null;
3266
3238
  fields: {
3267
3239
  name: string;
3268
3240
  label: string;
3269
- type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
3241
+ type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3270
3242
  required: boolean;
3271
3243
  hidden: boolean;
3272
3244
  options?: string[] | undefined;
@@ -3310,12 +3282,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3310
3282
  output: {
3311
3283
  id: string;
3312
3284
  data: Record<string, unknown>;
3313
- createdBy: string | null;
3285
+ slug: string;
3314
3286
  updatedBy: string | null;
3315
3287
  legacyExtra: Record<string, unknown> | null;
3316
3288
  createdAt: string;
3317
3289
  updatedAt: string;
3318
- slug: string;
3290
+ createdBy: string | null;
3319
3291
  collectionId: string;
3320
3292
  title: string;
3321
3293
  related: string[] | null;
@@ -3333,12 +3305,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3333
3305
  output: {
3334
3306
  id: string;
3335
3307
  data: Record<string, unknown>;
3336
- createdBy: string | null;
3308
+ slug: string;
3337
3309
  updatedBy: string | null;
3338
3310
  legacyExtra: Record<string, unknown> | null;
3339
3311
  createdAt: string;
3340
3312
  updatedAt: string;
3341
- slug: string;
3313
+ createdBy: string | null;
3342
3314
  collectionId: string;
3343
3315
  title: string;
3344
3316
  related: string[] | null;
@@ -3361,12 +3333,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3361
3333
  output: {
3362
3334
  id: string;
3363
3335
  data: Record<string, unknown>;
3364
- createdBy: string | null;
3336
+ slug: string;
3365
3337
  updatedBy: string | null;
3366
3338
  legacyExtra: Record<string, unknown> | null;
3367
3339
  createdAt: string;
3368
3340
  updatedAt: string;
3369
- slug: string;
3341
+ createdBy: string | null;
3370
3342
  collectionId: string;
3371
3343
  title: string;
3372
3344
  related: string[] | null;
@@ -3390,12 +3362,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3390
3362
  output: {
3391
3363
  id: string;
3392
3364
  data: Record<string, unknown>;
3393
- createdBy: string | null;
3365
+ slug: string;
3394
3366
  updatedBy: string | null;
3395
3367
  legacyExtra: Record<string, unknown> | null;
3396
3368
  createdAt: string;
3397
3369
  updatedAt: string;
3398
- slug: string;
3370
+ createdBy: string | null;
3399
3371
  collectionId: string;
3400
3372
  title: string;
3401
3373
  related: string[] | null;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{homedir as St}from"node:os";import{join as z}from"node:path";import{z as r}from"zod";import{Database as Ut}from"bun:sqlite";import{mkdirSync as Ot,existsSync as Nt}from"node:fs";import{drizzle as It}from"drizzle-orm/bun-sqlite";import{migrate as Dt}from"drizzle-orm/bun-sqlite/migrator";import{sqliteTable as I,text as o,integer as ue,uniqueIndex as Mt}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as ee,FIELD_TYPES as pe}from"./domains/collections/constants.mjs";import{fieldDefinitionSchema as L,buildDataSchema as me}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS}from"./domains/collections/utils.mjs";import{sql as K,eq as d,and as M,isNull as q,gt as te,desc as R,or as ye,lt as he,isNotNull as fe}from"drizzle-orm";import{S3Client as kt,PutObjectCommand as ge,HeadObjectCommand as Tt,DeleteObjectsCommand as xt,GetObjectCommand as Rt}from"@aws-sdk/client-s3";import{getSignedUrl as we}from"@aws-sdk/s3-request-presigner";import{initTRPC as Ct,TRPCError as H}from"@trpc/server";import{randomBytes as ie,createHash as $t}from"node:crypto";import{SignJWT as Bt,jwtVerify as jt}from"jose";import{consola as Ee}from"consola";import{createInsertSchema as se,createUpdateSchema as F}from"drizzle-zod";import{nanoid as _e}from"nanoid";const $=r.string().min(1),Pt=r.object({COMMUN_DATA_DIR:r.string().default(z(St(),".commun")),COMMUN_MIGRATIONS_DIR:r.string().optional(),COMMUN_S3_ENDPOINT:r.string().optional(),COMMUN_S3_REGION:r.string().default("fr-par"),COMMUN_S3_BUCKET:$,COMMUN_S3_ACCESS_KEY:$,COMMUN_S3_SECRET_KEY:$,COMMUN_EMAIL_WEBHOOK_URL:$,COMMUN_EMAIL_WEBHOOK_TOKEN:r.string().optional(),COMMUN_ADMIN_URL:r.string().optional(),COMMUN_JWT_SECRET:$});function ve(i=process.env){return Pt.parse({COMMUN_DATA_DIR:i.COMMUN_DATA_DIR,COMMUN_MIGRATIONS_DIR:i.COMMUN_MIGRATIONS_DIR,COMMUN_S3_ENDPOINT:i.COMMUN_S3_ENDPOINT,COMMUN_S3_REGION:i.COMMUN_S3_REGION,COMMUN_S3_BUCKET:i.COMMUN_S3_BUCKET,COMMUN_S3_ACCESS_KEY:i.COMMUN_S3_ACCESS_KEY,COMMUN_S3_SECRET_KEY:i.COMMUN_S3_SECRET_KEY,COMMUN_EMAIL_WEBHOOK_URL:i.COMMUN_EMAIL_WEBHOOK_URL,COMMUN_EMAIL_WEBHOOK_TOKEN:i.COMMUN_EMAIL_WEBHOOK_TOKEN,COMMUN_ADMIN_URL:i.COMMUN_ADMIN_URL,COMMUN_JWT_SECRET:i.COMMUN_JWT_SECRET})}const k=()=>o("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),D=()=>o("created_at").notNull().$defaultFn(()=>new Date().toISOString()),B=()=>o("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),W=()=>o("legacy_extra",{mode:"json"}).$type(),zt=()=>o("status",{enum:ee}).notNull().default("draft"),Lt=()=>o("published_at"),be=r.object({street:r.string().optional(),postalCode:r.string().optional(),city:r.string().optional()}),U=I("organization",{id:ue("id").primaryKey().default(1),name:o("name").notNull(),type:o("type",{enum:["commune","intercommunality","syndicate","other"]}).notNull().default("commune"),slug:o("slug").notNull(),description:o("description"),address:o("address",{mode:"json"}).$type(),deployment:o("deployment",{mode:"json"}).$type(),settings:o("settings",{mode:"json"}).$type(),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:B()}),y=I("users",{id:k(),email:o("email").notNull().unique(),name:o("name").notNull(),passwordHash:o("password_hash"),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),createdAt:D(),updatedAt:B()}),m=I("sessions",{id:k(),userId:o("user_id").notNull().references(()=>y.id,{onDelete:"cascade"}),expiresAt:o("expires_at").notNull(),revokedAt:o("revoked_at"),ua:o("ua"),ip:o("ip"),createdAt:D()}),b=I("invitations",{id:k(),email:o("email").notNull(),tokenHash:o("token_hash").notNull().unique(),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),expiresAt:o("expires_at").notNull(),usedAt:o("used_at"),createdAt:D()}),f=I("api_tokens",{id:k(),name:o("name").notNull(),tokenHash:o("token_hash").notNull().unique(),lastUsedAt:o("last_used_at"),revokedAt:o("revoked_at"),createdAt:D()}),_=I("media",{id:k(),filename:o("filename").notNull(),mime:o("mime").notNull(),size:ue("size").notNull(),alt:o("alt"),caption:o("caption"),objects:o("objects",{mode:"json"}).$type().notNull(),metaData:o("meta_data",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:B()}),g=I("collection_definitions",{id:k(),name:o("name").notNull(),slug:o("slug").notNull().unique(),description:o("description"),fields:o("fields",{mode:"json"}).$type().notNull(),editor:o("editor",{mode:"json"}).$type(),display:o("display",{mode:"json"}).$type(),headings:o("headings",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:B()}),c=I("entries",{id:k(),collectionId:o("collection_id").notNull().references(()=>g.id,{onDelete:"cascade"}),title:o("title").notNull(),slug:o("slug").notNull(),data:o("data",{mode:"json"}).$type().notNull(),related:o("related",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),status:zt(),publishedAt:Lt(),legacyExtra:W(),createdAt:D(),updatedAt:B()},i=>[Mt("entries_slug_unique").on(i.collectionId,i.slug)]),Kt={__proto__:null,FIELD_TYPES:pe,PUBLICATION_STATUSES:ee,addressSchema:be,apiTokens:f,collectionDefinitions:g,entries:c,fieldDefinitionSchema:L,invitations:b,media:_,organization:U,sessions:m,users:y};function qt(){const i=import.meta.dir;return i?z(i,"..","..","..","drizzle"):void 0}function Ae(i,e){const t=e??qt();Ot(i,{recursive:!0});const s=new Ut(z(i,"commun.db"));s.exec("PRAGMA journal_mode=WAL"),s.exec("PRAGMA foreign_keys=ON"),s.exec("PRAGMA busy_timeout=5000");const n=It({client:s,schema:Kt});return t&&Nt(z(t,"meta","_journal.json"))&&Dt(n,{migrationsFolder:t}),n}class Z{constructor(e){this.config=e}static fromEnv(e){return new Z({url:e.COMMUN_EMAIL_WEBHOOK_URL,token:e.COMMUN_EMAIL_WEBHOOK_TOKEN})}async sendEvent(e){const t=await fetch(this.config.url,{method:"POST",headers:{"content-type":"application/json",...this.config.token?{authorization:`Bearer ${this.config.token}`}:{}},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`email webhook ${t.status}: ${(await t.text()).slice(0,200)}`)}}class Se{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(K`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Ue=168*3600,Ht="medias/";class Oe{constructor(e){this.config=e,this.client=new kt({region:e.region,...e.endpoint?{endpoint:e.endpoint,forcePathStyle:!0}:{},credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,s){return we(this.client,new ge({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:s}),{expiresIn:Ue})}async put(e,t,s){await this.client.send(new ge({Bucket:this.config.bucket,Key:e,Body:t,ContentType:s}))}async head(e){try{return{size:(await this.client.send(new Tt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new xt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Ht)?Promise.resolve(this.publicUrl(e)):we(this.client,new Rt({Bucket:this.config.bucket,Key:e}),{expiresIn:Ue})}publicUrl(e){const t=(this.config.endpoint??`https://s3.${this.config.region}.scw.cloud`).replace(/\/+$/,""),s=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${s}`}}function Ne(i){return new Oe({endpoint:i.COMMUN_S3_ENDPOINT||void 0,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const E={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class Q extends Error{}function w(i,e){return class extends Q{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const ne=Ct.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof Q?{type:t.type}:{}}}}}),S=ne.router,Ft=ne.procedure,Ie=ne.middleware,Wt=Ie(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof Q)throw new H({code:t.trpcCode,message:t.message,cause:t})}return e}),C=Ft.use(Wt),De=i=>Ie(({ctx:e,next:t})=>{if(!e.session)throw new H({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new H({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),h=C.use(De()),v=C.use(De("admin")),Qt=S({ping:C.query(({ctx:i})=>i.services.health.check())}),Me=r.object({email:r.email(),password:r.string().min(1)}),ke=r.object({token:r.string().min(1),name:r.string().min(1).optional(),password:r.string().min(10)}),Te=r.object({email:r.email()}),xe=r.object({email:r.email(),role:r.enum(["admin","redacteur"])}),Re=r.object({id:r.string(),data:r.object({name:r.string().min(1).optional(),role:r.enum(["admin","redacteur"]).optional(),email:r.email().optional()})}),T=({id:i,email:e,name:t,role:s})=>({id:i,email:e,name:t,role:s}),Ce=r.object({name:r.string().min(1)});class $e{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(y).where(d(y.email,e)).get()}async findUserById(e){return this.db.select().from(y).where(d(y.id,e)).get()}async listUsers(){return this.db.select().from(y).all()}async hasAnyUser(){return this.db.select({id:y.id}).from(y).limit(1).all().length>0}async deleteUser(e){this.db.delete(y).where(d(y.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(y).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(d(y.id,t.id)).returning().get():this.db.insert(y).values(e).returning().get()}async insertSession(e){return this.db.insert(m).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:m,user:y}).from(m).innerJoin(y,d(y.id,m.userId)).where(M(d(m.id,e),q(m.revokedAt),te(m.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(m).set({revokedAt:t}).where(d(m.id,e)).run()}async findSessionById(e){return this.db.select().from(m).where(d(m.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(m).where(M(d(m.userId,e),q(m.revokedAt),te(m.expiresAt,t))).orderBy(R(m.createdAt)).all()}async updateUser(e,t){return this.db.update(y).set(t).where(d(y.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(b).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(b).where(M(d(b.tokenHash,e),q(b.usedAt),te(b.expiresAt,t))).get()}async markInvitationUsed(e,t){this.db.update(b).set({usedAt:t}).where(d(b.id,e)).run()}async insertApiToken(e){return this.db.insert(f).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(f).where(M(d(f.tokenHash,e),q(f.revokedAt))).get()}async touchApiToken(e,t){this.db.update(f).set({lastUsedAt:t}).where(d(f.id,e)).run()}async revokeApiToken(e,t){this.db.update(f).set({revokedAt:t}).where(d(f.id,e)).run()}async listApiTokens(){return this.db.select({id:f.id,name:f.name,lastUsedAt:f.lastUsedAt,revokedAt:f.revokedAt,createdAt:f.createdAt}).from(f).orderBy(R(f.createdAt)).all()}async purgeExpired(e){this.db.delete(m).where(ye(he(m.expiresAt,e),fe(m.revokedAt))).run(),this.db.delete(b).where(ye(he(b.expiresAt,e),fe(b.usedAt))).run()}}const re=w("user-not-found-error",E.NOT_FOUND),Be=w("session-not-found-error",E.NOT_FOUND),je=w("invitation-invalid-error",E.BAD_REQUEST),Pe=w("cannot-remove-self-error",E.BAD_REQUEST),ze=w("too-many-attempts-error",E.TOO_MANY_REQUESTS),j=i=>$t("sha256").update(i).digest("hex"),O=()=>new Date().toISOString(),Yt=720*3600*1e3,Le=168*3600*1e3,Gt=Bun.password.hashSync("commun-dummy-password-for-timing"),Jt=5*6e4,Vt=10,P=new Map,Ke=i=>{const e=Date.now(),t=(P.get(i)??[]).filter(s=>e-s<Jt);return t.length?P.set(i,t):P.delete(i),t},Zt=i=>Ke(i).length>=Vt,Xt=i=>{P.set(i,[...Ke(i),Date.now()])},ei=i=>P.delete(i);class qe{constructor(e,t={}){this.repository=e,this.options=t}jwtKey(){if(!this.options.jwtSecret)throw new Error("COMMUN_JWT_SECRET manquant \u2014 requis pour signer les sessions (fail-fast au boot)");return new TextEncoder().encode(this.options.jwtSecret)}async sendEmailEvent(e){try{await this.options.email?.sendEvent(e)}catch(t){Ee.warn(`[email] \xE9chec d'\xE9mission ${e.eventName} \u2192 ${e.email}: ${String(t)}`)}}hashPassword(e){return Bun.password.hash(e)}verifyPassword(e,t){return Bun.password.verify(e,t)}async login(e,t,s){const n=e.toLowerCase();if(Zt(n))throw new ze;const a=await this.repository.findUserByEmail(n),l=await this.verifyPassword(t,a?.passwordHash??Gt);return!a?.passwordHash||!l?(Xt(n),null):(ei(n),this.createSession(a,s))}async createSession(e,t){const s=new Date(Date.now()+Yt).toISOString(),n=await this.repository.insertSession({userId:e.id,expiresAt:s,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Bt({session:n.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(s)).sign(this.jwtKey()),session:{sessionId:n.id,user:e,expiresAt:s}}}async verifySession(e){let t;try{const{payload:n}=await jt(e,this.jwtKey());if(typeof n.session!="string")return null;t=n.session}catch{return null}const s=await this.repository.findActiveSessionWithUser(t,O());return s?{sessionId:s.session.id,user:s.user,expiresAt:s.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,O())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,O())).map(s=>({id:s.id,createdAt:s.createdAt,expiresAt:s.expiresAt,ua:s.ua,ip:s.ip,current:s.id===t}))}async revokeOwnSession(e,t){const s=await this.repository.findSessionById(t);if(!s||s.userId!==e)throw new Be(`session not found: ${t}`);await this.repository.revokeSession(t,O())}async purgeExpired(){await this.repository.purgeExpired(O())}async createInvitation(e){const t=ie(32).toString("base64url"),s=new Date(Date.now()+Le).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:j(t),expiresAt:s}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:s}}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const s=ie(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:j(s),expiresAt:new Date(Date.now()+Le).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${s}`}})}async acceptInvitation(e,t){const s=await this.repository.findValidInvitation(j(e),O());if(!s)throw new je;const n=await this.repository.findUserByEmail(s.email),a=t.name?.trim()||n?.name||s.email.split("@")[0]||"Membre",l=await this.repository.activateUser({email:s.email,name:a,passwordHash:await this.hashPassword(t.password),role:s.role});return await this.repository.markInvitationUsed(s.id,O()),l}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new re(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new Pe;await this.repository.deleteUser(t)}async updateUser(e,t){const s=await this.repository.updateUser(e,t);if(!s)throw new re(`user not found: ${e}`);return s}async createApiToken(e){const t=`commun_${ie(24).toString("base64url")}`,s=await this.repository.insertApiToken({name:e,tokenHash:j(t)});return{token:t,record:s}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(j(e));return t?(await this.repository.touchApiToken(t.id,O()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,O())}async listApiTokens(){return this.repository.listApiTokens()}}const He=S({login:C.input(Me).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new H({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:T(t.session.user)}}),logout:h.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:h.query(({ctx:i})=>({user:T(i.session.user)})),sessions:S({list:h.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:h.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:C.input(ke).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:T(t)}}),requestPasswordReset:C.input(Te).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Fe=S({list:v.query(async({ctx:i})=>(await i.services.users.listUsers()).map(T)),directory:h.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:v.input(r.object({id:r.string()})).query(async({ctx:i,input:e})=>T(await i.services.users.getUser(e.id))),invite:v.input(xe).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:v.input(Re).mutation(async({ctx:i,input:e})=>T(await i.services.users.updateUser(e.id,e.data))),remove:v.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),We=S({list:v.query(({ctx:i})=>i.services.users.listApiTokens()),create:v.input(Ce).mutation(async({ctx:i,input:e})=>{const{token:t,record:s}=await i.services.users.createApiToken(e.name);return{token:t,id:s.id,name:s.name}}),revoke:v.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),Qe={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},ti={createdBy:!0,updatedBy:!0},oe={...Qe,...ti},Ye={...Qe,updatedBy:!0},Ge=se(U).omit(Ye),Je=F(U).omit(Ye);class Ve{constructor(e){this.db=e}async get(){return this.db.select().from(U).where(d(U.id,1)).get()}async insert(e){return this.db.insert(U).values({...e,id:1}).returning().get()}async update(e){return this.db.update(U).set(e).where(d(U.id,1)).returning().get()}}const Ze=w("organization-not-initialized-error",E.NOT_FOUND),Xe=w("organization-already-initialized-error",E.BAD_REQUEST),et=w("deploy-hook-missing-error",E.BAD_REQUEST),ae=w("deploy-failed-error",E.INTERNAL_SERVER_ERROR),ii=3e4;class tt{constructor(e,t={}){this.repository=e,this.options=t}async get(){return await this.repository.get()??null}async init(e){if(await this.repository.get())throw new Xe;return this.repository.insert(e)}async update(e,t){const s=await this.repository.update({...e,updatedBy:t??null});if(!s)throw new Ze;return s}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new et;const t=this.options.fetchImpl??fetch;let s;try{s=await t(e,{signal:AbortSignal.timeout(ii)})}catch(n){throw new ae(`deploy hook unreachable: ${n instanceof Error?n.message:String(n)}`)}if(!s.ok)throw new ae(`deploy hook: ${s.status} ${s.statusText}`);return{status:s.status}}}const it=S({get:h.query(({ctx:i})=>i.services.organization.get()),init:v.input(Ge).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:v.input(Je).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:h.mutation(({ctx:i})=>i.services.organization.deploy())}),st=r.object({filename:r.string().min(1),mime:r.string().min(1),metaData:r.record(r.string(),r.string()).optional()}),nt=r.object({key:r.string().min(1),filename:r.string().min(1),mime:r.string().min(1),alt:r.string().optional(),metaData:r.record(r.string(),r.unknown()).optional()}),rt=F(_).pick({alt:!0,caption:!0,filename:!0});class ot{constructor(e){this.db=e}async insert(e){return this.db.insert(_).values(e).returning().get()}async findById(e){return this.db.select().from(_).where(d(_.id,e)).get()}async list(){return this.db.select().from(_).orderBy(R(_.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(_).where(K`json_extract(${_.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(_).set(t).where(d(_.id,e)).returning().get()}async delete(e){this.db.delete(_).where(d(_.id,e)).run()}}const Y=w("media-not-found-error",E.NOT_FOUND),de=w("unsupported-mime-error",E.BAD_REQUEST),at=w("upload-incomplete-error",E.BAD_REQUEST),ce=new Set(["image/jpeg","image/png","image/webp","image/gif","application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet"]),dt=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],le=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",ct="medias/";class lt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,s){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const n=`${ct}${_e(10)}/${le(e)}`;return{key:n,url:await this.storage.presignedPutUrl(n,t,s)}}async finalize(e,t){const s=await this.storage.head(e.key);if(!s)throw new at(`object not found in storage: ${e.key}`);const n=await this.repository.insert({filename:le(e.filename),mime:e.mime,size:s.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Ee.info(`[media] resize \xE0 impl\xE9menter pour ${n.id} (${dt.join(", ")})`),n}async uploadDirect(e,t,s,n,a){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const l=`${ct}${_e(10)}/${le(e)}`;return await this.storage.put(l,s,t),this.finalize({key:l,filename:e,mime:t,metaData:n},a)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,s){const n=await this.repository.update(e,{...t,updatedBy:s??null});if(!n)throw new Y(`media not found: ${e}`);return n}async remove(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);const s=t.objects;await this.storage.remove([s.original,...Object.values(s.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async toLegacyMedia(e){const t=await this.repository.findById(e);if(!t)return null;const s=t.objects.original,n=await this.storage.url(s),a={original:n},l=s.match(/^(.*)-original\.[^.]+$/)?.[1];for(const u of dt)a[u]=l?await this.storage.url(`${l}-${u}.webp`):n;return{_id:t.id,id:t.id,originalName:t.filename,mime:t.mime,...t.metaData?{metaData:t.metaData}:{},objects:a}}async resolveMediaPlaceholders(e){const t=n=>typeof n=="string"&&n.startsWith("_media:"),s=async n=>(await Promise.all(n.map(a=>this.toLegacyMedia(a.slice(7))))).filter(a=>a!==null);if(t(e))return s([e]);if(Array.isArray(e))return e.length>0&&e.every(t)?s(e):Promise.all(e.map(n=>this.resolveMediaPlaceholders(n)));if(e!==null&&typeof e=="object"){const n={};for(const[a,l]of Object.entries(e))n[a]=await this.resolveMediaPlaceholders(l);return n}return e}async objectUrls(e){const t=e.objects,s={original:await this.storage.url(t.original)};for(const[n,a]of Object.entries(t.variants??{}))s[n]=await this.storage.url(a);return s}}const ut=S({requestUpload:h.input(st).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:h.input(nt).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:h.query(({ctx:i})=>i.services.media.listResolved()),get:h.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:h.input(r.object({id:r.string(),data:rt})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:h.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))}),pt=se(g).omit(oe).extend({fields:r.array(L).min(1),slug:r.string().optional()}),mt=F(g).omit(oe).extend({fields:r.array(L).min(1).optional()}),yt={...oe,related:!0,collectionId:!0},ht=se(c).omit(yt).extend({slug:r.string().optional()}),ft=F(c).omit(yt).extend({related:r.array(r.string()).optional()});class gt{constructor(e){this.db=e}async list(){return this.db.select().from(g).all()}async findBySlug(e){return this.db.select().from(g).where(d(g.slug,e)).get()}async findById(e){return this.db.select().from(g).where(d(g.id,e)).get()}async findByLegacyId(e){return this.db.select().from(g).where(K`json_extract(${g.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(g).values(e).returning().get()}async update(e,t){return this.db.update(g).set(t).where(d(g.id,e)).returning().get()}async delete(e){return this.db.delete(g).where(d(g.id,e)).returning().get()}}class wt{constructor(e){this.db=e}async list(e){return this.db.select().from(c).where(d(c.collectionId,e)).orderBy(R(c.updatedAt)).all()}async listPaginated(e,t){return this.db.select().from(c).where(d(c.collectionId,e)).orderBy(R(c.updatedAt)).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(c).where(M(d(c.collectionId,e),d(c.status,"published"))).orderBy(R(c.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(c).where(M(d(c.collectionId,e),d(c.slug,t))).get()}async findById(e){return this.db.select().from(c).where(d(c.id,e)).get()}async findByDataField(e,t,s){return this.db.select().from(c).where(M(d(c.collectionId,e),K`json_extract(${c.data}, ${`$.${t}`}) = ${s}`)).get()}async insert(e){return this.db.insert(c).values(e).returning().get()}async update(e,t){return this.db.update(c).set(t).where(d(c.id,e)).returning().get()}async delete(e){return this.db.delete(c).where(d(c.id,e)).returning().get()}}const G=w("collection-not-found-error",E.NOT_FOUND),J=w("entry-not-found-error",E.NOT_FOUND),Et=w("invalid-entry-data-error",E.BAD_REQUEST),_t=w("duplicate-slug-error",E.BAD_REQUEST);function vt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function V(i,e){const t=[];for(const s of i){if(s.type!=="relation")continue;const n=e[s.name];typeof n=="string"&&n?t.push(n):Array.isArray(n)&&t.push(...n.filter(a=>typeof a=="string"))}return[...new Set(t)]}class bt{constructor(e,t,s){this.definitions=e,this.entries=t,this.media=s}async listDefinitions(){return this.definitions.list()}async getDefinition(e){const t=await this.definitions.findBySlug(e)??await this.definitions.findById(e);if(!t)throw new G(`collection not found: ${e}`);return t}async createDefinition(e,t){return this.definitions.insert({...e,slug:e.slug||await this.uniqueDefinitionSlug(vt(e.name)),createdBy:t??null,updatedBy:t??null})}async updateDefinition(e,t,s){const n=await this.definitions.update(e,{...t,updatedBy:s??null});if(!n)throw new G(`collection not found: ${e}`);return n}async removeDefinition(e){if(!await this.definitions.delete(e))throw new G(`collection not found: ${e}`)}validateData(e,t){const s=me(e.fields).safeParse(t);if(!s.success)throw new Et(`invalid data for collection ${e.slug}: ${s.error.message}`);return s.data}async listEntries(e){return this.entries.list((await this.getDefinition(e)).id)}async getEntry(e){const t=await this.entries.findById(e);if(!t)throw new J(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){const s=await this.getDefinition(e);return this.entries.listPaginated(s.id,{skip:t.skip??0,limit:t.limit??20})}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,s){const n=await this.getDefinition(e),a=this.validateData(n,t.data),l=await this.uniqueEntrySlug(n.id,t.slug||vt(t.title)),u=await this.entries.insert({...t,slug:l,data:a,collectionId:n.id,createdBy:s??null,updatedBy:s??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(n,u.id,[],V(n.fields,a)),u}async updateEntry(e,t,s){const n=await this.entries.findById(e);if(!n)throw new J(`entry not found: ${e}`);const a=await this.getDefinition(n.collectionId),l=new Set(a.fields.map(A=>A.name)),u=Object.fromEntries(Object.entries(n.data??{}).filter(([A])=>!l.has(A))),p=t.data?{...n.data,...t.data}:n.data,N=Object.fromEntries(Object.entries(p).filter(([A])=>l.has(A)||A in(t.data??{}))),x=t.data?{...u,...this.validateData(a,N)}:void 0,X={...t,updatedBy:s??null};x&&(X.data=x),t.status==="published"&&!t.publishedAt&&(X.publishedAt=new Date().toISOString());try{const A=await this.entries.update(e,X);return x&&await this.linkRelations(a,e,V(a.fields,n.data),V(a.fields,x)),t.related&&await this.linkRelations(a,e,n.related??[],t.related),A}catch(A){throw this.mapSlugConflict(A,a.slug,t.slug??n.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new J(`entry not found: ${e}`);const s=await this.getDefinition(t.collectionId);await this.linkRelations(s,e,V(s.fields,t.data),[]),await this.entries.delete(e)}async resolveEntryData(e,t){const s={};for(const n of e.fields){if(n.hidden)continue;const a=t.data[n.name];if(a==null){s[n.name]=a;continue}switch(n.type){case"rich-text":s[n.name]=JSON.stringify(await this.resolveRichTextMedia(a));break;case"steps":{const l=Array.isArray(a)?a:[];s[n.name]=await Promise.all(l.map(async u=>{const p=u;return p.content==null?p:{...p,content:JSON.stringify(await this.resolveRichTextMedia(p.content))}}));break}case"media":{const l=Array.isArray(a)?a:[a],u=await Promise.all(l.filter(p=>typeof p=="string"&&p.length>0).sort().map(p=>this.media.toLegacyMedia(p)));s[n.name]=u.filter(p=>p!==null);break}default:s[n.name]=a}}return s}async resolveRichTextMedia(e){if(Array.isArray(e))return Promise.all(e.map(n=>this.resolveRichTextMedia(n)));if(e===null||typeof e!="object")return e;const t={...e},s=t.attrs;if((t.type==="image"||t.type==="file")&&s&&typeof s.id=="string"&&s.id){const n=await this.media.toLegacyMedia(s.id);t.attrs={...s,mediaRecord:n,src:n?.objects.original??null}}return Array.isArray(t.content)&&(t.content=await this.resolveRichTextMedia(t.content)),t}hasEmptySchedules(e){const t=e.data.schedules??e.legacyExtra?.schedules;return t!==void 0&&(t.periods?.length??0)===0}async legacyRecordsPayload(){const e={};for(const t of await this.definitions.list()){const s=await this.entries.listPublished(t.id);for(const n of s)t.slug==="events"&&this.hasEmptySchedules(n)||(e[n.id]={_id:n.id,title:n.title,slug:n.slug,relatedCollection:t.slug,...n.publishedAt!=null?{publishedAt:n.publishedAt}:{},...await this.resolveEntryData(t,n),records:n.related??[]})}return e}async publishedSlugs(){const e=[];for(const t of await this.definitions.list()){const s=await this.entries.listPublished(t.id);e.push(...s.map(n=>`/${t.slug}/${n.slug}`))}return e}mapSlugConflict(e,t,s){return e instanceof Error&&e.message.includes("UNIQUE constraint failed")&&e.message.includes("entries.slug")?new _t(`le slug "${s}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let s=t;for(let n=1;await this.entries.findBySlug(e,s);n++)s=`${t}-${n}`;return s}async uniqueDefinitionSlug(e){let t=e;for(let s=1;await this.definitions.findBySlug(t);s++)t=`${e}-${s}`;return t}async linkRelations(e,t,s,n){const a=n.filter(u=>!s.includes(u)),l=s.filter(u=>!n.includes(u));for(const u of a){const p=await this.entries.findById(u);if(!p)continue;const N=new Set(p.related??[]);N.add(t),await this.entries.update(u,{related:[...N]})}for(const u of l){const p=await this.entries.findById(u);p&&await this.entries.update(u,{related:(p.related??[]).filter(N=>N!==t)})}}}const At=S({list:h.query(({ctx:i})=>i.services.collections.listDefinitions()),get:h.input(r.object({idOrSlug:r.string()})).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:v.input(pt).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:v.input(r.object({id:r.string(),data:mt})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:v.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:S({get:h.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),list:h.input(r.object({collectionId:r.string(),skip:r.number().int().min(0).optional(),limit:r.number().int().min(1).max(100).optional()})).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),create:h.input(r.object({collectionId:r.string(),data:ht})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:h.input(r.object({id:r.string(),data:ft})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:h.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})});function si({env:i}={}){const e=i??ve(),t=Ae(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),s=Ne(e),n=Z.fromEnv(e),a=new qe(new $e(t),{email:n,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),l=new ot(t),u=new lt(l,s),p=new bt(new gt(t),new wt(t),u),N=new tt(new Ve(t)),x={health:new Se(t),users:a,organization:N,media:u,collections:p};return{env:e,db:t,storage:s,services:x}}const ni=S({health:Qt,auth:He,users:Fe,apiTokens:We,organization:it,media:ut,collections:At});export{ce as ALLOWED_MIME,Pe as CannotRemoveSelfError,G as CollectionNotFoundError,bt as CollectionsService,gt as DefinitionRepository,ae as DeployFailedError,et as DeployHookMissingError,Q as DomainError,_t as DuplicateSlugError,Z as EmailService,J as EntryNotFoundError,wt as EntryRepository,pe as FIELD_TYPES,Se as HealthService,Et as InvalidEntryDataError,je as InvitationInvalidError,Y as MediaNotFoundError,ot as MediaRepository,lt as MediaService,Xe as OrganizationAlreadyInitializedError,Ze as OrganizationNotInitializedError,Ve as OrganizationRepository,tt as OrganizationService,ee as PUBLICATION_STATUSES,Oe as S3Storage,Be as SessionNotFoundError,ze as TooManyAttemptsError,de as UnsupportedMimeError,at as UploadIncompleteError,re as UserNotFoundError,$e as UsersRepository,qe as UsersService,ke as acceptInvitationDto,be as addressSchema,Ce as apiTokenCreateDto,f as apiTokens,We as apiTokensRouter,ni as appRouter,He as authRouter,me as buildDataSchema,g as collectionDefinitions,At as collectionsRouter,Ae as connectDb,si as createCore,Ne as createStorage,w as createTypedError,pt as definitionCreateDto,mt as definitionUpdateDto,c as entries,ht as entryCreateDto,ft as entryUpdateDto,L as fieldDefinitionSchema,b as invitations,xe as inviteDto,Me as loginDto,_ as media,nt as mediaFinalizeDto,st as mediaRequestUploadDto,ut as mediaRouter,rt as mediaUpdateDto,U as organization,Ge as organizationInitDto,it as organizationRouter,Je as organizationUpdateDto,ve as parseEnv,Te as requestPasswordResetDto,m as sessions,T as toPublicUser,Re as userUpdateDto,y as users,Fe as usersRouter};
1
+ import{homedir as bt}from"node:os";import{join as z}from"node:path";import{z as s}from"zod";import{Database as At}from"bun:sqlite";import{mkdirSync as Ut,existsSync as Ot}from"node:fs";import{drizzle as Nt}from"drizzle-orm/bun-sqlite";import{migrate as It}from"drizzle-orm/bun-sqlite/migrator";import{sqliteTable as I,text as o,integer as ue,uniqueIndex as Dt}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as ee,FIELD_TYPES as pe}from"./domains/collections/constants.mjs";import{fieldDefinitionSchema as K,buildDataSchema as me}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS}from"./domains/collections/utils.mjs";import{sql as q,eq as a,and as M,isNull as L,gt as te,desc as R,or as ye,lt as he,isNotNull as ge}from"drizzle-orm";import{S3Client as Mt,PutObjectCommand as we,HeadObjectCommand as kt,DeleteObjectsCommand as Tt,GetObjectCommand as xt}from"@aws-sdk/client-s3";import{getSignedUrl as fe}from"@aws-sdk/s3-request-presigner";import{initTRPC as Rt,TRPCError as H}from"@trpc/server";import{randomBytes as ie,createHash as Ct}from"node:crypto";import{SignJWT as Bt,jwtVerify as $t}from"jose";import{consola as Ee}from"consola";import{createInsertSchema as ne,createUpdateSchema as F}from"drizzle-zod";import{nanoid as _e}from"nanoid";const B=s.string().min(1),jt=s.object({COMMUN_DATA_DIR:s.string().default(z(bt(),".commun")),COMMUN_MIGRATIONS_DIR:s.string().optional(),COMMUN_S3_ENDPOINT:s.string().optional(),COMMUN_S3_REGION:s.string().default("fr-par"),COMMUN_S3_BUCKET:B,COMMUN_S3_ACCESS_KEY:B,COMMUN_S3_SECRET_KEY:B,COMMUN_EMAIL_WEBHOOK_URL:B,COMMUN_EMAIL_WEBHOOK_TOKEN:s.string().optional(),COMMUN_ADMIN_URL:s.string().optional(),COMMUN_JWT_SECRET:B});function ve(i=process.env){return jt.parse({COMMUN_DATA_DIR:i.COMMUN_DATA_DIR,COMMUN_MIGRATIONS_DIR:i.COMMUN_MIGRATIONS_DIR,COMMUN_S3_ENDPOINT:i.COMMUN_S3_ENDPOINT,COMMUN_S3_REGION:i.COMMUN_S3_REGION,COMMUN_S3_BUCKET:i.COMMUN_S3_BUCKET,COMMUN_S3_ACCESS_KEY:i.COMMUN_S3_ACCESS_KEY,COMMUN_S3_SECRET_KEY:i.COMMUN_S3_SECRET_KEY,COMMUN_EMAIL_WEBHOOK_URL:i.COMMUN_EMAIL_WEBHOOK_URL,COMMUN_EMAIL_WEBHOOK_TOKEN:i.COMMUN_EMAIL_WEBHOOK_TOKEN,COMMUN_ADMIN_URL:i.COMMUN_ADMIN_URL,COMMUN_JWT_SECRET:i.COMMUN_JWT_SECRET})}const k=()=>o("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),D=()=>o("created_at").notNull().$defaultFn(()=>new Date().toISOString()),$=()=>o("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),W=()=>o("legacy_extra",{mode:"json"}).$type(),Pt=()=>o("status",{enum:ee}).notNull().default("draft"),zt=()=>o("published_at"),Se=s.object({street:s.string().optional(),postalCode:s.string().optional(),city:s.string().optional()}),U=I("organization",{id:ue("id").primaryKey().default(1),name:o("name").notNull(),type:o("type",{enum:["commune","intercommunality","syndicate","other"]}).notNull().default("commune"),slug:o("slug").notNull(),description:o("description"),address:o("address",{mode:"json"}).$type(),deployment:o("deployment",{mode:"json"}).$type(),settings:o("settings",{mode:"json"}).$type(),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:$()}),u=I("users",{id:k(),email:o("email").notNull().unique(),name:o("name").notNull(),passwordHash:o("password_hash"),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),createdAt:D(),updatedAt:$()}),l=I("sessions",{id:k(),userId:o("user_id").notNull().references(()=>u.id,{onDelete:"cascade"}),expiresAt:o("expires_at").notNull(),revokedAt:o("revoked_at"),ua:o("ua"),ip:o("ip"),createdAt:D()}),v=I("invitations",{id:k(),email:o("email").notNull(),tokenHash:o("token_hash").notNull().unique(),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),expiresAt:o("expires_at").notNull(),usedAt:o("used_at"),createdAt:D()}),y=I("api_tokens",{id:k(),name:o("name").notNull(),tokenHash:o("token_hash").notNull().unique(),lastUsedAt:o("last_used_at"),revokedAt:o("revoked_at"),createdAt:D()}),E=I("media",{id:k(),filename:o("filename").notNull(),mime:o("mime").notNull(),size:ue("size").notNull(),alt:o("alt"),caption:o("caption"),objects:o("objects",{mode:"json"}).$type().notNull(),metaData:o("meta_data",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:$()}),h=I("collection_definitions",{id:k(),name:o("name").notNull(),slug:o("slug").notNull().unique(),description:o("description"),fields:o("fields",{mode:"json"}).$type().notNull(),editor:o("editor",{mode:"json"}).$type(),display:o("display",{mode:"json"}).$type(),headings:o("headings",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:$()}),d=I("entries",{id:k(),collectionId:o("collection_id").notNull().references(()=>h.id,{onDelete:"cascade"}),title:o("title").notNull(),slug:o("slug").notNull(),data:o("data",{mode:"json"}).$type().notNull(),related:o("related",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),status:Pt(),publishedAt:zt(),legacyExtra:W(),createdAt:D(),updatedAt:$()},i=>[Dt("entries_slug_unique").on(i.collectionId,i.slug)]),Kt={__proto__:null,FIELD_TYPES:pe,PUBLICATION_STATUSES:ee,addressSchema:Se,apiTokens:y,collectionDefinitions:h,entries:d,fieldDefinitionSchema:K,invitations:v,media:E,organization:U,sessions:l,users:u};function qt(){const i=import.meta.dir;return i?z(i,"..","..","..","drizzle"):void 0}function be(i,e){const t=e??qt();Ut(i,{recursive:!0});const n=new At(z(i,"commun.db"));n.exec("PRAGMA journal_mode=WAL"),n.exec("PRAGMA foreign_keys=ON"),n.exec("PRAGMA busy_timeout=5000");const r=Nt({client:n,schema:Kt});return t&&Ot(z(t,"meta","_journal.json"))&&It(r,{migrationsFolder:t}),r}class Z{constructor(e){this.config=e}static fromEnv(e){return new Z({url:e.COMMUN_EMAIL_WEBHOOK_URL,token:e.COMMUN_EMAIL_WEBHOOK_TOKEN})}async sendEvent(e){const t=await fetch(this.config.url,{method:"POST",headers:{"content-type":"application/json",...this.config.token?{authorization:`Bearer ${this.config.token}`}:{}},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`email webhook ${t.status}: ${(await t.text()).slice(0,200)}`)}}class Ae{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(q`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Ue=168*3600,Lt="medias/";class Oe{constructor(e){this.config=e,this.client=new Mt({region:e.region,...e.endpoint?{endpoint:e.endpoint,forcePathStyle:!0}:{},credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,n){return fe(this.client,new we({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:n}),{expiresIn:Ue})}async put(e,t,n){await this.client.send(new we({Bucket:this.config.bucket,Key:e,Body:t,ContentType:n}))}async head(e){try{return{size:(await this.client.send(new kt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Tt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Lt)?Promise.resolve(this.publicUrl(e)):fe(this.client,new xt({Bucket:this.config.bucket,Key:e}),{expiresIn:Ue})}publicUrl(e){const t=(this.config.endpoint??`https://s3.${this.config.region}.scw.cloud`).replace(/\/+$/,""),n=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${n}`}}function Ne(i){return new Oe({endpoint:i.COMMUN_S3_ENDPOINT||void 0,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const w={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class Q extends Error{}function g(i,e){return class extends Q{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const se=Rt.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof Q?{type:t.type}:{}}}}}),b=se.router,Ht=se.procedure,Ie=se.middleware,Ft=Ie(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof Q)throw new H({code:t.trpcCode,message:t.message,cause:t})}return e}),C=Ht.use(Ft),De=i=>Ie(({ctx:e,next:t})=>{if(!e.session)throw new H({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new H({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),p=C.use(De()),_=C.use(De("admin")),Wt=b({ping:C.query(({ctx:i})=>i.services.health.check())}),Me=s.object({email:s.email(),password:s.string().min(1)}),ke=s.object({token:s.string().min(1),name:s.string().min(1).optional(),password:s.string().min(10)}),Te=s.object({email:s.email()}),xe=s.object({email:s.email(),role:s.enum(["admin","redacteur"])}),Re=s.object({id:s.string(),data:s.object({name:s.string().min(1).optional(),role:s.enum(["admin","redacteur"]).optional(),email:s.email().optional()})}),T=({id:i,email:e,name:t,role:n})=>({id:i,email:e,name:t,role:n}),Ce=s.object({name:s.string().min(1)});class Be{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(u).where(a(u.email,e)).get()}async findUserById(e){return this.db.select().from(u).where(a(u.id,e)).get()}async listUsers(){return this.db.select().from(u).all()}async hasAnyUser(){return this.db.select({id:u.id}).from(u).limit(1).all().length>0}async deleteUser(e){this.db.delete(u).where(a(u.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(u).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(a(u.id,t.id)).returning().get():this.db.insert(u).values(e).returning().get()}async insertSession(e){return this.db.insert(l).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:l,user:u}).from(l).innerJoin(u,a(u.id,l.userId)).where(M(a(l.id,e),L(l.revokedAt),te(l.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(l).set({revokedAt:t}).where(a(l.id,e)).run()}async findSessionById(e){return this.db.select().from(l).where(a(l.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(l).where(M(a(l.userId,e),L(l.revokedAt),te(l.expiresAt,t))).orderBy(R(l.createdAt)).all()}async updateUser(e,t){return this.db.update(u).set(t).where(a(u.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(v).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(v).where(M(a(v.tokenHash,e),L(v.usedAt),te(v.expiresAt,t))).get()}async markInvitationUsed(e,t){this.db.update(v).set({usedAt:t}).where(a(v.id,e)).run()}async insertApiToken(e){return this.db.insert(y).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(y).where(M(a(y.tokenHash,e),L(y.revokedAt))).get()}async touchApiToken(e,t){this.db.update(y).set({lastUsedAt:t}).where(a(y.id,e)).run()}async revokeApiToken(e,t){this.db.update(y).set({revokedAt:t}).where(a(y.id,e)).run()}async listApiTokens(){return this.db.select({id:y.id,name:y.name,lastUsedAt:y.lastUsedAt,revokedAt:y.revokedAt,createdAt:y.createdAt}).from(y).orderBy(R(y.createdAt)).all()}async purgeExpired(e){this.db.delete(l).where(ye(he(l.expiresAt,e),ge(l.revokedAt))).run(),this.db.delete(v).where(ye(he(v.expiresAt,e),ge(v.usedAt))).run()}}const re=g("user-not-found-error",w.NOT_FOUND),$e=g("session-not-found-error",w.NOT_FOUND),je=g("invitation-invalid-error",w.BAD_REQUEST),Pe=g("cannot-remove-self-error",w.BAD_REQUEST),ze=g("too-many-attempts-error",w.TOO_MANY_REQUESTS),j=i=>Ct("sha256").update(i).digest("hex"),O=()=>new Date().toISOString(),Qt=720*3600*1e3,Ke=168*3600*1e3,Yt=Bun.password.hashSync("commun-dummy-password-for-timing"),Gt=5*6e4,Jt=10,P=new Map,qe=i=>{const e=Date.now(),t=(P.get(i)??[]).filter(n=>e-n<Gt);return t.length?P.set(i,t):P.delete(i),t},Vt=i=>qe(i).length>=Jt,Zt=i=>{P.set(i,[...qe(i),Date.now()])},Xt=i=>P.delete(i);class Le{constructor(e,t={}){this.repository=e,this.options=t}jwtKey(){if(!this.options.jwtSecret)throw new Error("COMMUN_JWT_SECRET manquant \u2014 requis pour signer les sessions (fail-fast au boot)");return new TextEncoder().encode(this.options.jwtSecret)}async sendEmailEvent(e){try{await this.options.email?.sendEvent(e)}catch(t){Ee.warn(`[email] \xE9chec d'\xE9mission ${e.eventName} \u2192 ${e.email}: ${String(t)}`)}}hashPassword(e){return Bun.password.hash(e)}verifyPassword(e,t){return Bun.password.verify(e,t)}async login(e,t,n){const r=e.toLowerCase();if(Vt(r))throw new ze;const c=await this.repository.findUserByEmail(r),f=await this.verifyPassword(t,c?.passwordHash??Yt);return!c?.passwordHash||!f?(Zt(r),null):(Xt(r),this.createSession(c,n))}async createSession(e,t){const n=new Date(Date.now()+Qt).toISOString(),r=await this.repository.insertSession({userId:e.id,expiresAt:n,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Bt({session:r.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(n)).sign(this.jwtKey()),session:{sessionId:r.id,user:e,expiresAt:n}}}async verifySession(e){let t;try{const{payload:r}=await $t(e,this.jwtKey());if(typeof r.session!="string")return null;t=r.session}catch{return null}const n=await this.repository.findActiveSessionWithUser(t,O());return n?{sessionId:n.session.id,user:n.user,expiresAt:n.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,O())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,O())).map(n=>({id:n.id,createdAt:n.createdAt,expiresAt:n.expiresAt,ua:n.ua,ip:n.ip,current:n.id===t}))}async revokeOwnSession(e,t){const n=await this.repository.findSessionById(t);if(!n||n.userId!==e)throw new $e(`session not found: ${t}`);await this.repository.revokeSession(t,O())}async purgeExpired(){await this.repository.purgeExpired(O())}async createInvitation(e){const t=ie(32).toString("base64url"),n=new Date(Date.now()+Ke).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:j(t),expiresAt:n}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:n}}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const n=ie(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:j(n),expiresAt:new Date(Date.now()+Ke).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${n}`}})}async acceptInvitation(e,t){const n=await this.repository.findValidInvitation(j(e),O());if(!n)throw new je;const r=await this.repository.findUserByEmail(n.email),c=t.name?.trim()||r?.name||n.email.split("@")[0]||"Membre",f=await this.repository.activateUser({email:n.email,name:c,passwordHash:await this.hashPassword(t.password),role:n.role});return await this.repository.markInvitationUsed(n.id,O()),f}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new re(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new Pe;await this.repository.deleteUser(t)}async updateUser(e,t){const n=await this.repository.updateUser(e,t);if(!n)throw new re(`user not found: ${e}`);return n}async createApiToken(e){const t=`commun_${ie(24).toString("base64url")}`,n=await this.repository.insertApiToken({name:e,tokenHash:j(t)});return{token:t,record:n}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(j(e));return t?(await this.repository.touchApiToken(t.id,O()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,O())}async listApiTokens(){return this.repository.listApiTokens()}}const He=b({login:C.input(Me).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new H({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:T(t.session.user)}}),logout:p.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:p.query(({ctx:i})=>({user:T(i.session.user)})),sessions:b({list:p.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:p.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:C.input(ke).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:T(t)}}),requestPasswordReset:C.input(Te).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Fe=b({list:_.query(async({ctx:i})=>(await i.services.users.listUsers()).map(T)),directory:p.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:_.input(s.object({id:s.string()})).query(async({ctx:i,input:e})=>T(await i.services.users.getUser(e.id))),invite:_.input(xe).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:_.input(Re).mutation(async({ctx:i,input:e})=>T(await i.services.users.updateUser(e.id,e.data))),remove:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),We=b({list:_.query(({ctx:i})=>i.services.users.listApiTokens()),create:_.input(Ce).mutation(async({ctx:i,input:e})=>{const{token:t,record:n}=await i.services.users.createApiToken(e.name);return{token:t,id:n.id,name:n.name}}),revoke:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),Qe={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},ei={createdBy:!0,updatedBy:!0},oe={...Qe,...ei},Ye={...Qe,updatedBy:!0},Ge=ne(U).omit(Ye),Je=F(U).omit(Ye);class Ve{constructor(e){this.db=e}async get(){return this.db.select().from(U).where(a(U.id,1)).get()}async insert(e){return this.db.insert(U).values({...e,id:1}).returning().get()}async update(e){return this.db.update(U).set(e).where(a(U.id,1)).returning().get()}}const Ze=g("organization-not-initialized-error",w.NOT_FOUND),Xe=g("organization-already-initialized-error",w.BAD_REQUEST),et=g("deploy-hook-missing-error",w.BAD_REQUEST),ae=g("deploy-failed-error",w.INTERNAL_SERVER_ERROR),ti=3e4;class tt{constructor(e,t={}){this.repository=e,this.options=t}async get(){return await this.repository.get()??null}async init(e){if(await this.repository.get())throw new Xe;return this.repository.insert(e)}async update(e,t){const n=await this.repository.update({...e,updatedBy:t??null});if(!n)throw new Ze;return n}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new et;const t=this.options.fetchImpl??fetch;let n;try{n=await t(e,{signal:AbortSignal.timeout(ti)})}catch(r){throw new ae(`deploy hook unreachable: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw new ae(`deploy hook: ${n.status} ${n.statusText}`);return{status:n.status}}}const it=b({get:p.query(({ctx:i})=>i.services.organization.get()),init:_.input(Ge).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:_.input(Je).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:p.mutation(({ctx:i})=>i.services.organization.deploy())}),nt=s.object({filename:s.string().min(1),mime:s.string().min(1),metaData:s.record(s.string(),s.string()).optional()}),st=s.object({key:s.string().min(1),filename:s.string().min(1),mime:s.string().min(1),alt:s.string().optional(),metaData:s.record(s.string(),s.unknown()).optional()}),rt=F(E).pick({alt:!0,caption:!0,filename:!0});class ot{constructor(e){this.db=e}async insert(e){return this.db.insert(E).values(e).returning().get()}async findById(e){return this.db.select().from(E).where(a(E.id,e)).get()}async list(){return this.db.select().from(E).orderBy(R(E.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(E).where(q`json_extract(${E.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(E).set(t).where(a(E.id,e)).returning().get()}async delete(e){this.db.delete(E).where(a(E.id,e)).run()}}const Y=g("media-not-found-error",w.NOT_FOUND),de=g("unsupported-mime-error",w.BAD_REQUEST),at=g("upload-incomplete-error",w.BAD_REQUEST),ce=new Set(["image/jpeg","image/png","image/webp","image/gif","application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet"]),ii=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],le=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",dt="medias/";class ct{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,n){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const r=`${dt}${_e(10)}/${le(e)}`;return{key:r,url:await this.storage.presignedPutUrl(r,t,n)}}async finalize(e,t){const n=await this.storage.head(e.key);if(!n)throw new at(`object not found in storage: ${e.key}`);const r=await this.repository.insert({filename:le(e.filename),mime:e.mime,size:n.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Ee.info(`[media] resize \xE0 impl\xE9menter pour ${r.id} (${ii.join(", ")})`),r}async uploadDirect(e,t,n,r,c){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const f=`${dt}${_e(10)}/${le(e)}`;return await this.storage.put(f,n,t),this.finalize({key:f,filename:e,mime:t,metaData:r},c)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,n){const r=await this.repository.update(e,{...t,updatedBy:n??null});if(!r)throw new Y(`media not found: ${e}`);return r}async remove(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);const n=t.objects;await this.storage.remove([n.original,...Object.values(n.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async objectUrls(e){const t=e.objects,n={original:await this.storage.url(t.original)};for(const[r,c]of Object.entries(t.variants??{}))n[r]=await this.storage.url(c);return n}}const lt=b({requestUpload:p.input(nt).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:p.input(st).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:p.query(({ctx:i})=>i.services.media.listResolved()),get:p.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:p.input(s.object({id:s.string(),data:rt})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:p.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))}),ut=ne(h).omit(oe).extend({fields:s.array(K).min(1),slug:s.string().optional()}),pt=F(h).omit(oe).extend({fields:s.array(K).min(1).optional()}),mt={...oe,related:!0,collectionId:!0},yt=ne(d).omit(mt).extend({slug:s.string().optional()}),ht=F(d).omit(mt).extend({related:s.array(s.string()).optional()});class gt{constructor(e){this.db=e}async list(){return this.db.select().from(h).all()}async findBySlug(e){return this.db.select().from(h).where(a(h.slug,e)).get()}async findById(e){return this.db.select().from(h).where(a(h.id,e)).get()}async findByLegacyId(e){return this.db.select().from(h).where(q`json_extract(${h.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(h).values(e).returning().get()}async update(e,t){return this.db.update(h).set(t).where(a(h.id,e)).returning().get()}async delete(e){return this.db.delete(h).where(a(h.id,e)).returning().get()}}class wt{constructor(e){this.db=e}async list(e){return this.db.select().from(d).where(a(d.collectionId,e)).orderBy(R(d.updatedAt)).all()}async listPaginated(e,t){return this.db.select().from(d).where(a(d.collectionId,e)).orderBy(R(d.updatedAt)).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(d).where(M(a(d.collectionId,e),a(d.status,"published"))).orderBy(R(d.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(d).where(M(a(d.collectionId,e),a(d.slug,t))).get()}async findById(e){return this.db.select().from(d).where(a(d.id,e)).get()}async findByDataField(e,t,n){return this.db.select().from(d).where(M(a(d.collectionId,e),q`json_extract(${d.data}, ${`$.${t}`}) = ${n}`)).get()}async insert(e){return this.db.insert(d).values(e).returning().get()}async update(e,t){return this.db.update(d).set(t).where(a(d.id,e)).returning().get()}async delete(e){return this.db.delete(d).where(a(d.id,e)).returning().get()}}const G=g("collection-not-found-error",w.NOT_FOUND),J=g("entry-not-found-error",w.NOT_FOUND),ft=g("invalid-entry-data-error",w.BAD_REQUEST),Et=g("duplicate-slug-error",w.BAD_REQUEST);function _t(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function V(i,e){const t=[];for(const n of i){if(n.type!=="relation")continue;const r=e[n.name];typeof r=="string"&&r?t.push(r):Array.isArray(r)&&t.push(...r.filter(c=>typeof c=="string"))}return[...new Set(t)]}class vt{constructor(e,t,n){this.definitions=e,this.entries=t,this.media=n}async listDefinitions(){return this.definitions.list()}async getDefinition(e){const t=await this.definitions.findBySlug(e)??await this.definitions.findById(e);if(!t)throw new G(`collection not found: ${e}`);return t}async createDefinition(e,t){return this.definitions.insert({...e,slug:e.slug||await this.uniqueDefinitionSlug(_t(e.name)),createdBy:t??null,updatedBy:t??null})}async updateDefinition(e,t,n){const r=await this.definitions.update(e,{...t,updatedBy:n??null});if(!r)throw new G(`collection not found: ${e}`);return r}async removeDefinition(e){if(!await this.definitions.delete(e))throw new G(`collection not found: ${e}`)}validateData(e,t){const n=me(e.fields).safeParse(t);if(!n.success)throw new ft(`invalid data for collection ${e.slug}: ${n.error.message}`);return n.data}async listEntries(e){return this.entries.list((await this.getDefinition(e)).id)}async getEntry(e){const t=await this.entries.findById(e);if(!t)throw new J(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){const n=await this.getDefinition(e);return this.entries.listPaginated(n.id,{skip:t.skip??0,limit:t.limit??20})}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,n){const r=await this.getDefinition(e),c=this.validateData(r,t.data),f=await this.uniqueEntrySlug(r.id,t.slug||_t(t.title)),m=await this.entries.insert({...t,slug:f,data:c,collectionId:r.id,createdBy:n??null,updatedBy:n??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(r,m.id,[],V(r.fields,c)),m}async updateEntry(e,t,n){const r=await this.entries.findById(e);if(!r)throw new J(`entry not found: ${e}`);const c=await this.getDefinition(r.collectionId),f=new Set(c.fields.map(S=>S.name)),m=Object.fromEntries(Object.entries(r.data??{}).filter(([S])=>!f.has(S))),A=t.data?{...r.data,...t.data}:r.data,N=Object.fromEntries(Object.entries(A).filter(([S])=>f.has(S)||S in(t.data??{}))),x=t.data?{...m,...this.validateData(c,N)}:void 0,X={...t,updatedBy:n??null};x&&(X.data=x),t.status==="published"&&!t.publishedAt&&(X.publishedAt=new Date().toISOString());try{const S=await this.entries.update(e,X);return x&&await this.linkRelations(c,e,V(c.fields,r.data),V(c.fields,x)),t.related&&await this.linkRelations(c,e,r.related??[],t.related),S}catch(S){throw this.mapSlugConflict(S,c.slug,t.slug??r.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new J(`entry not found: ${e}`);const n=await this.getDefinition(t.collectionId);await this.linkRelations(n,e,V(n.fields,t.data),[]),await this.entries.delete(e)}mapSlugConflict(e,t,n){return e instanceof Error&&e.message.includes("UNIQUE constraint failed")&&e.message.includes("entries.slug")?new Et(`le slug "${n}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let n=t;for(let r=1;await this.entries.findBySlug(e,n);r++)n=`${t}-${r}`;return n}async uniqueDefinitionSlug(e){let t=e;for(let n=1;await this.definitions.findBySlug(t);n++)t=`${e}-${n}`;return t}async linkRelations(e,t,n,r){const c=r.filter(m=>!n.includes(m)),f=n.filter(m=>!r.includes(m));for(const m of c){const A=await this.entries.findById(m);if(!A)continue;const N=new Set(A.related??[]);N.add(t),await this.entries.update(m,{related:[...N]})}for(const m of f){const A=await this.entries.findById(m);A&&await this.entries.update(m,{related:(A.related??[]).filter(N=>N!==t)})}}}const St=b({list:p.query(({ctx:i})=>i.services.collections.listDefinitions()),get:p.input(s.object({idOrSlug:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:_.input(ut).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:_.input(s.object({id:s.string(),data:pt})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:b({get:p.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),list:p.input(s.object({collectionId:s.string(),skip:s.number().int().min(0).optional(),limit:s.number().int().min(1).max(100).optional()})).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),create:p.input(s.object({collectionId:s.string(),data:yt})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:p.input(s.object({id:s.string(),data:ht})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:p.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})});function ni({env:i}={}){const e=i??ve(),t=be(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),n=Ne(e),r=Z.fromEnv(e),c=new Le(new Be(t),{email:r,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),f=new ot(t),m=new ct(f,n),A=new vt(new gt(t),new wt(t),m),N=new tt(new Ve(t)),x={health:new Ae(t),users:c,organization:N,media:m,collections:A};return{env:e,db:t,storage:n,services:x}}const si=b({health:Wt,auth:He,users:Fe,apiTokens:We,organization:it,media:lt,collections:St});export{ce as ALLOWED_MIME,Pe as CannotRemoveSelfError,G as CollectionNotFoundError,vt as CollectionsService,gt as DefinitionRepository,ae as DeployFailedError,et as DeployHookMissingError,Q as DomainError,Et as DuplicateSlugError,Z as EmailService,J as EntryNotFoundError,wt as EntryRepository,pe as FIELD_TYPES,Ae as HealthService,ft as InvalidEntryDataError,je as InvitationInvalidError,Y as MediaNotFoundError,ot as MediaRepository,ct as MediaService,Xe as OrganizationAlreadyInitializedError,Ze as OrganizationNotInitializedError,Ve as OrganizationRepository,tt as OrganizationService,ee as PUBLICATION_STATUSES,Oe as S3Storage,$e as SessionNotFoundError,ze as TooManyAttemptsError,de as UnsupportedMimeError,at as UploadIncompleteError,re as UserNotFoundError,Be as UsersRepository,Le as UsersService,ke as acceptInvitationDto,Se as addressSchema,Ce as apiTokenCreateDto,y as apiTokens,We as apiTokensRouter,si as appRouter,He as authRouter,me as buildDataSchema,h as collectionDefinitions,St as collectionsRouter,be as connectDb,ni as createCore,Ne as createStorage,g as createTypedError,ut as definitionCreateDto,pt as definitionUpdateDto,d as entries,yt as entryCreateDto,ht as entryUpdateDto,K as fieldDefinitionSchema,v as invitations,xe as inviteDto,Me as loginDto,E as media,st as mediaFinalizeDto,nt as mediaRequestUploadDto,lt as mediaRouter,rt as mediaUpdateDto,U as organization,Ge as organizationInitDto,it as organizationRouter,Je as organizationUpdateDto,ve as parseEnv,Te as requestPasswordResetDto,l as sessions,T as toPublicUser,Re as userUpdateDto,u as users,Fe as usersRouter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-commune/core",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "Business domains, database schema and tRPC router. Holds the logic; knows nothing of transport.",
6
6
  "main": "./dist/index.mjs",
@@ -26,7 +26,8 @@
26
26
  "types": "./dist/domains/collections/utils.d.mts",
27
27
  "import": "./dist/domains/collections/utils.mjs"
28
28
  },
29
- "./drizzle": "./drizzle"
29
+ "./drizzle": "./drizzle",
30
+ "./package.json": "./package.json"
30
31
  },
31
32
  "scripts": {
32
33
  "typecheck": "tsc --noEmit",