@open-commune/core 0.2.0 → 0.2.1

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" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
1181
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
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" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
1201
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
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
- name: string;
1896
1895
  id: string;
1896
+ name: string;
1897
1897
  createdAt: string;
1898
1898
  revokedAt: string | null;
1899
1899
  tokenHash: string;
1900
1900
  lastUsedAt: string | null;
1901
- }, "name" | "id" | "createdAt" | "revokedAt" | "lastUsedAt">[]>;
1901
+ }, "id" | "name" | "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>>;
1923
1924
  name: z.ZodString;
1924
1925
  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>>;
1956
1957
  name: z.ZodOptional<z.ZodString>;
1957
1958
  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;
@@ -2107,10 +2107,25 @@ declare class EntryRepository {
2107
2107
  private readonly db;
2108
2108
  constructor(db: StoreDb);
2109
2109
  list(collectionId: string): Promise<Entry[]>;
2110
- /** Admin listing: most recently updated first, paginated. */
2110
+ /**
2111
+ * What an admin listing keeps. Narrowing happens in SQL: the browser is never
2112
+ * handed rows in order to discard them, and a collection of several hundred
2113
+ * entries would not fit in it anyway.
2114
+ */
2115
+ private narrowing;
2116
+ /** The total a paginated listing is a window onto. Counted in SQL. */
2117
+ countMatching(options: {
2118
+ collectionId: string;
2119
+ status?: Entry['status'][];
2120
+ search?: string;
2121
+ }): Promise<number>;
2122
+ /** Admin listing: most recently updated first by default, paginated. */
2111
2123
  listPaginated(collectionId: string, options: {
2112
2124
  skip: number;
2113
2125
  limit: number;
2126
+ status?: Entry['status'][];
2127
+ search?: string;
2128
+ order?: 'recent' | 'oldest' | 'title';
2114
2129
  }): Promise<Entry[]>;
2115
2130
  listPublished(collectionId: string): Promise<Entry[]>;
2116
2131
  findBySlug(collectionId: string, slug: string): Promise<Entry | undefined>;
@@ -2123,8 +2138,8 @@ declare class EntryRepository {
2123
2138
  }
2124
2139
 
2125
2140
  declare const definitionCreateDto: z.ZodObject<{
2126
- name: z.ZodString;
2127
2141
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2142
+ name: z.ZodString;
2128
2143
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2129
2144
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2130
2145
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -2134,14 +2149,14 @@ declare const definitionCreateDto: z.ZodObject<{
2134
2149
  type: z.ZodEnum<{
2135
2150
  number: "number";
2136
2151
  boolean: "boolean";
2137
- text: "text";
2138
- "rich-text": "rich-text";
2152
+ json: "json";
2139
2153
  date: "date";
2154
+ text: "text";
2155
+ select: "select";
2140
2156
  media: "media";
2157
+ "rich-text": "rich-text";
2141
2158
  relation: "relation";
2142
- select: "select";
2143
2159
  steps: "steps";
2144
- json: "json";
2145
2160
  }>;
2146
2161
  required: z.ZodDefault<z.ZodBoolean>;
2147
2162
  hidden: z.ZodDefault<z.ZodBoolean>;
@@ -2154,9 +2169,9 @@ declare const definitionCreateDto: z.ZodObject<{
2154
2169
  in: {};
2155
2170
  }>;
2156
2171
  declare const definitionUpdateDto: z.ZodObject<{
2172
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2157
2173
  name: z.ZodOptional<z.ZodString>;
2158
2174
  slug: z.ZodOptional<z.ZodString>;
2159
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2160
2175
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2161
2176
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2162
2177
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -2166,14 +2181,14 @@ declare const definitionUpdateDto: z.ZodObject<{
2166
2181
  type: z.ZodEnum<{
2167
2182
  number: "number";
2168
2183
  boolean: "boolean";
2169
- text: "text";
2170
- "rich-text": "rich-text";
2184
+ json: "json";
2171
2185
  date: "date";
2186
+ text: "text";
2187
+ select: "select";
2172
2188
  media: "media";
2189
+ "rich-text": "rich-text";
2173
2190
  relation: "relation";
2174
- select: "select";
2175
2191
  steps: "steps";
2176
- json: "json";
2177
2192
  }>;
2178
2193
  required: z.ZodDefault<z.ZodBoolean>;
2179
2194
  hidden: z.ZodDefault<z.ZodBoolean>;
@@ -2244,7 +2259,15 @@ declare class CollectionsService {
2244
2259
  listEntriesPaginated(collectionIdOrSlug: string, options?: {
2245
2260
  skip?: number;
2246
2261
  limit?: number;
2262
+ status?: Entry['status'][];
2263
+ search?: string;
2264
+ order?: 'recent' | 'oldest' | 'title';
2247
2265
  }): Promise<Entry[]>;
2266
+ /** The total a listing is a window onto, under the same narrowing. */
2267
+ countEntries(collectionIdOrSlug: string, options?: {
2268
+ status?: Entry['status'][];
2269
+ search?: string;
2270
+ }): Promise<number>;
2248
2271
  listPublishedEntries(collectionIdOrSlug: string): Promise<Entry[]>;
2249
2272
  createEntry(collectionIdOrSlug: string, input: EntryCreateDto, actorId?: string): Promise<Entry>;
2250
2273
  /** PARTIAL update: `data` is merged field by field with what already exists. */
@@ -2347,10 +2370,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2347
2370
  input: void;
2348
2371
  output: {
2349
2372
  type: "commune" | "intercommunality" | "syndicate" | "other";
2350
- name: string;
2373
+ description: string | null;
2351
2374
  id: number;
2375
+ name: string;
2352
2376
  slug: string;
2353
- description: string | null;
2354
2377
  address: {
2355
2378
  street?: string | undefined;
2356
2379
  postalCode?: string | undefined;
@@ -2381,10 +2404,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2381
2404
  };
2382
2405
  output: {
2383
2406
  type: "commune" | "intercommunality" | "syndicate" | "other";
2384
- name: string;
2407
+ description: string | null;
2385
2408
  id: number;
2409
+ name: string;
2386
2410
  slug: string;
2387
- description: string | null;
2388
2411
  address: {
2389
2412
  street?: string | undefined;
2390
2413
  postalCode?: string | undefined;
@@ -2402,9 +2425,9 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2402
2425
  update: _trpc_server.TRPCMutationProcedure<{
2403
2426
  input: {
2404
2427
  type?: "commune" | "intercommunality" | "syndicate" | "other" | undefined;
2428
+ description?: string | null | undefined;
2405
2429
  name?: string | undefined;
2406
2430
  slug?: string | undefined;
2407
- description?: string | null | undefined;
2408
2431
  address?: {
2409
2432
  street?: string | undefined;
2410
2433
  postalCode?: string | undefined;
@@ -2415,10 +2438,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2415
2438
  };
2416
2439
  output: {
2417
2440
  type: "commune" | "intercommunality" | "syndicate" | "other";
2418
- name: string;
2441
+ description: string | null;
2419
2442
  id: number;
2443
+ name: string;
2420
2444
  slug: string;
2421
- description: string | null;
2422
2445
  address: {
2423
2446
  street?: string | undefined;
2424
2447
  postalCode?: string | undefined;
@@ -2792,13 +2815,13 @@ declare const apiTokensRouter: _trpc_server.TRPCBuiltRouter<{
2792
2815
  list: _trpc_server.TRPCQueryProcedure<{
2793
2816
  input: void;
2794
2817
  output: Pick<{
2795
- name: string;
2796
2818
  id: string;
2819
+ name: string;
2797
2820
  createdAt: string;
2798
2821
  revokedAt: string | null;
2799
2822
  tokenHash: string;
2800
2823
  lastUsedAt: string | null;
2801
- }, "name" | "id" | "createdAt" | "revokedAt" | "lastUsedAt">[];
2824
+ }, "id" | "name" | "createdAt" | "revokedAt" | "lastUsedAt">[];
2802
2825
  meta: object;
2803
2826
  }>;
2804
2827
  /** The plaintext token is returned ONCE — only its hash is stored. */
@@ -2943,18 +2966,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2943
2966
  metaData?: Record<string, unknown> | undefined;
2944
2967
  };
2945
2968
  output: {
2946
- filename: string;
2947
2969
  id: string;
2948
2970
  updatedBy: string | null;
2949
2971
  legacyExtra: Record<string, unknown> | null;
2950
2972
  createdAt: string;
2951
2973
  updatedAt: string;
2974
+ filename: string;
2952
2975
  mime: string;
2953
- size: number;
2976
+ metaData: Record<string, unknown> | null;
2954
2977
  alt: string | null;
2978
+ size: number;
2955
2979
  caption: string | null;
2956
2980
  objects: Record<string, unknown>;
2957
- metaData: Record<string, unknown> | null;
2958
2981
  createdBy: string | null;
2959
2982
  };
2960
2983
  meta: object;
@@ -2962,18 +2985,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2962
2985
  list: _trpc_server.TRPCQueryProcedure<{
2963
2986
  input: void;
2964
2987
  output: ({
2965
- filename: string;
2966
2988
  id: string;
2967
2989
  updatedBy: string | null;
2968
2990
  legacyExtra: Record<string, unknown> | null;
2969
2991
  createdAt: string;
2970
2992
  updatedAt: string;
2993
+ filename: string;
2971
2994
  mime: string;
2972
- size: number;
2995
+ metaData: Record<string, unknown> | null;
2973
2996
  alt: string | null;
2997
+ size: number;
2974
2998
  caption: string | null;
2975
2999
  objects: Record<string, unknown>;
2976
- metaData: Record<string, unknown> | null;
2977
3000
  createdBy: string | null;
2978
3001
  } & {
2979
3002
  objects: Record<string, string>;
@@ -2985,18 +3008,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2985
3008
  id: string;
2986
3009
  };
2987
3010
  output: {
2988
- filename: string;
2989
3011
  id: string;
2990
3012
  updatedBy: string | null;
2991
3013
  legacyExtra: Record<string, unknown> | null;
2992
3014
  createdAt: string;
2993
3015
  updatedAt: string;
3016
+ filename: string;
2994
3017
  mime: string;
2995
- size: number;
3018
+ metaData: Record<string, unknown> | null;
2996
3019
  alt: string | null;
3020
+ size: number;
2997
3021
  caption: string | null;
2998
3022
  objects: Record<string, unknown>;
2999
- metaData: Record<string, unknown> | null;
3000
3023
  createdBy: string | null;
3001
3024
  } & {
3002
3025
  objects: Record<string, string>;
@@ -3013,18 +3036,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3013
3036
  };
3014
3037
  };
3015
3038
  output: {
3016
- filename: string;
3017
3039
  id: string;
3018
3040
  updatedBy: string | null;
3019
3041
  legacyExtra: Record<string, unknown> | null;
3020
3042
  createdAt: string;
3021
3043
  updatedAt: string;
3044
+ filename: string;
3022
3045
  mime: string;
3023
- size: number;
3046
+ metaData: Record<string, unknown> | null;
3024
3047
  alt: string | null;
3048
+ size: number;
3025
3049
  caption: string | null;
3026
3050
  objects: Record<string, unknown>;
3027
- metaData: Record<string, unknown> | null;
3028
3051
  createdBy: string | null;
3029
3052
  };
3030
3053
  meta: object;
@@ -3108,10 +3131,10 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3108
3131
  list: _trpc_server.TRPCQueryProcedure<{
3109
3132
  input: void;
3110
3133
  output: {
3111
- name: string;
3134
+ description: string | null;
3112
3135
  id: string;
3136
+ name: string;
3113
3137
  slug: string;
3114
- description: string | null;
3115
3138
  updatedBy: string | null;
3116
3139
  legacyExtra: Record<string, unknown> | null;
3117
3140
  createdAt: string;
@@ -3120,7 +3143,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3120
3143
  fields: {
3121
3144
  name: string;
3122
3145
  label: string;
3123
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3146
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3124
3147
  required: boolean;
3125
3148
  hidden: boolean;
3126
3149
  options?: string[] | undefined;
@@ -3137,10 +3160,10 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3137
3160
  idOrSlug: string;
3138
3161
  };
3139
3162
  output: {
3140
- name: string;
3163
+ description: string | null;
3141
3164
  id: string;
3165
+ name: string;
3142
3166
  slug: string;
3143
- description: string | null;
3144
3167
  updatedBy: string | null;
3145
3168
  legacyExtra: Record<string, unknown> | null;
3146
3169
  createdAt: string;
@@ -3149,7 +3172,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3149
3172
  fields: {
3150
3173
  name: string;
3151
3174
  label: string;
3152
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3175
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3153
3176
  required: boolean;
3154
3177
  hidden: boolean;
3155
3178
  options?: string[] | undefined;
@@ -3167,7 +3190,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3167
3190
  fields: {
3168
3191
  name: string;
3169
3192
  label: string;
3170
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3193
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3171
3194
  required?: boolean | undefined;
3172
3195
  hidden?: boolean | undefined;
3173
3196
  options?: string[] | undefined;
@@ -3180,10 +3203,10 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3180
3203
  slug?: string | undefined;
3181
3204
  };
3182
3205
  output: {
3183
- name: string;
3206
+ description: string | null;
3184
3207
  id: string;
3208
+ name: string;
3185
3209
  slug: string;
3186
- description: string | null;
3187
3210
  updatedBy: string | null;
3188
3211
  legacyExtra: Record<string, unknown> | null;
3189
3212
  createdAt: string;
@@ -3192,7 +3215,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3192
3215
  fields: {
3193
3216
  name: string;
3194
3217
  label: string;
3195
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3218
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3196
3219
  required: boolean;
3197
3220
  hidden: boolean;
3198
3221
  options?: string[] | undefined;
@@ -3208,16 +3231,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3208
3231
  input: {
3209
3232
  id: string;
3210
3233
  data: {
3234
+ description?: string | null | undefined;
3211
3235
  name?: string | undefined;
3212
3236
  slug?: string | undefined;
3213
- description?: string | null | undefined;
3214
3237
  editor?: Record<string, unknown> | null | undefined;
3215
3238
  display?: Record<string, unknown> | null | undefined;
3216
3239
  headings?: Record<string, unknown> | null | undefined;
3217
3240
  fields?: {
3218
3241
  name: string;
3219
3242
  label: string;
3220
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3243
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3221
3244
  required?: boolean | undefined;
3222
3245
  hidden?: boolean | undefined;
3223
3246
  options?: string[] | undefined;
@@ -3226,10 +3249,10 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3226
3249
  };
3227
3250
  };
3228
3251
  output: {
3229
- name: string;
3252
+ description: string | null;
3230
3253
  id: string;
3254
+ name: string;
3231
3255
  slug: string;
3232
- description: string | null;
3233
3256
  updatedBy: string | null;
3234
3257
  legacyExtra: Record<string, unknown> | null;
3235
3258
  createdAt: string;
@@ -3238,7 +3261,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3238
3261
  fields: {
3239
3262
  name: string;
3240
3263
  label: string;
3241
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3264
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3242
3265
  required: boolean;
3243
3266
  hidden: boolean;
3244
3267
  options?: string[] | undefined;
@@ -3296,9 +3319,13 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3296
3319
  };
3297
3320
  meta: object;
3298
3321
  }>;
3322
+ /** Narrowing is optional: a caller that ignores it keeps the old behaviour. */
3299
3323
  list: _trpc_server.TRPCQueryProcedure<{
3300
3324
  input: {
3301
3325
  collectionId: string;
3326
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
3327
+ search?: string | undefined;
3328
+ order?: "title" | "recent" | "oldest" | undefined;
3302
3329
  skip?: number | undefined;
3303
3330
  limit?: number | undefined;
3304
3331
  };
@@ -3319,6 +3346,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3319
3346
  }[];
3320
3347
  meta: object;
3321
3348
  }>;
3349
+ /** The total a listing is a window onto, under the same narrowing. */
3350
+ count: _trpc_server.TRPCQueryProcedure<{
3351
+ input: {
3352
+ collectionId: string;
3353
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
3354
+ search?: string | undefined;
3355
+ };
3356
+ output: number;
3357
+ meta: object;
3358
+ }>;
3322
3359
  create: _trpc_server.TRPCMutationProcedure<{
3323
3360
  input: {
3324
3361
  collectionId: string;
@@ -4190,9 +4227,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4190
4227
  legacyExtra: Record<string, unknown> | null;
4191
4228
  createdBy: string | null;
4192
4229
  collectionId: string;
4230
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4193
4231
  title: string;
4194
4232
  related: string[] | null;
4195
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4196
4233
  publishedAt: string | null;
4197
4234
  };
4198
4235
  meta: object;
@@ -4200,6 +4237,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4200
4237
  list: _trpc_server.TRPCQueryProcedure<{
4201
4238
  input: {
4202
4239
  collectionId: string;
4240
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
4241
+ search?: string | undefined;
4242
+ order?: "recent" | "oldest" | "title" | undefined;
4203
4243
  skip?: number | undefined;
4204
4244
  limit?: number | undefined;
4205
4245
  };
@@ -4213,13 +4253,22 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4213
4253
  legacyExtra: Record<string, unknown> | null;
4214
4254
  createdBy: string | null;
4215
4255
  collectionId: string;
4256
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4216
4257
  title: string;
4217
4258
  related: string[] | null;
4218
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4219
4259
  publishedAt: string | null;
4220
4260
  }[];
4221
4261
  meta: object;
4222
4262
  }>;
4263
+ count: _trpc_server.TRPCQueryProcedure<{
4264
+ input: {
4265
+ collectionId: string;
4266
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
4267
+ search?: string | undefined;
4268
+ };
4269
+ output: number;
4270
+ meta: object;
4271
+ }>;
4223
4272
  create: _trpc_server.TRPCMutationProcedure<{
4224
4273
  input: {
4225
4274
  collectionId: string;
@@ -4241,9 +4290,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4241
4290
  legacyExtra: Record<string, unknown> | null;
4242
4291
  createdBy: string | null;
4243
4292
  collectionId: string;
4293
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4244
4294
  title: string;
4245
4295
  related: string[] | null;
4246
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4247
4296
  publishedAt: string | null;
4248
4297
  };
4249
4298
  meta: object;
@@ -4254,8 +4303,8 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4254
4303
  data: {
4255
4304
  data?: Record<string, unknown> | undefined;
4256
4305
  slug?: string | undefined;
4257
- title?: string | undefined;
4258
4306
  status?: "draft" | "waiting" | "ready" | "scheduled" | "published" | undefined;
4307
+ title?: string | undefined;
4259
4308
  publishedAt?: string | null | undefined;
4260
4309
  related?: string[] | undefined;
4261
4310
  };
@@ -4270,9 +4319,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4270
4319
  legacyExtra: Record<string, unknown> | null;
4271
4320
  createdBy: string | null;
4272
4321
  collectionId: string;
4322
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4273
4323
  title: string;
4274
4324
  related: string[] | null;
4275
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4276
4325
  publishedAt: string | null;
4277
4326
  };
4278
4327
  meta: object;
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" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
1181
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
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" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
1201
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
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
- name: string;
1896
1895
  id: string;
1896
+ name: string;
1897
1897
  createdAt: string;
1898
1898
  revokedAt: string | null;
1899
1899
  tokenHash: string;
1900
1900
  lastUsedAt: string | null;
1901
- }, "name" | "id" | "createdAt" | "revokedAt" | "lastUsedAt">[]>;
1901
+ }, "id" | "name" | "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>>;
1923
1924
  name: z.ZodString;
1924
1925
  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>>;
1956
1957
  name: z.ZodOptional<z.ZodString>;
1957
1958
  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;
@@ -2107,10 +2107,25 @@ declare class EntryRepository {
2107
2107
  private readonly db;
2108
2108
  constructor(db: StoreDb);
2109
2109
  list(collectionId: string): Promise<Entry[]>;
2110
- /** Admin listing: most recently updated first, paginated. */
2110
+ /**
2111
+ * What an admin listing keeps. Narrowing happens in SQL: the browser is never
2112
+ * handed rows in order to discard them, and a collection of several hundred
2113
+ * entries would not fit in it anyway.
2114
+ */
2115
+ private narrowing;
2116
+ /** The total a paginated listing is a window onto. Counted in SQL. */
2117
+ countMatching(options: {
2118
+ collectionId: string;
2119
+ status?: Entry['status'][];
2120
+ search?: string;
2121
+ }): Promise<number>;
2122
+ /** Admin listing: most recently updated first by default, paginated. */
2111
2123
  listPaginated(collectionId: string, options: {
2112
2124
  skip: number;
2113
2125
  limit: number;
2126
+ status?: Entry['status'][];
2127
+ search?: string;
2128
+ order?: 'recent' | 'oldest' | 'title';
2114
2129
  }): Promise<Entry[]>;
2115
2130
  listPublished(collectionId: string): Promise<Entry[]>;
2116
2131
  findBySlug(collectionId: string, slug: string): Promise<Entry | undefined>;
@@ -2123,8 +2138,8 @@ declare class EntryRepository {
2123
2138
  }
2124
2139
 
2125
2140
  declare const definitionCreateDto: z.ZodObject<{
2126
- name: z.ZodString;
2127
2141
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2142
+ name: z.ZodString;
2128
2143
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2129
2144
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2130
2145
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -2134,14 +2149,14 @@ declare const definitionCreateDto: z.ZodObject<{
2134
2149
  type: z.ZodEnum<{
2135
2150
  number: "number";
2136
2151
  boolean: "boolean";
2137
- text: "text";
2138
- "rich-text": "rich-text";
2152
+ json: "json";
2139
2153
  date: "date";
2154
+ text: "text";
2155
+ select: "select";
2140
2156
  media: "media";
2157
+ "rich-text": "rich-text";
2141
2158
  relation: "relation";
2142
- select: "select";
2143
2159
  steps: "steps";
2144
- json: "json";
2145
2160
  }>;
2146
2161
  required: z.ZodDefault<z.ZodBoolean>;
2147
2162
  hidden: z.ZodDefault<z.ZodBoolean>;
@@ -2154,9 +2169,9 @@ declare const definitionCreateDto: z.ZodObject<{
2154
2169
  in: {};
2155
2170
  }>;
2156
2171
  declare const definitionUpdateDto: z.ZodObject<{
2172
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2157
2173
  name: z.ZodOptional<z.ZodString>;
2158
2174
  slug: z.ZodOptional<z.ZodString>;
2159
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2160
2175
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2161
2176
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
2162
2177
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -2166,14 +2181,14 @@ declare const definitionUpdateDto: z.ZodObject<{
2166
2181
  type: z.ZodEnum<{
2167
2182
  number: "number";
2168
2183
  boolean: "boolean";
2169
- text: "text";
2170
- "rich-text": "rich-text";
2184
+ json: "json";
2171
2185
  date: "date";
2186
+ text: "text";
2187
+ select: "select";
2172
2188
  media: "media";
2189
+ "rich-text": "rich-text";
2173
2190
  relation: "relation";
2174
- select: "select";
2175
2191
  steps: "steps";
2176
- json: "json";
2177
2192
  }>;
2178
2193
  required: z.ZodDefault<z.ZodBoolean>;
2179
2194
  hidden: z.ZodDefault<z.ZodBoolean>;
@@ -2244,7 +2259,15 @@ declare class CollectionsService {
2244
2259
  listEntriesPaginated(collectionIdOrSlug: string, options?: {
2245
2260
  skip?: number;
2246
2261
  limit?: number;
2262
+ status?: Entry['status'][];
2263
+ search?: string;
2264
+ order?: 'recent' | 'oldest' | 'title';
2247
2265
  }): Promise<Entry[]>;
2266
+ /** The total a listing is a window onto, under the same narrowing. */
2267
+ countEntries(collectionIdOrSlug: string, options?: {
2268
+ status?: Entry['status'][];
2269
+ search?: string;
2270
+ }): Promise<number>;
2248
2271
  listPublishedEntries(collectionIdOrSlug: string): Promise<Entry[]>;
2249
2272
  createEntry(collectionIdOrSlug: string, input: EntryCreateDto, actorId?: string): Promise<Entry>;
2250
2273
  /** PARTIAL update: `data` is merged field by field with what already exists. */
@@ -2347,10 +2370,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2347
2370
  input: void;
2348
2371
  output: {
2349
2372
  type: "commune" | "intercommunality" | "syndicate" | "other";
2350
- name: string;
2373
+ description: string | null;
2351
2374
  id: number;
2375
+ name: string;
2352
2376
  slug: string;
2353
- description: string | null;
2354
2377
  address: {
2355
2378
  street?: string | undefined;
2356
2379
  postalCode?: string | undefined;
@@ -2381,10 +2404,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2381
2404
  };
2382
2405
  output: {
2383
2406
  type: "commune" | "intercommunality" | "syndicate" | "other";
2384
- name: string;
2407
+ description: string | null;
2385
2408
  id: number;
2409
+ name: string;
2386
2410
  slug: string;
2387
- description: string | null;
2388
2411
  address: {
2389
2412
  street?: string | undefined;
2390
2413
  postalCode?: string | undefined;
@@ -2402,9 +2425,9 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2402
2425
  update: _trpc_server.TRPCMutationProcedure<{
2403
2426
  input: {
2404
2427
  type?: "commune" | "intercommunality" | "syndicate" | "other" | undefined;
2428
+ description?: string | null | undefined;
2405
2429
  name?: string | undefined;
2406
2430
  slug?: string | undefined;
2407
- description?: string | null | undefined;
2408
2431
  address?: {
2409
2432
  street?: string | undefined;
2410
2433
  postalCode?: string | undefined;
@@ -2415,10 +2438,10 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
2415
2438
  };
2416
2439
  output: {
2417
2440
  type: "commune" | "intercommunality" | "syndicate" | "other";
2418
- name: string;
2441
+ description: string | null;
2419
2442
  id: number;
2443
+ name: string;
2420
2444
  slug: string;
2421
- description: string | null;
2422
2445
  address: {
2423
2446
  street?: string | undefined;
2424
2447
  postalCode?: string | undefined;
@@ -2792,13 +2815,13 @@ declare const apiTokensRouter: _trpc_server.TRPCBuiltRouter<{
2792
2815
  list: _trpc_server.TRPCQueryProcedure<{
2793
2816
  input: void;
2794
2817
  output: Pick<{
2795
- name: string;
2796
2818
  id: string;
2819
+ name: string;
2797
2820
  createdAt: string;
2798
2821
  revokedAt: string | null;
2799
2822
  tokenHash: string;
2800
2823
  lastUsedAt: string | null;
2801
- }, "name" | "id" | "createdAt" | "revokedAt" | "lastUsedAt">[];
2824
+ }, "id" | "name" | "createdAt" | "revokedAt" | "lastUsedAt">[];
2802
2825
  meta: object;
2803
2826
  }>;
2804
2827
  /** The plaintext token is returned ONCE — only its hash is stored. */
@@ -2943,18 +2966,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2943
2966
  metaData?: Record<string, unknown> | undefined;
2944
2967
  };
2945
2968
  output: {
2946
- filename: string;
2947
2969
  id: string;
2948
2970
  updatedBy: string | null;
2949
2971
  legacyExtra: Record<string, unknown> | null;
2950
2972
  createdAt: string;
2951
2973
  updatedAt: string;
2974
+ filename: string;
2952
2975
  mime: string;
2953
- size: number;
2976
+ metaData: Record<string, unknown> | null;
2954
2977
  alt: string | null;
2978
+ size: number;
2955
2979
  caption: string | null;
2956
2980
  objects: Record<string, unknown>;
2957
- metaData: Record<string, unknown> | null;
2958
2981
  createdBy: string | null;
2959
2982
  };
2960
2983
  meta: object;
@@ -2962,18 +2985,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2962
2985
  list: _trpc_server.TRPCQueryProcedure<{
2963
2986
  input: void;
2964
2987
  output: ({
2965
- filename: string;
2966
2988
  id: string;
2967
2989
  updatedBy: string | null;
2968
2990
  legacyExtra: Record<string, unknown> | null;
2969
2991
  createdAt: string;
2970
2992
  updatedAt: string;
2993
+ filename: string;
2971
2994
  mime: string;
2972
- size: number;
2995
+ metaData: Record<string, unknown> | null;
2973
2996
  alt: string | null;
2997
+ size: number;
2974
2998
  caption: string | null;
2975
2999
  objects: Record<string, unknown>;
2976
- metaData: Record<string, unknown> | null;
2977
3000
  createdBy: string | null;
2978
3001
  } & {
2979
3002
  objects: Record<string, string>;
@@ -2985,18 +3008,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2985
3008
  id: string;
2986
3009
  };
2987
3010
  output: {
2988
- filename: string;
2989
3011
  id: string;
2990
3012
  updatedBy: string | null;
2991
3013
  legacyExtra: Record<string, unknown> | null;
2992
3014
  createdAt: string;
2993
3015
  updatedAt: string;
3016
+ filename: string;
2994
3017
  mime: string;
2995
- size: number;
3018
+ metaData: Record<string, unknown> | null;
2996
3019
  alt: string | null;
3020
+ size: number;
2997
3021
  caption: string | null;
2998
3022
  objects: Record<string, unknown>;
2999
- metaData: Record<string, unknown> | null;
3000
3023
  createdBy: string | null;
3001
3024
  } & {
3002
3025
  objects: Record<string, string>;
@@ -3013,18 +3036,18 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3013
3036
  };
3014
3037
  };
3015
3038
  output: {
3016
- filename: string;
3017
3039
  id: string;
3018
3040
  updatedBy: string | null;
3019
3041
  legacyExtra: Record<string, unknown> | null;
3020
3042
  createdAt: string;
3021
3043
  updatedAt: string;
3044
+ filename: string;
3022
3045
  mime: string;
3023
- size: number;
3046
+ metaData: Record<string, unknown> | null;
3024
3047
  alt: string | null;
3048
+ size: number;
3025
3049
  caption: string | null;
3026
3050
  objects: Record<string, unknown>;
3027
- metaData: Record<string, unknown> | null;
3028
3051
  createdBy: string | null;
3029
3052
  };
3030
3053
  meta: object;
@@ -3108,10 +3131,10 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3108
3131
  list: _trpc_server.TRPCQueryProcedure<{
3109
3132
  input: void;
3110
3133
  output: {
3111
- name: string;
3134
+ description: string | null;
3112
3135
  id: string;
3136
+ name: string;
3113
3137
  slug: string;
3114
- description: string | null;
3115
3138
  updatedBy: string | null;
3116
3139
  legacyExtra: Record<string, unknown> | null;
3117
3140
  createdAt: string;
@@ -3120,7 +3143,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3120
3143
  fields: {
3121
3144
  name: string;
3122
3145
  label: string;
3123
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3146
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3124
3147
  required: boolean;
3125
3148
  hidden: boolean;
3126
3149
  options?: string[] | undefined;
@@ -3137,10 +3160,10 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3137
3160
  idOrSlug: string;
3138
3161
  };
3139
3162
  output: {
3140
- name: string;
3163
+ description: string | null;
3141
3164
  id: string;
3165
+ name: string;
3142
3166
  slug: string;
3143
- description: string | null;
3144
3167
  updatedBy: string | null;
3145
3168
  legacyExtra: Record<string, unknown> | null;
3146
3169
  createdAt: string;
@@ -3149,7 +3172,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3149
3172
  fields: {
3150
3173
  name: string;
3151
3174
  label: string;
3152
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3175
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3153
3176
  required: boolean;
3154
3177
  hidden: boolean;
3155
3178
  options?: string[] | undefined;
@@ -3167,7 +3190,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3167
3190
  fields: {
3168
3191
  name: string;
3169
3192
  label: string;
3170
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3193
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3171
3194
  required?: boolean | undefined;
3172
3195
  hidden?: boolean | undefined;
3173
3196
  options?: string[] | undefined;
@@ -3180,10 +3203,10 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3180
3203
  slug?: string | undefined;
3181
3204
  };
3182
3205
  output: {
3183
- name: string;
3206
+ description: string | null;
3184
3207
  id: string;
3208
+ name: string;
3185
3209
  slug: string;
3186
- description: string | null;
3187
3210
  updatedBy: string | null;
3188
3211
  legacyExtra: Record<string, unknown> | null;
3189
3212
  createdAt: string;
@@ -3192,7 +3215,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3192
3215
  fields: {
3193
3216
  name: string;
3194
3217
  label: string;
3195
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3218
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3196
3219
  required: boolean;
3197
3220
  hidden: boolean;
3198
3221
  options?: string[] | undefined;
@@ -3208,16 +3231,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3208
3231
  input: {
3209
3232
  id: string;
3210
3233
  data: {
3234
+ description?: string | null | undefined;
3211
3235
  name?: string | undefined;
3212
3236
  slug?: string | undefined;
3213
- description?: string | null | undefined;
3214
3237
  editor?: Record<string, unknown> | null | undefined;
3215
3238
  display?: Record<string, unknown> | null | undefined;
3216
3239
  headings?: Record<string, unknown> | null | undefined;
3217
3240
  fields?: {
3218
3241
  name: string;
3219
3242
  label: string;
3220
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3243
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3221
3244
  required?: boolean | undefined;
3222
3245
  hidden?: boolean | undefined;
3223
3246
  options?: string[] | undefined;
@@ -3226,10 +3249,10 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3226
3249
  };
3227
3250
  };
3228
3251
  output: {
3229
- name: string;
3252
+ description: string | null;
3230
3253
  id: string;
3254
+ name: string;
3231
3255
  slug: string;
3232
- description: string | null;
3233
3256
  updatedBy: string | null;
3234
3257
  legacyExtra: Record<string, unknown> | null;
3235
3258
  createdAt: string;
@@ -3238,7 +3261,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3238
3261
  fields: {
3239
3262
  name: string;
3240
3263
  label: string;
3241
- type: "number" | "boolean" | "text" | "rich-text" | "date" | "media" | "relation" | "select" | "steps" | "json";
3264
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3242
3265
  required: boolean;
3243
3266
  hidden: boolean;
3244
3267
  options?: string[] | undefined;
@@ -3296,9 +3319,13 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3296
3319
  };
3297
3320
  meta: object;
3298
3321
  }>;
3322
+ /** Narrowing is optional: a caller that ignores it keeps the old behaviour. */
3299
3323
  list: _trpc_server.TRPCQueryProcedure<{
3300
3324
  input: {
3301
3325
  collectionId: string;
3326
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
3327
+ search?: string | undefined;
3328
+ order?: "title" | "recent" | "oldest" | undefined;
3302
3329
  skip?: number | undefined;
3303
3330
  limit?: number | undefined;
3304
3331
  };
@@ -3319,6 +3346,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3319
3346
  }[];
3320
3347
  meta: object;
3321
3348
  }>;
3349
+ /** The total a listing is a window onto, under the same narrowing. */
3350
+ count: _trpc_server.TRPCQueryProcedure<{
3351
+ input: {
3352
+ collectionId: string;
3353
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
3354
+ search?: string | undefined;
3355
+ };
3356
+ output: number;
3357
+ meta: object;
3358
+ }>;
3322
3359
  create: _trpc_server.TRPCMutationProcedure<{
3323
3360
  input: {
3324
3361
  collectionId: string;
@@ -4190,9 +4227,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4190
4227
  legacyExtra: Record<string, unknown> | null;
4191
4228
  createdBy: string | null;
4192
4229
  collectionId: string;
4230
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4193
4231
  title: string;
4194
4232
  related: string[] | null;
4195
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4196
4233
  publishedAt: string | null;
4197
4234
  };
4198
4235
  meta: object;
@@ -4200,6 +4237,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4200
4237
  list: _trpc_server.TRPCQueryProcedure<{
4201
4238
  input: {
4202
4239
  collectionId: string;
4240
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
4241
+ search?: string | undefined;
4242
+ order?: "recent" | "oldest" | "title" | undefined;
4203
4243
  skip?: number | undefined;
4204
4244
  limit?: number | undefined;
4205
4245
  };
@@ -4213,13 +4253,22 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4213
4253
  legacyExtra: Record<string, unknown> | null;
4214
4254
  createdBy: string | null;
4215
4255
  collectionId: string;
4256
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4216
4257
  title: string;
4217
4258
  related: string[] | null;
4218
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4219
4259
  publishedAt: string | null;
4220
4260
  }[];
4221
4261
  meta: object;
4222
4262
  }>;
4263
+ count: _trpc_server.TRPCQueryProcedure<{
4264
+ input: {
4265
+ collectionId: string;
4266
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
4267
+ search?: string | undefined;
4268
+ };
4269
+ output: number;
4270
+ meta: object;
4271
+ }>;
4223
4272
  create: _trpc_server.TRPCMutationProcedure<{
4224
4273
  input: {
4225
4274
  collectionId: string;
@@ -4241,9 +4290,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4241
4290
  legacyExtra: Record<string, unknown> | null;
4242
4291
  createdBy: string | null;
4243
4292
  collectionId: string;
4293
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4244
4294
  title: string;
4245
4295
  related: string[] | null;
4246
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4247
4296
  publishedAt: string | null;
4248
4297
  };
4249
4298
  meta: object;
@@ -4254,8 +4303,8 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4254
4303
  data: {
4255
4304
  data?: Record<string, unknown> | undefined;
4256
4305
  slug?: string | undefined;
4257
- title?: string | undefined;
4258
4306
  status?: "draft" | "waiting" | "ready" | "scheduled" | "published" | undefined;
4307
+ title?: string | undefined;
4259
4308
  publishedAt?: string | null | undefined;
4260
4309
  related?: string[] | undefined;
4261
4310
  };
@@ -4270,9 +4319,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4270
4319
  legacyExtra: Record<string, unknown> | null;
4271
4320
  createdBy: string | null;
4272
4321
  collectionId: string;
4322
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4273
4323
  title: string;
4274
4324
  related: string[] | null;
4275
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4276
4325
  publishedAt: string | null;
4277
4326
  };
4278
4327
  meta: object;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{homedir as bt}from"node:os";import{join as z}from"node:path";import{z as s}from"zod";import{Database as At}from"bun:sqlite";import{mkdirSync as Ut,existsSync as Ot}from"node:fs";import{drizzle as Nt}from"drizzle-orm/bun-sqlite";import{migrate as It}from"drizzle-orm/bun-sqlite/migrator";import{sqliteTable as I,text as o,integer as ue,uniqueIndex as Dt}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as ee,FIELD_TYPES as pe}from"./domains/collections/constants.mjs";import{fieldDefinitionSchema as K,buildDataSchema as me}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS}from"./domains/collections/utils.mjs";import{sql as q,eq as a,and as M,isNull as L,gt as te,desc as R,or as ye,lt as he,isNotNull as ge}from"drizzle-orm";import{S3Client as Mt,PutObjectCommand as we,HeadObjectCommand as kt,DeleteObjectsCommand as Tt,GetObjectCommand as xt}from"@aws-sdk/client-s3";import{getSignedUrl as fe}from"@aws-sdk/s3-request-presigner";import{initTRPC as Rt,TRPCError as H}from"@trpc/server";import{randomBytes as ie,createHash as Ct}from"node:crypto";import{SignJWT as Bt,jwtVerify as $t}from"jose";import{consola as Ee}from"consola";import{createInsertSchema as ne,createUpdateSchema as F}from"drizzle-zod";import{nanoid as _e}from"nanoid";const B=s.string().min(1),jt=s.object({COMMUN_DATA_DIR:s.string().default(z(bt(),".commun")),COMMUN_MIGRATIONS_DIR:s.string().optional(),COMMUN_S3_ENDPOINT:s.string().optional(),COMMUN_S3_REGION:s.string().default("fr-par"),COMMUN_S3_BUCKET:B,COMMUN_S3_ACCESS_KEY:B,COMMUN_S3_SECRET_KEY:B,COMMUN_EMAIL_WEBHOOK_URL:B,COMMUN_EMAIL_WEBHOOK_TOKEN:s.string().optional(),COMMUN_ADMIN_URL:s.string().optional(),COMMUN_JWT_SECRET:B});function ve(i=process.env){return jt.parse({COMMUN_DATA_DIR:i.COMMUN_DATA_DIR,COMMUN_MIGRATIONS_DIR:i.COMMUN_MIGRATIONS_DIR,COMMUN_S3_ENDPOINT:i.COMMUN_S3_ENDPOINT,COMMUN_S3_REGION:i.COMMUN_S3_REGION,COMMUN_S3_BUCKET:i.COMMUN_S3_BUCKET,COMMUN_S3_ACCESS_KEY:i.COMMUN_S3_ACCESS_KEY,COMMUN_S3_SECRET_KEY:i.COMMUN_S3_SECRET_KEY,COMMUN_EMAIL_WEBHOOK_URL:i.COMMUN_EMAIL_WEBHOOK_URL,COMMUN_EMAIL_WEBHOOK_TOKEN:i.COMMUN_EMAIL_WEBHOOK_TOKEN,COMMUN_ADMIN_URL:i.COMMUN_ADMIN_URL,COMMUN_JWT_SECRET:i.COMMUN_JWT_SECRET})}const k=()=>o("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),D=()=>o("created_at").notNull().$defaultFn(()=>new Date().toISOString()),$=()=>o("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),W=()=>o("legacy_extra",{mode:"json"}).$type(),Pt=()=>o("status",{enum:ee}).notNull().default("draft"),zt=()=>o("published_at"),Se=s.object({street:s.string().optional(),postalCode:s.string().optional(),city:s.string().optional()}),U=I("organization",{id:ue("id").primaryKey().default(1),name:o("name").notNull(),type:o("type",{enum:["commune","intercommunality","syndicate","other"]}).notNull().default("commune"),slug:o("slug").notNull(),description:o("description"),address:o("address",{mode:"json"}).$type(),deployment:o("deployment",{mode:"json"}).$type(),settings:o("settings",{mode:"json"}).$type(),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:$()}),u=I("users",{id:k(),email:o("email").notNull().unique(),name:o("name").notNull(),passwordHash:o("password_hash"),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),createdAt:D(),updatedAt:$()}),l=I("sessions",{id:k(),userId:o("user_id").notNull().references(()=>u.id,{onDelete:"cascade"}),expiresAt:o("expires_at").notNull(),revokedAt:o("revoked_at"),ua:o("ua"),ip:o("ip"),createdAt:D()}),v=I("invitations",{id:k(),email:o("email").notNull(),tokenHash:o("token_hash").notNull().unique(),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),expiresAt:o("expires_at").notNull(),usedAt:o("used_at"),createdAt:D()}),y=I("api_tokens",{id:k(),name:o("name").notNull(),tokenHash:o("token_hash").notNull().unique(),lastUsedAt:o("last_used_at"),revokedAt:o("revoked_at"),createdAt:D()}),E=I("media",{id:k(),filename:o("filename").notNull(),mime:o("mime").notNull(),size:ue("size").notNull(),alt:o("alt"),caption:o("caption"),objects:o("objects",{mode:"json"}).$type().notNull(),metaData:o("meta_data",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:$()}),h=I("collection_definitions",{id:k(),name:o("name").notNull(),slug:o("slug").notNull().unique(),description:o("description"),fields:o("fields",{mode:"json"}).$type().notNull(),editor:o("editor",{mode:"json"}).$type(),display:o("display",{mode:"json"}).$type(),headings:o("headings",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:W(),createdAt:D(),updatedAt:$()}),d=I("entries",{id:k(),collectionId:o("collection_id").notNull().references(()=>h.id,{onDelete:"cascade"}),title:o("title").notNull(),slug:o("slug").notNull(),data:o("data",{mode:"json"}).$type().notNull(),related:o("related",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),status:Pt(),publishedAt:zt(),legacyExtra:W(),createdAt:D(),updatedAt:$()},i=>[Dt("entries_slug_unique").on(i.collectionId,i.slug)]),Kt={__proto__:null,FIELD_TYPES:pe,PUBLICATION_STATUSES:ee,addressSchema:Se,apiTokens:y,collectionDefinitions:h,entries:d,fieldDefinitionSchema:K,invitations:v,media:E,organization:U,sessions:l,users:u};function qt(){const i=import.meta.dir;return i?z(i,"..","..","..","drizzle"):void 0}function be(i,e){const t=e??qt();Ut(i,{recursive:!0});const n=new At(z(i,"commun.db"));n.exec("PRAGMA journal_mode=WAL"),n.exec("PRAGMA foreign_keys=ON"),n.exec("PRAGMA busy_timeout=5000");const r=Nt({client:n,schema:Kt});return t&&Ot(z(t,"meta","_journal.json"))&&It(r,{migrationsFolder:t}),r}class Z{constructor(e){this.config=e}static fromEnv(e){return new Z({url:e.COMMUN_EMAIL_WEBHOOK_URL,token:e.COMMUN_EMAIL_WEBHOOK_TOKEN})}async sendEvent(e){const t=await fetch(this.config.url,{method:"POST",headers:{"content-type":"application/json",...this.config.token?{authorization:`Bearer ${this.config.token}`}:{}},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`email webhook ${t.status}: ${(await t.text()).slice(0,200)}`)}}class Ae{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(q`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Ue=168*3600,Lt="medias/";class Oe{constructor(e){this.config=e,this.client=new Mt({region:e.region,...e.endpoint?{endpoint:e.endpoint,forcePathStyle:!0}:{},credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,n){return fe(this.client,new we({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:n}),{expiresIn:Ue})}async put(e,t,n){await this.client.send(new we({Bucket:this.config.bucket,Key:e,Body:t,ContentType:n}))}async head(e){try{return{size:(await this.client.send(new kt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Tt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Lt)?Promise.resolve(this.publicUrl(e)):fe(this.client,new xt({Bucket:this.config.bucket,Key:e}),{expiresIn:Ue})}publicUrl(e){const t=(this.config.endpoint??`https://s3.${this.config.region}.scw.cloud`).replace(/\/+$/,""),n=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${n}`}}function Ne(i){return new Oe({endpoint:i.COMMUN_S3_ENDPOINT||void 0,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const w={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class Q extends Error{}function g(i,e){return class extends Q{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const se=Rt.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof Q?{type:t.type}:{}}}}}),b=se.router,Ht=se.procedure,Ie=se.middleware,Ft=Ie(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof Q)throw new H({code:t.trpcCode,message:t.message,cause:t})}return e}),C=Ht.use(Ft),De=i=>Ie(({ctx:e,next:t})=>{if(!e.session)throw new H({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new H({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),p=C.use(De()),_=C.use(De("admin")),Wt=b({ping:C.query(({ctx:i})=>i.services.health.check())}),Me=s.object({email:s.email(),password:s.string().min(1)}),ke=s.object({token:s.string().min(1),name:s.string().min(1).optional(),password:s.string().min(10)}),Te=s.object({email:s.email()}),xe=s.object({email:s.email(),role:s.enum(["admin","redacteur"])}),Re=s.object({id:s.string(),data:s.object({name:s.string().min(1).optional(),role:s.enum(["admin","redacteur"]).optional(),email:s.email().optional()})}),T=({id:i,email:e,name:t,role:n})=>({id:i,email:e,name:t,role:n}),Ce=s.object({name:s.string().min(1)});class Be{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(u).where(a(u.email,e)).get()}async findUserById(e){return this.db.select().from(u).where(a(u.id,e)).get()}async listUsers(){return this.db.select().from(u).all()}async hasAnyUser(){return this.db.select({id:u.id}).from(u).limit(1).all().length>0}async deleteUser(e){this.db.delete(u).where(a(u.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(u).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(a(u.id,t.id)).returning().get():this.db.insert(u).values(e).returning().get()}async insertSession(e){return this.db.insert(l).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:l,user:u}).from(l).innerJoin(u,a(u.id,l.userId)).where(M(a(l.id,e),L(l.revokedAt),te(l.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(l).set({revokedAt:t}).where(a(l.id,e)).run()}async findSessionById(e){return this.db.select().from(l).where(a(l.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(l).where(M(a(l.userId,e),L(l.revokedAt),te(l.expiresAt,t))).orderBy(R(l.createdAt)).all()}async updateUser(e,t){return this.db.update(u).set(t).where(a(u.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(v).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(v).where(M(a(v.tokenHash,e),L(v.usedAt),te(v.expiresAt,t))).get()}async markInvitationUsed(e,t){this.db.update(v).set({usedAt:t}).where(a(v.id,e)).run()}async insertApiToken(e){return this.db.insert(y).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(y).where(M(a(y.tokenHash,e),L(y.revokedAt))).get()}async touchApiToken(e,t){this.db.update(y).set({lastUsedAt:t}).where(a(y.id,e)).run()}async revokeApiToken(e,t){this.db.update(y).set({revokedAt:t}).where(a(y.id,e)).run()}async listApiTokens(){return this.db.select({id:y.id,name:y.name,lastUsedAt:y.lastUsedAt,revokedAt:y.revokedAt,createdAt:y.createdAt}).from(y).orderBy(R(y.createdAt)).all()}async purgeExpired(e){this.db.delete(l).where(ye(he(l.expiresAt,e),ge(l.revokedAt))).run(),this.db.delete(v).where(ye(he(v.expiresAt,e),ge(v.usedAt))).run()}}const re=g("user-not-found-error",w.NOT_FOUND),$e=g("session-not-found-error",w.NOT_FOUND),je=g("invitation-invalid-error",w.BAD_REQUEST),Pe=g("cannot-remove-self-error",w.BAD_REQUEST),ze=g("too-many-attempts-error",w.TOO_MANY_REQUESTS),j=i=>Ct("sha256").update(i).digest("hex"),O=()=>new Date().toISOString(),Qt=720*3600*1e3,Ke=168*3600*1e3,Yt=Bun.password.hashSync("commun-dummy-password-for-timing"),Gt=5*6e4,Jt=10,P=new Map,qe=i=>{const e=Date.now(),t=(P.get(i)??[]).filter(n=>e-n<Gt);return t.length?P.set(i,t):P.delete(i),t},Vt=i=>qe(i).length>=Jt,Zt=i=>{P.set(i,[...qe(i),Date.now()])},Xt=i=>P.delete(i);class Le{constructor(e,t={}){this.repository=e,this.options=t}jwtKey(){if(!this.options.jwtSecret)throw new Error("COMMUN_JWT_SECRET manquant \u2014 requis pour signer les sessions (fail-fast au boot)");return new TextEncoder().encode(this.options.jwtSecret)}async sendEmailEvent(e){try{await this.options.email?.sendEvent(e)}catch(t){Ee.warn(`[email] \xE9chec d'\xE9mission ${e.eventName} \u2192 ${e.email}: ${String(t)}`)}}hashPassword(e){return Bun.password.hash(e)}verifyPassword(e,t){return Bun.password.verify(e,t)}async login(e,t,n){const r=e.toLowerCase();if(Vt(r))throw new ze;const c=await this.repository.findUserByEmail(r),f=await this.verifyPassword(t,c?.passwordHash??Yt);return!c?.passwordHash||!f?(Zt(r),null):(Xt(r),this.createSession(c,n))}async createSession(e,t){const n=new Date(Date.now()+Qt).toISOString(),r=await this.repository.insertSession({userId:e.id,expiresAt:n,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Bt({session:r.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(n)).sign(this.jwtKey()),session:{sessionId:r.id,user:e,expiresAt:n}}}async verifySession(e){let t;try{const{payload:r}=await $t(e,this.jwtKey());if(typeof r.session!="string")return null;t=r.session}catch{return null}const n=await this.repository.findActiveSessionWithUser(t,O());return n?{sessionId:n.session.id,user:n.user,expiresAt:n.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,O())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,O())).map(n=>({id:n.id,createdAt:n.createdAt,expiresAt:n.expiresAt,ua:n.ua,ip:n.ip,current:n.id===t}))}async revokeOwnSession(e,t){const n=await this.repository.findSessionById(t);if(!n||n.userId!==e)throw new $e(`session not found: ${t}`);await this.repository.revokeSession(t,O())}async purgeExpired(){await this.repository.purgeExpired(O())}async createInvitation(e){const t=ie(32).toString("base64url"),n=new Date(Date.now()+Ke).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:j(t),expiresAt:n}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:n}}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const n=ie(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:j(n),expiresAt:new Date(Date.now()+Ke).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${n}`}})}async acceptInvitation(e,t){const n=await this.repository.findValidInvitation(j(e),O());if(!n)throw new je;const r=await this.repository.findUserByEmail(n.email),c=t.name?.trim()||r?.name||n.email.split("@")[0]||"Membre",f=await this.repository.activateUser({email:n.email,name:c,passwordHash:await this.hashPassword(t.password),role:n.role});return await this.repository.markInvitationUsed(n.id,O()),f}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new re(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new Pe;await this.repository.deleteUser(t)}async updateUser(e,t){const n=await this.repository.updateUser(e,t);if(!n)throw new re(`user not found: ${e}`);return n}async createApiToken(e){const t=`commun_${ie(24).toString("base64url")}`,n=await this.repository.insertApiToken({name:e,tokenHash:j(t)});return{token:t,record:n}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(j(e));return t?(await this.repository.touchApiToken(t.id,O()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,O())}async listApiTokens(){return this.repository.listApiTokens()}}const He=b({login:C.input(Me).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new H({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:T(t.session.user)}}),logout:p.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:p.query(({ctx:i})=>({user:T(i.session.user)})),sessions:b({list:p.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:p.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:C.input(ke).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:T(t)}}),requestPasswordReset:C.input(Te).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Fe=b({list:_.query(async({ctx:i})=>(await i.services.users.listUsers()).map(T)),directory:p.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:_.input(s.object({id:s.string()})).query(async({ctx:i,input:e})=>T(await i.services.users.getUser(e.id))),invite:_.input(xe).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:_.input(Re).mutation(async({ctx:i,input:e})=>T(await i.services.users.updateUser(e.id,e.data))),remove:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),We=b({list:_.query(({ctx:i})=>i.services.users.listApiTokens()),create:_.input(Ce).mutation(async({ctx:i,input:e})=>{const{token:t,record:n}=await i.services.users.createApiToken(e.name);return{token:t,id:n.id,name:n.name}}),revoke:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),Qe={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},ei={createdBy:!0,updatedBy:!0},oe={...Qe,...ei},Ye={...Qe,updatedBy:!0},Ge=ne(U).omit(Ye),Je=F(U).omit(Ye);class Ve{constructor(e){this.db=e}async get(){return this.db.select().from(U).where(a(U.id,1)).get()}async insert(e){return this.db.insert(U).values({...e,id:1}).returning().get()}async update(e){return this.db.update(U).set(e).where(a(U.id,1)).returning().get()}}const Ze=g("organization-not-initialized-error",w.NOT_FOUND),Xe=g("organization-already-initialized-error",w.BAD_REQUEST),et=g("deploy-hook-missing-error",w.BAD_REQUEST),ae=g("deploy-failed-error",w.INTERNAL_SERVER_ERROR),ti=3e4;class tt{constructor(e,t={}){this.repository=e,this.options=t}async get(){return await this.repository.get()??null}async init(e){if(await this.repository.get())throw new Xe;return this.repository.insert(e)}async update(e,t){const n=await this.repository.update({...e,updatedBy:t??null});if(!n)throw new Ze;return n}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new et;const t=this.options.fetchImpl??fetch;let n;try{n=await t(e,{signal:AbortSignal.timeout(ti)})}catch(r){throw new ae(`deploy hook unreachable: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw new ae(`deploy hook: ${n.status} ${n.statusText}`);return{status:n.status}}}const it=b({get:p.query(({ctx:i})=>i.services.organization.get()),init:_.input(Ge).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:_.input(Je).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:p.mutation(({ctx:i})=>i.services.organization.deploy())}),nt=s.object({filename:s.string().min(1),mime:s.string().min(1),metaData:s.record(s.string(),s.string()).optional()}),st=s.object({key:s.string().min(1),filename:s.string().min(1),mime:s.string().min(1),alt:s.string().optional(),metaData:s.record(s.string(),s.unknown()).optional()}),rt=F(E).pick({alt:!0,caption:!0,filename:!0});class ot{constructor(e){this.db=e}async insert(e){return this.db.insert(E).values(e).returning().get()}async findById(e){return this.db.select().from(E).where(a(E.id,e)).get()}async list(){return this.db.select().from(E).orderBy(R(E.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(E).where(q`json_extract(${E.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(E).set(t).where(a(E.id,e)).returning().get()}async delete(e){this.db.delete(E).where(a(E.id,e)).run()}}const Y=g("media-not-found-error",w.NOT_FOUND),de=g("unsupported-mime-error",w.BAD_REQUEST),at=g("upload-incomplete-error",w.BAD_REQUEST),ce=new Set(["image/jpeg","image/png","image/webp","image/gif","application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet"]),ii=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],le=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",dt="medias/";class ct{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,n){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const r=`${dt}${_e(10)}/${le(e)}`;return{key:r,url:await this.storage.presignedPutUrl(r,t,n)}}async finalize(e,t){const n=await this.storage.head(e.key);if(!n)throw new at(`object not found in storage: ${e.key}`);const r=await this.repository.insert({filename:le(e.filename),mime:e.mime,size:n.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Ee.info(`[media] resize \xE0 impl\xE9menter pour ${r.id} (${ii.join(", ")})`),r}async uploadDirect(e,t,n,r,c){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const f=`${dt}${_e(10)}/${le(e)}`;return await this.storage.put(f,n,t),this.finalize({key:f,filename:e,mime:t,metaData:r},c)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,n){const r=await this.repository.update(e,{...t,updatedBy:n??null});if(!r)throw new Y(`media not found: ${e}`);return r}async remove(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);const n=t.objects;await this.storage.remove([n.original,...Object.values(n.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async objectUrls(e){const t=e.objects,n={original:await this.storage.url(t.original)};for(const[r,c]of Object.entries(t.variants??{}))n[r]=await this.storage.url(c);return n}}const lt=b({requestUpload:p.input(nt).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:p.input(st).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:p.query(({ctx:i})=>i.services.media.listResolved()),get:p.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:p.input(s.object({id:s.string(),data:rt})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:p.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))}),ut=ne(h).omit(oe).extend({fields:s.array(K).min(1),slug:s.string().optional()}),pt=F(h).omit(oe).extend({fields:s.array(K).min(1).optional()}),mt={...oe,related:!0,collectionId:!0},yt=ne(d).omit(mt).extend({slug:s.string().optional()}),ht=F(d).omit(mt).extend({related:s.array(s.string()).optional()});class gt{constructor(e){this.db=e}async list(){return this.db.select().from(h).all()}async findBySlug(e){return this.db.select().from(h).where(a(h.slug,e)).get()}async findById(e){return this.db.select().from(h).where(a(h.id,e)).get()}async findByLegacyId(e){return this.db.select().from(h).where(q`json_extract(${h.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(h).values(e).returning().get()}async update(e,t){return this.db.update(h).set(t).where(a(h.id,e)).returning().get()}async delete(e){return this.db.delete(h).where(a(h.id,e)).returning().get()}}class wt{constructor(e){this.db=e}async list(e){return this.db.select().from(d).where(a(d.collectionId,e)).orderBy(R(d.updatedAt)).all()}async listPaginated(e,t){return this.db.select().from(d).where(a(d.collectionId,e)).orderBy(R(d.updatedAt)).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(d).where(M(a(d.collectionId,e),a(d.status,"published"))).orderBy(R(d.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(d).where(M(a(d.collectionId,e),a(d.slug,t))).get()}async findById(e){return this.db.select().from(d).where(a(d.id,e)).get()}async findByDataField(e,t,n){return this.db.select().from(d).where(M(a(d.collectionId,e),q`json_extract(${d.data}, ${`$.${t}`}) = ${n}`)).get()}async insert(e){return this.db.insert(d).values(e).returning().get()}async update(e,t){return this.db.update(d).set(t).where(a(d.id,e)).returning().get()}async delete(e){return this.db.delete(d).where(a(d.id,e)).returning().get()}}const G=g("collection-not-found-error",w.NOT_FOUND),J=g("entry-not-found-error",w.NOT_FOUND),ft=g("invalid-entry-data-error",w.BAD_REQUEST),Et=g("duplicate-slug-error",w.BAD_REQUEST);function _t(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function V(i,e){const t=[];for(const n of i){if(n.type!=="relation")continue;const r=e[n.name];typeof r=="string"&&r?t.push(r):Array.isArray(r)&&t.push(...r.filter(c=>typeof c=="string"))}return[...new Set(t)]}class vt{constructor(e,t,n){this.definitions=e,this.entries=t,this.media=n}async listDefinitions(){return this.definitions.list()}async getDefinition(e){const t=await this.definitions.findBySlug(e)??await this.definitions.findById(e);if(!t)throw new G(`collection not found: ${e}`);return t}async createDefinition(e,t){return this.definitions.insert({...e,slug:e.slug||await this.uniqueDefinitionSlug(_t(e.name)),createdBy:t??null,updatedBy:t??null})}async updateDefinition(e,t,n){const r=await this.definitions.update(e,{...t,updatedBy:n??null});if(!r)throw new G(`collection not found: ${e}`);return r}async removeDefinition(e){if(!await this.definitions.delete(e))throw new G(`collection not found: ${e}`)}validateData(e,t){const n=me(e.fields).safeParse(t);if(!n.success)throw new ft(`invalid data for collection ${e.slug}: ${n.error.message}`);return n.data}async listEntries(e){return this.entries.list((await this.getDefinition(e)).id)}async getEntry(e){const t=await this.entries.findById(e);if(!t)throw new J(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){const n=await this.getDefinition(e);return this.entries.listPaginated(n.id,{skip:t.skip??0,limit:t.limit??20})}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,n){const r=await this.getDefinition(e),c=this.validateData(r,t.data),f=await this.uniqueEntrySlug(r.id,t.slug||_t(t.title)),m=await this.entries.insert({...t,slug:f,data:c,collectionId:r.id,createdBy:n??null,updatedBy:n??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(r,m.id,[],V(r.fields,c)),m}async updateEntry(e,t,n){const r=await this.entries.findById(e);if(!r)throw new J(`entry not found: ${e}`);const c=await this.getDefinition(r.collectionId),f=new Set(c.fields.map(S=>S.name)),m=Object.fromEntries(Object.entries(r.data??{}).filter(([S])=>!f.has(S))),A=t.data?{...r.data,...t.data}:r.data,N=Object.fromEntries(Object.entries(A).filter(([S])=>f.has(S)||S in(t.data??{}))),x=t.data?{...m,...this.validateData(c,N)}:void 0,X={...t,updatedBy:n??null};x&&(X.data=x),t.status==="published"&&!t.publishedAt&&(X.publishedAt=new Date().toISOString());try{const S=await this.entries.update(e,X);return x&&await this.linkRelations(c,e,V(c.fields,r.data),V(c.fields,x)),t.related&&await this.linkRelations(c,e,r.related??[],t.related),S}catch(S){throw this.mapSlugConflict(S,c.slug,t.slug??r.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new J(`entry not found: ${e}`);const n=await this.getDefinition(t.collectionId);await this.linkRelations(n,e,V(n.fields,t.data),[]),await this.entries.delete(e)}mapSlugConflict(e,t,n){return e instanceof Error&&e.message.includes("UNIQUE constraint failed")&&e.message.includes("entries.slug")?new Et(`le slug "${n}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let n=t;for(let r=1;await this.entries.findBySlug(e,n);r++)n=`${t}-${r}`;return n}async uniqueDefinitionSlug(e){let t=e;for(let n=1;await this.definitions.findBySlug(t);n++)t=`${e}-${n}`;return t}async linkRelations(e,t,n,r){const c=r.filter(m=>!n.includes(m)),f=n.filter(m=>!r.includes(m));for(const m of c){const A=await this.entries.findById(m);if(!A)continue;const N=new Set(A.related??[]);N.add(t),await this.entries.update(m,{related:[...N]})}for(const m of f){const A=await this.entries.findById(m);A&&await this.entries.update(m,{related:(A.related??[]).filter(N=>N!==t)})}}}const St=b({list:p.query(({ctx:i})=>i.services.collections.listDefinitions()),get:p.input(s.object({idOrSlug:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:_.input(ut).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:_.input(s.object({id:s.string(),data:pt})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:b({get:p.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),list:p.input(s.object({collectionId:s.string(),skip:s.number().int().min(0).optional(),limit:s.number().int().min(1).max(100).optional()})).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),create:p.input(s.object({collectionId:s.string(),data:yt})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:p.input(s.object({id:s.string(),data:ht})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:p.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})});function ni({env:i}={}){const e=i??ve(),t=be(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),n=Ne(e),r=Z.fromEnv(e),c=new Le(new Be(t),{email:r,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),f=new ot(t),m=new ct(f,n),A=new vt(new gt(t),new wt(t),m),N=new tt(new Ve(t)),x={health:new Ae(t),users:c,organization:N,media:m,collections:A};return{env:e,db:t,storage:n,services:x}}const si=b({health:Wt,auth:He,users:Fe,apiTokens:We,organization:it,media:lt,collections:St});export{ce as ALLOWED_MIME,Pe as CannotRemoveSelfError,G as CollectionNotFoundError,vt as CollectionsService,gt as DefinitionRepository,ae as DeployFailedError,et as DeployHookMissingError,Q as DomainError,Et as DuplicateSlugError,Z as EmailService,J as EntryNotFoundError,wt as EntryRepository,pe as FIELD_TYPES,Ae as HealthService,ft as InvalidEntryDataError,je as InvitationInvalidError,Y as MediaNotFoundError,ot as MediaRepository,ct as MediaService,Xe as OrganizationAlreadyInitializedError,Ze as OrganizationNotInitializedError,Ve as OrganizationRepository,tt as OrganizationService,ee as PUBLICATION_STATUSES,Oe as S3Storage,$e as SessionNotFoundError,ze as TooManyAttemptsError,de as UnsupportedMimeError,at as UploadIncompleteError,re as UserNotFoundError,Be as UsersRepository,Le as UsersService,ke as acceptInvitationDto,Se as addressSchema,Ce as apiTokenCreateDto,y as apiTokens,We as apiTokensRouter,si as appRouter,He as authRouter,me as buildDataSchema,h as collectionDefinitions,St as collectionsRouter,be as connectDb,ni as createCore,Ne as createStorage,g as createTypedError,ut as definitionCreateDto,pt as definitionUpdateDto,d as entries,yt as entryCreateDto,ht as entryUpdateDto,K as fieldDefinitionSchema,v as invitations,xe as inviteDto,Me as loginDto,E as media,st as mediaFinalizeDto,nt as mediaRequestUploadDto,lt as mediaRouter,rt as mediaUpdateDto,U as organization,Ge as organizationInitDto,it as organizationRouter,Je as organizationUpdateDto,ve as parseEnv,Te as requestPasswordResetDto,l as sessions,T as toPublicUser,Re as userUpdateDto,u as users,Fe as usersRouter};
1
+ import{homedir as Ut}from"node:os";import{join as K}from"node:path";import{z as s}from"zod";import{Database as Ot}from"bun:sqlite";import{mkdirSync as Nt,existsSync as It}from"node:fs";import{drizzle as Dt}from"drizzle-orm/bun-sqlite";import{migrate as Mt}from"drizzle-orm/bun-sqlite/migrator";import{sqliteTable as I,text as o,integer as pe,uniqueIndex as kt}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as B,FIELD_TYPES as me}from"./domains/collections/constants.mjs";import{fieldDefinitionSchema as L,buildDataSchema as he}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS}from"./domains/collections/utils.mjs";import{sql as $,eq as a,and as D,isNull as H,gt as te,desc as R,or as ie,lt as ye,isNotNull as ge,inArray as xt,like as we,asc as fe}from"drizzle-orm";import{S3Client as Tt,PutObjectCommand as Ee,HeadObjectCommand as Rt,DeleteObjectsCommand as Ct,GetObjectCommand as Bt}from"@aws-sdk/client-s3";import{getSignedUrl as _e}from"@aws-sdk/s3-request-presigner";import{initTRPC as $t,TRPCError as F}from"@trpc/server";import{randomBytes as ne,createHash as jt}from"node:crypto";import{SignJWT as Pt,jwtVerify as zt}from"jose";import{consola as ve}from"consola";import{createInsertSchema as se,createUpdateSchema as W}from"drizzle-zod";import{nanoid as Se}from"nanoid";const j=s.string().min(1),qt=s.object({COMMUN_DATA_DIR:s.string().default(K(Ut(),".commun")),COMMUN_MIGRATIONS_DIR:s.string().optional(),COMMUN_S3_ENDPOINT:s.string().optional(),COMMUN_S3_REGION:s.string().default("fr-par"),COMMUN_S3_BUCKET:j,COMMUN_S3_ACCESS_KEY:j,COMMUN_S3_SECRET_KEY:j,COMMUN_EMAIL_WEBHOOK_URL:j,COMMUN_EMAIL_WEBHOOK_TOKEN:s.string().optional(),COMMUN_ADMIN_URL:s.string().optional(),COMMUN_JWT_SECRET:j});function be(i=process.env){return qt.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()),M=()=>o("created_at").notNull().$defaultFn(()=>new Date().toISOString()),P=()=>o("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),Q=()=>o("legacy_extra",{mode:"json"}).$type(),Kt=()=>o("status",{enum:B}).notNull().default("draft"),Lt=()=>o("published_at"),Ae=s.object({street:s.string().optional(),postalCode:s.string().optional(),city:s.string().optional()}),U=I("organization",{id:pe("id").primaryKey().default(1),name:o("name").notNull(),type:o("type",{enum:["commune","intercommunality","syndicate","other"]}).notNull().default("commune"),slug:o("slug").notNull(),description:o("description"),address:o("address",{mode:"json"}).$type(),deployment:o("deployment",{mode:"json"}).$type(),settings:o("settings",{mode:"json"}).$type(),updatedBy:o("updated_by"),legacyExtra:Q(),createdAt:M(),updatedAt:P()}),p=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:M(),updatedAt:P()}),l=I("sessions",{id:k(),userId:o("user_id").notNull().references(()=>p.id,{onDelete:"cascade"}),expiresAt:o("expires_at").notNull(),revokedAt:o("revoked_at"),ua:o("ua"),ip:o("ip"),createdAt:M()}),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:M()}),h=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:M()}),E=I("media",{id:k(),filename:o("filename").notNull(),mime:o("mime").notNull(),size:pe("size").notNull(),alt:o("alt"),caption:o("caption"),objects:o("objects",{mode:"json"}).$type().notNull(),metaData:o("meta_data",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:Q(),createdAt:M(),updatedAt:P()}),y=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:Q(),createdAt:M(),updatedAt:P()}),c=I("entries",{id:k(),collectionId:o("collection_id").notNull().references(()=>y.id,{onDelete:"cascade"}),title:o("title").notNull(),slug:o("slug").notNull(),data:o("data",{mode:"json"}).$type().notNull(),related:o("related",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),status:Kt(),publishedAt:Lt(),legacyExtra:Q(),createdAt:M(),updatedAt:P()},i=>[kt("entries_slug_unique").on(i.collectionId,i.slug)]),Ht={__proto__:null,FIELD_TYPES:me,PUBLICATION_STATUSES:B,addressSchema:Ae,apiTokens:h,collectionDefinitions:y,entries:c,fieldDefinitionSchema:L,invitations:v,media:E,organization:U,sessions:l,users:p};function Ft(){const i=import.meta.dir;return i?K(i,"..","..","..","drizzle"):void 0}function Ue(i,e){const t=e??Ft();Nt(i,{recursive:!0});const n=new Ot(K(i,"commun.db"));n.exec("PRAGMA journal_mode=WAL"),n.exec("PRAGMA foreign_keys=ON"),n.exec("PRAGMA busy_timeout=5000");const r=Dt({client:n,schema:Ht});return t&&It(K(t,"meta","_journal.json"))&&Mt(r,{migrationsFolder:t}),r}class X{constructor(e){this.config=e}static fromEnv(e){return new X({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 Oe{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run($`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Ne=168*3600,Wt="medias/";class Ie{constructor(e){this.config=e,this.client=new Tt({region:e.region,...e.endpoint?{endpoint:e.endpoint,forcePathStyle:!0}:{},credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,n){return _e(this.client,new Ee({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:n}),{expiresIn:Ne})}async put(e,t,n){await this.client.send(new Ee({Bucket:this.config.bucket,Key:e,Body:t,ContentType:n}))}async head(e){try{return{size:(await this.client.send(new Rt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Ct({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Wt)?Promise.resolve(this.publicUrl(e)):_e(this.client,new Bt({Bucket:this.config.bucket,Key:e}),{expiresIn:Ne})}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 De(i){return new Ie({endpoint:i.COMMUN_S3_ENDPOINT||void 0,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const w={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class Y extends Error{}function g(i,e){return class extends Y{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const re=$t.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof Y?{type:t.type}:{}}}}}),b=re.router,Qt=re.procedure,Me=re.middleware,Yt=Me(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof Y)throw new F({code:t.trpcCode,message:t.message,cause:t})}return e}),C=Qt.use(Yt),ke=i=>Me(({ctx:e,next:t})=>{if(!e.session)throw new F({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new F({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),u=C.use(ke()),_=C.use(ke("admin")),Gt=b({ping:C.query(({ctx:i})=>i.services.health.check())}),xe=s.object({email:s.email(),password:s.string().min(1)}),Te=s.object({token:s.string().min(1),name:s.string().min(1).optional(),password:s.string().min(10)}),Re=s.object({email:s.email()}),Ce=s.object({email:s.email(),role:s.enum(["admin","redacteur"])}),Be=s.object({id:s.string(),data:s.object({name:s.string().min(1).optional(),role:s.enum(["admin","redacteur"]).optional(),email:s.email().optional()})}),x=({id:i,email:e,name:t,role:n})=>({id:i,email:e,name:t,role:n}),$e=s.object({name:s.string().min(1)});class je{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(p).where(a(p.email,e)).get()}async findUserById(e){return this.db.select().from(p).where(a(p.id,e)).get()}async listUsers(){return this.db.select().from(p).all()}async hasAnyUser(){return this.db.select({id:p.id}).from(p).limit(1).all().length>0}async deleteUser(e){this.db.delete(p).where(a(p.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(p).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(a(p.id,t.id)).returning().get():this.db.insert(p).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:p}).from(l).innerJoin(p,a(p.id,l.userId)).where(D(a(l.id,e),H(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(D(a(l.userId,e),H(l.revokedAt),te(l.expiresAt,t))).orderBy(R(l.createdAt)).all()}async updateUser(e,t){return this.db.update(p).set(t).where(a(p.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(D(a(v.tokenHash,e),H(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(h).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(h).where(D(a(h.tokenHash,e),H(h.revokedAt))).get()}async touchApiToken(e,t){this.db.update(h).set({lastUsedAt:t}).where(a(h.id,e)).run()}async revokeApiToken(e,t){this.db.update(h).set({revokedAt:t}).where(a(h.id,e)).run()}async listApiTokens(){return this.db.select({id:h.id,name:h.name,lastUsedAt:h.lastUsedAt,revokedAt:h.revokedAt,createdAt:h.createdAt}).from(h).orderBy(R(h.createdAt)).all()}async purgeExpired(e){this.db.delete(l).where(ie(ye(l.expiresAt,e),ge(l.revokedAt))).run(),this.db.delete(v).where(ie(ye(v.expiresAt,e),ge(v.usedAt))).run()}}const oe=g("user-not-found-error",w.NOT_FOUND),Pe=g("session-not-found-error",w.NOT_FOUND),ze=g("invitation-invalid-error",w.BAD_REQUEST),qe=g("cannot-remove-self-error",w.BAD_REQUEST),Ke=g("too-many-attempts-error",w.TOO_MANY_REQUESTS),z=i=>jt("sha256").update(i).digest("hex"),O=()=>new Date().toISOString(),Jt=720*3600*1e3,Le=168*3600*1e3,Vt=Bun.password.hashSync("commun-dummy-password-for-timing"),Zt=5*6e4,Xt=10,q=new Map,He=i=>{const e=Date.now(),t=(q.get(i)??[]).filter(n=>e-n<Zt);return t.length?q.set(i,t):q.delete(i),t},ei=i=>He(i).length>=Xt,ti=i=>{q.set(i,[...He(i),Date.now()])},ii=i=>q.delete(i);class Fe{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){ve.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(ei(r))throw new Ke;const d=await this.repository.findUserByEmail(r),f=await this.verifyPassword(t,d?.passwordHash??Vt);return!d?.passwordHash||!f?(ti(r),null):(ii(r),this.createSession(d,n))}async createSession(e,t){const n=new Date(Date.now()+Jt).toISOString(),r=await this.repository.insertSession({userId:e.id,expiresAt:n,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Pt({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 zt(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 Pe(`session not found: ${t}`);await this.repository.revokeSession(t,O())}async purgeExpired(){await this.repository.purgeExpired(O())}async createInvitation(e){const t=ne(32).toString("base64url"),n=new Date(Date.now()+Le).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:z(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=ne(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:z(n),expiresAt:new Date(Date.now()+Le).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(z(e),O());if(!n)throw new ze;const r=await this.repository.findUserByEmail(n.email),d=t.name?.trim()||r?.name||n.email.split("@")[0]||"Membre",f=await this.repository.activateUser({email:n.email,name:d,passwordHash:await this.hashPassword(t.password),role:n.role});return await this.repository.markInvitationUsed(n.id,O()),f}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new oe(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new qe;await this.repository.deleteUser(t)}async updateUser(e,t){const n=await this.repository.updateUser(e,t);if(!n)throw new oe(`user not found: ${e}`);return n}async createApiToken(e){const t=`commun_${ne(24).toString("base64url")}`,n=await this.repository.insertApiToken({name:e,tokenHash:z(t)});return{token:t,record:n}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(z(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 We=b({login:C.input(xe).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new F({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:x(t.session.user)}}),logout:u.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:u.query(({ctx:i})=>({user:x(i.session.user)})),sessions:b({list:u.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:u.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:C.input(Te).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:x(t)}}),requestPasswordReset:C.input(Re).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Qe=b({list:_.query(async({ctx:i})=>(await i.services.users.listUsers()).map(x)),directory:u.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})=>x(await i.services.users.getUser(e.id))),invite:_.input(Ce).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:_.input(Be).mutation(async({ctx:i,input:e})=>x(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}))}),Ye=b({list:_.query(({ctx:i})=>i.services.users.listApiTokens()),create:_.input($e).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}))}),Ge={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},ni={createdBy:!0,updatedBy:!0},ae={...Ge,...ni},Je={...Ge,updatedBy:!0},Ve=se(U).omit(Je),Ze=W(U).omit(Je);class Xe{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 et=g("organization-not-initialized-error",w.NOT_FOUND),tt=g("organization-already-initialized-error",w.BAD_REQUEST),it=g("deploy-hook-missing-error",w.BAD_REQUEST),ce=g("deploy-failed-error",w.INTERNAL_SERVER_ERROR),si=3e4;class nt{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 tt;return this.repository.insert(e)}async update(e,t){const n=await this.repository.update({...e,updatedBy:t??null});if(!n)throw new et;return n}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new it;const t=this.options.fetchImpl??fetch;let n;try{n=await t(e,{signal:AbortSignal.timeout(si)})}catch(r){throw new ce(`deploy hook unreachable: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw new ce(`deploy hook: ${n.status} ${n.statusText}`);return{status:n.status}}}const st=b({get:u.query(({ctx:i})=>i.services.organization.get()),init:_.input(Ve).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:_.input(Ze).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:u.mutation(({ctx:i})=>i.services.organization.deploy())}),rt=s.object({filename:s.string().min(1),mime:s.string().min(1),metaData:s.record(s.string(),s.string()).optional()}),ot=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()}),at=W(E).pick({alt:!0,caption:!0,filename:!0});class ct{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($`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 G=g("media-not-found-error",w.NOT_FOUND),de=g("unsupported-mime-error",w.BAD_REQUEST),dt=g("upload-incomplete-error",w.BAD_REQUEST),le=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"]),ri=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],ue=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",lt="medias/";class ut{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,n){if(!le.has(t))throw new de(`unsupported mime type: ${t}`);const r=`${lt}${Se(10)}/${ue(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 dt(`object not found in storage: ${e.key}`);const r=await this.repository.insert({filename:ue(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 ve.info(`[media] resize \xE0 impl\xE9menter pour ${r.id} (${ri.join(", ")})`),r}async uploadDirect(e,t,n,r,d){if(!le.has(t))throw new de(`unsupported mime type: ${t}`);const f=`${lt}${Se(10)}/${ue(e)}`;return await this.storage.put(f,n,t),this.finalize({key:f,filename:e,mime:t,metaData:r},d)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new G(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,n){const r=await this.repository.update(e,{...t,updatedBy:n??null});if(!r)throw new G(`media not found: ${e}`);return r}async remove(e){const t=await this.repository.findById(e);if(!t)throw new G(`media not found: ${e}`);const n=t.objects;await this.storage.remove([n.original,...Object.values(n.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async objectUrls(e){const t=e.objects,n={original:await this.storage.url(t.original)};for(const[r,d]of Object.entries(t.variants??{}))n[r]=await this.storage.url(d);return n}}const pt=b({requestUpload:u.input(rt).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:u.input(ot).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:u.query(({ctx:i})=>i.services.media.listResolved()),get:u.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:u.input(s.object({id:s.string(),data:at})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:u.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))}),mt=se(y).omit(ae).extend({fields:s.array(L).min(1),slug:s.string().optional()}),ht=W(y).omit(ae).extend({fields:s.array(L).min(1).optional()}),yt={...ae,related:!0,collectionId:!0},gt=se(c).omit(yt).extend({slug:s.string().optional()}),wt=W(c).omit(yt).extend({related:s.array(s.string()).optional()});class ft{constructor(e){this.db=e}async list(){return this.db.select().from(y).all()}async findBySlug(e){return this.db.select().from(y).where(a(y.slug,e)).get()}async findById(e){return this.db.select().from(y).where(a(y.id,e)).get()}async findByLegacyId(e){return this.db.select().from(y).where($`json_extract(${y.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(y).values(e).returning().get()}async update(e,t){return this.db.update(y).set(t).where(a(y.id,e)).returning().get()}async delete(e){return this.db.delete(y).where(a(y.id,e)).returning().get()}}class Et{constructor(e){this.db=e}async list(e){return this.db.select().from(c).where(a(c.collectionId,e)).orderBy(R(c.updatedAt)).all()}narrowing(e){const t=[a(c.collectionId,e.collectionId)];if(e.status?.length&&t.push(xt(c.status,e.status)),e.search?.trim()){const n=`%${e.search.trim()}%`;t.push(ie(we(c.title,n),we(c.data,n)))}return D(...t)}async countMatching(e){const[t]=this.db.select({total:$`count(*)`}).from(c).where(this.narrowing(e)).all();return t?.total??0}async listPaginated(e,t){const n={recent:R(c.updatedAt),oldest:fe(c.updatedAt),title:fe(c.title)};return this.db.select().from(c).where(this.narrowing({...t,collectionId:e})).orderBy(n[t.order??"recent"]).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(c).where(D(a(c.collectionId,e),a(c.status,"published"))).orderBy(R(c.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(c).where(D(a(c.collectionId,e),a(c.slug,t))).get()}async findById(e){return this.db.select().from(c).where(a(c.id,e)).get()}async findByDataField(e,t,n){return this.db.select().from(c).where(D(a(c.collectionId,e),$`json_extract(${c.data}, ${`$.${t}`}) = ${n}`)).get()}async insert(e){return this.db.insert(c).values(e).returning().get()}async update(e,t){return this.db.update(c).set(t).where(a(c.id,e)).returning().get()}async delete(e){return this.db.delete(c).where(a(c.id,e)).returning().get()}}const J=g("collection-not-found-error",w.NOT_FOUND),V=g("entry-not-found-error",w.NOT_FOUND),_t=g("invalid-entry-data-error",w.BAD_REQUEST),vt=g("duplicate-slug-error",w.BAD_REQUEST);function St(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function Z(i,e){const t=[];for(const n of i){if(n.type!=="relation")continue;const r=e[n.name];typeof r=="string"&&r?t.push(r):Array.isArray(r)&&t.push(...r.filter(d=>typeof d=="string"))}return[...new Set(t)]}class bt{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 J(`collection not found: ${e}`);return t}async createDefinition(e,t){return this.definitions.insert({...e,slug:e.slug||await this.uniqueDefinitionSlug(St(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 J(`collection not found: ${e}`);return r}async removeDefinition(e){if(!await this.definitions.delete(e))throw new J(`collection not found: ${e}`)}validateData(e,t){const n=he(e.fields).safeParse(t);if(!n.success)throw new _t(`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 V(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){const n=await this.getDefinition(e);return this.entries.listPaginated(n.id,{skip:t.skip??0,limit:t.limit??20,status:t.status,search:t.search,order:t.order})}async countEntries(e,t={}){const n=await this.getDefinition(e);return this.entries.countMatching({collectionId:n.id,status:t.status,search:t.search})}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,n){const r=await this.getDefinition(e),d=this.validateData(r,t.data),f=await this.uniqueEntrySlug(r.id,t.slug||St(t.title)),m=await this.entries.insert({...t,slug:f,data:d,collectionId:r.id,createdBy:n??null,updatedBy:n??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(r,m.id,[],Z(r.fields,d)),m}async updateEntry(e,t,n){const r=await this.entries.findById(e);if(!r)throw new V(`entry not found: ${e}`);const d=await this.getDefinition(r.collectionId),f=new Set(d.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??{}))),T=t.data?{...m,...this.validateData(d,N)}:void 0,ee={...t,updatedBy:n??null};T&&(ee.data=T),t.status==="published"&&!t.publishedAt&&(ee.publishedAt=new Date().toISOString());try{const S=await this.entries.update(e,ee);return T&&await this.linkRelations(d,e,Z(d.fields,r.data),Z(d.fields,T)),t.related&&await this.linkRelations(d,e,r.related??[],t.related),S}catch(S){throw this.mapSlugConflict(S,d.slug,t.slug??r.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new V(`entry not found: ${e}`);const n=await this.getDefinition(t.collectionId);await this.linkRelations(n,e,Z(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 vt(`le slug "${n}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let n=t;for(let r=1;await this.entries.findBySlug(e,n);r++)n=`${t}-${r}`;return n}async uniqueDefinitionSlug(e){let t=e;for(let n=1;await this.definitions.findBySlug(t);n++)t=`${e}-${n}`;return t}async linkRelations(e,t,n,r){const d=r.filter(m=>!n.includes(m)),f=n.filter(m=>!r.includes(m));for(const m of d){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 At=b({list:u.query(({ctx:i})=>i.services.collections.listDefinitions()),get:u.input(s.object({idOrSlug:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:_.input(mt).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:_.input(s.object({id:s.string(),data:ht})).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:u.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),list:u.input(s.object({collectionId:s.string(),status:s.array(s.enum(B)).optional(),search:s.string().max(200).optional(),order:s.enum(["recent","oldest","title"]).optional(),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)),count:u.input(s.object({collectionId:s.string(),status:s.array(s.enum(B)).optional(),search:s.string().max(200).optional()})).query(({ctx:i,input:e})=>i.services.collections.countEntries(e.collectionId,e)),create:u.input(s.object({collectionId:s.string(),data:gt})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:u.input(s.object({id:s.string(),data:wt})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:u.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})});function oi({env:i}={}){const e=i??be(),t=Ue(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),n=De(e),r=X.fromEnv(e),d=new Fe(new je(t),{email:r,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),f=new ct(t),m=new ut(f,n),A=new bt(new ft(t),new Et(t),m),N=new nt(new Xe(t)),T={health:new Oe(t),users:d,organization:N,media:m,collections:A};return{env:e,db:t,storage:n,services:T}}const ai=b({health:Gt,auth:We,users:Qe,apiTokens:Ye,organization:st,media:pt,collections:At});export{le as ALLOWED_MIME,qe as CannotRemoveSelfError,J as CollectionNotFoundError,bt as CollectionsService,ft as DefinitionRepository,ce as DeployFailedError,it as DeployHookMissingError,Y as DomainError,vt as DuplicateSlugError,X as EmailService,V as EntryNotFoundError,Et as EntryRepository,me as FIELD_TYPES,Oe as HealthService,_t as InvalidEntryDataError,ze as InvitationInvalidError,G as MediaNotFoundError,ct as MediaRepository,ut as MediaService,tt as OrganizationAlreadyInitializedError,et as OrganizationNotInitializedError,Xe as OrganizationRepository,nt as OrganizationService,B as PUBLICATION_STATUSES,Ie as S3Storage,Pe as SessionNotFoundError,Ke as TooManyAttemptsError,de as UnsupportedMimeError,dt as UploadIncompleteError,oe as UserNotFoundError,je as UsersRepository,Fe as UsersService,Te as acceptInvitationDto,Ae as addressSchema,$e as apiTokenCreateDto,h as apiTokens,Ye as apiTokensRouter,ai as appRouter,We as authRouter,he as buildDataSchema,y as collectionDefinitions,At as collectionsRouter,Ue as connectDb,oi as createCore,De as createStorage,g as createTypedError,mt as definitionCreateDto,ht as definitionUpdateDto,c as entries,gt as entryCreateDto,wt as entryUpdateDto,L as fieldDefinitionSchema,v as invitations,Ce as inviteDto,xe as loginDto,E as media,ot as mediaFinalizeDto,rt as mediaRequestUploadDto,pt as mediaRouter,at as mediaUpdateDto,U as organization,Ve as organizationInitDto,st as organizationRouter,Ze as organizationUpdateDto,be as parseEnv,Re as requestPasswordResetDto,l as sessions,x as toPublicUser,Be as userUpdateDto,p as users,Qe as usersRouter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-commune/core",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
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",