@open-commune/core 0.2.18 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dtos.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- export { o as AUDIENCE_PERIODS, p as AcceptInvitationDto, r as ApiTokenCreateDto, l as AudienceAsk, m as AudiencePanelData, t as AudienceQuery, u as AudienceSummary, D as DefinitionCreateDto, h as DefinitionUpdateDto, v as ERROR_TYPES, j as EntryCreateDto, i as EntrySearchHit, k as EntryUpdateDto, n as ErrorType, w as InviteDto, L as LoginDto, d as MediaFinalizeDto, x as MediaRequestUploadDto, e as MediaUpdateDto, a as OrganizationInitDto, b as OrganizationUpdateDto, P as PublicUser, R as RequestPasswordResetDto, z as SessionUser, B as UpdateOwnProfileDto, F as UserUpdateDto, G as acceptInvitationDto, J as apiTokenCreateDto, Q as audienceAskDto, T as audienceQuerySchema, V as audienceSummarySchema, X as definitionCreateDto, Y as definitionDto, Z as definitionUpdateDto, $ as entryCreateDto, a0 as entryDto, a1 as entrySearchHitDto, a2 as entryUpdateDto, a4 as inviteDto, a5 as isErrorType, a6 as loginDto, a8 as mediaFinalizeDto, a9 as mediaRequestUploadDto, aa as mediaUpdateDto, ac as organizationInitDto, ad as organizationUpdateDto, ae as requestPasswordResetDto, ag as toPublicUser, ah as toSessionUser, ai as updateOwnProfileDto, aj as userUpdateDto } from './shared/core.C8czg6gz.mjs';
1
+ export { o as AUDIENCE_PERIODS, p as AcceptInvitationDto, r as ApiTokenCreateDto, l as AudienceAsk, m as AudiencePanelData, t as AudienceQuery, u as AudienceSummary, D as DefinitionCreateDto, h as DefinitionUpdateDto, v as ERROR_TYPES, j as EntryCreateDto, i as EntrySearchHit, k as EntryUpdateDto, n as ErrorType, w as InviteDto, L as LoginDto, d as MediaFinalizeDto, x as MediaRequestUploadDto, e as MediaUpdateDto, a as OrganizationInitDto, b as OrganizationUpdateDto, P as PublicUser, R as RequestPasswordResetDto, z as SessionUser, B as UpdateOwnProfileDto, F as UserUpdateDto, G as acceptInvitationDto, J as apiTokenCreateDto, Q as audienceAskDto, T as audienceQuerySchema, V as audienceSummarySchema, X as definitionCreateDto, Y as definitionDto, Z as definitionUpdateDto, $ as entryCreateDto, a0 as entryDto, a1 as entrySearchHitDto, a2 as entryUpdateDto, a4 as inviteDto, a5 as isErrorType, a6 as loginDto, a8 as mediaFinalizeDto, a9 as mediaRequestUploadDto, aa as mediaUpdateDto, ac as organizationInitDto, ad as organizationUpdateDto, ae as requestPasswordResetDto, ag as toPublicUser, ah as toSessionUser, ai as updateOwnProfileDto, aj as userUpdateDto } from './shared/core.BQTDkZ_p.mjs';
2
2
  import 'drizzle-zod';
3
3
  import 'drizzle-orm/sqlite-core';
4
4
  import 'zod';
package/dist/dtos.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { o as AUDIENCE_PERIODS, p as AcceptInvitationDto, r as ApiTokenCreateDto, l as AudienceAsk, m as AudiencePanelData, t as AudienceQuery, u as AudienceSummary, D as DefinitionCreateDto, h as DefinitionUpdateDto, v as ERROR_TYPES, j as EntryCreateDto, i as EntrySearchHit, k as EntryUpdateDto, n as ErrorType, w as InviteDto, L as LoginDto, d as MediaFinalizeDto, x as MediaRequestUploadDto, e as MediaUpdateDto, a as OrganizationInitDto, b as OrganizationUpdateDto, P as PublicUser, R as RequestPasswordResetDto, z as SessionUser, B as UpdateOwnProfileDto, F as UserUpdateDto, G as acceptInvitationDto, J as apiTokenCreateDto, Q as audienceAskDto, T as audienceQuerySchema, V as audienceSummarySchema, X as definitionCreateDto, Y as definitionDto, Z as definitionUpdateDto, $ as entryCreateDto, a0 as entryDto, a1 as entrySearchHitDto, a2 as entryUpdateDto, a4 as inviteDto, a5 as isErrorType, a6 as loginDto, a8 as mediaFinalizeDto, a9 as mediaRequestUploadDto, aa as mediaUpdateDto, ac as organizationInitDto, ad as organizationUpdateDto, ae as requestPasswordResetDto, ag as toPublicUser, ah as toSessionUser, ai as updateOwnProfileDto, aj as userUpdateDto } from './shared/core.bkXizwPE.js';
1
+ export { o as AUDIENCE_PERIODS, p as AcceptInvitationDto, r as ApiTokenCreateDto, l as AudienceAsk, m as AudiencePanelData, t as AudienceQuery, u as AudienceSummary, D as DefinitionCreateDto, h as DefinitionUpdateDto, v as ERROR_TYPES, j as EntryCreateDto, i as EntrySearchHit, k as EntryUpdateDto, n as ErrorType, w as InviteDto, L as LoginDto, d as MediaFinalizeDto, x as MediaRequestUploadDto, e as MediaUpdateDto, a as OrganizationInitDto, b as OrganizationUpdateDto, P as PublicUser, R as RequestPasswordResetDto, z as SessionUser, B as UpdateOwnProfileDto, F as UserUpdateDto, G as acceptInvitationDto, J as apiTokenCreateDto, Q as audienceAskDto, T as audienceQuerySchema, V as audienceSummarySchema, X as definitionCreateDto, Y as definitionDto, Z as definitionUpdateDto, $ as entryCreateDto, a0 as entryDto, a1 as entrySearchHitDto, a2 as entryUpdateDto, a4 as inviteDto, a5 as isErrorType, a6 as loginDto, a8 as mediaFinalizeDto, a9 as mediaRequestUploadDto, aa as mediaUpdateDto, ac as organizationInitDto, ad as organizationUpdateDto, ae as requestPasswordResetDto, ag as toPublicUser, ah as toSessionUser, ai as updateOwnProfileDto, aj as userUpdateDto } from './shared/core.D0n0cwjD.js';
2
2
  import 'drizzle-zod';
3
3
  import 'drizzle-orm/sqlite-core';
4
4
  import 'zod';
package/dist/index.d.mts CHANGED
@@ -3,8 +3,8 @@ import * as _trpc_server from '@trpc/server';
3
3
  import { z } from 'zod';
4
4
  import * as drizzle_orm_bun_sqlite from 'drizzle-orm/bun-sqlite';
5
5
  import { Database } from 'bun:sqlite';
6
- import { s as schema, U as User, S as Session, I as Invitation, A as ApiToken, O as Organization, N as NewOrganization, a as OrganizationInitDto, b as OrganizationUpdateDto, c as NewMedia, M as Media, d as MediaFinalizeDto, e as MediaUpdateDto, C as CollectionDefinition, f as NewCollectionDefinition, E as Entry, g as NewEntry, D as DefinitionCreateDto, h as DefinitionUpdateDto, i as EntrySearchHit, j as EntryCreateDto, k as EntryUpdateDto, l as AudienceAsk, m as AudiencePanelData, n as ErrorType } from './shared/core.C8czg6gz.mjs';
7
- export { o as AUDIENCE_PERIODS, p as AcceptInvitationDto, q as Address, r as ApiTokenCreateDto, t as AudienceQuery, u as AudienceSummary, v as ERROR_TYPES, w as InviteDto, L as LoginDto, x as MediaRequestUploadDto, y as NewUser, P as PublicUser, R as RequestPasswordResetDto, z as SessionUser, B as UpdateOwnProfileDto, F as UserUpdateDto, G as acceptInvitationDto, H as addressSchema, J as apiTokenCreateDto, K as apiTokens, Q as audienceAskDto, T as audienceQuerySchema, V as audienceSummarySchema, W as collectionDefinitions, X as definitionCreateDto, Y as definitionDto, Z as definitionUpdateDto, _ as entries, $ as entryCreateDto, a0 as entryDto, a1 as entrySearchHitDto, a2 as entryUpdateDto, a3 as invitations, a4 as inviteDto, a5 as isErrorType, a6 as loginDto, a7 as media, a8 as mediaFinalizeDto, a9 as mediaRequestUploadDto, aa as mediaUpdateDto, ab as organization, ac as organizationInitDto, ad as organizationUpdateDto, ae as requestPasswordResetDto, af as sessions, ag as toPublicUser, ah as toSessionUser, ai as updateOwnProfileDto, aj as userUpdateDto, ak as users } from './shared/core.C8czg6gz.mjs';
6
+ import { s as schema, U as User, S as Session, I as Invitation, A as ApiToken, O as Organization, N as NewOrganization, a as OrganizationInitDto, b as OrganizationUpdateDto, c as NewMedia, M as Media, d as MediaFinalizeDto, e as MediaUpdateDto, C as CollectionDefinition, f as NewCollectionDefinition, E as Entry, g as NewEntry, D as DefinitionCreateDto, h as DefinitionUpdateDto, i as EntrySearchHit, j as EntryCreateDto, k as EntryUpdateDto, l as AudienceAsk, m as AudiencePanelData, n as ErrorType } from './shared/core.BQTDkZ_p.mjs';
7
+ export { o as AUDIENCE_PERIODS, p as AcceptInvitationDto, q as Address, r as ApiTokenCreateDto, t as AudienceQuery, u as AudienceSummary, v as ERROR_TYPES, w as InviteDto, L as LoginDto, x as MediaRequestUploadDto, y as NewUser, P as PublicUser, R as RequestPasswordResetDto, z as SessionUser, B as UpdateOwnProfileDto, F as UserUpdateDto, G as acceptInvitationDto, H as addressSchema, J as apiTokenCreateDto, K as apiTokens, Q as audienceAskDto, T as audienceQuerySchema, V as audienceSummarySchema, W as collectionDefinitions, X as definitionCreateDto, Y as definitionDto, Z as definitionUpdateDto, _ as entries, $ as entryCreateDto, a0 as entryDto, a1 as entrySearchHitDto, a2 as entryUpdateDto, a3 as invitations, a4 as inviteDto, a5 as isErrorType, a6 as loginDto, a7 as media, a8 as mediaFinalizeDto, a9 as mediaRequestUploadDto, aa as mediaUpdateDto, ab as organization, ac as organizationInitDto, ad as organizationUpdateDto, ae as requestPasswordResetDto, af as sessions, ag as toPublicUser, ah as toSessionUser, ai as updateOwnProfileDto, aj as userUpdateDto, ak as users } from './shared/core.BQTDkZ_p.mjs';
8
8
  export { FIELD_TYPES, FieldType, PUBLICATION_STATUSES, PublicationStatus } from './domains/collections/constants.mjs';
9
9
  export { FIELD_VALUE_SCHEMAS, FieldDefinition, buildDataSchema, fieldDefinitionSchema } from './domains/collections/utils.mjs';
10
10
  import 'drizzle-orm/sqlite-core';
@@ -567,6 +567,7 @@ declare class AudienceService {
567
567
  private readonly config;
568
568
  private readonly cache;
569
569
  private names;
570
+ private sitePages;
570
571
  private readonly viewers;
571
572
  constructor(collections: CollectionsService, config: {
572
573
  url?: string;
@@ -585,6 +586,17 @@ declare class AudienceService {
585
586
  summary(ask: AudienceAsk, viewer: string): Promise<AudiencePanelData>;
586
587
  /** The source's answer, or `null`: any failure only hides the panel. */
587
588
  private ask;
589
+ /**
590
+ * The segment a collection's pages carry on the public site, which the
591
+ * source filters them on. A theme decides its own addresses: a collection
592
+ * `posts` may live under `/blog`, `events` under `/agenda`. So it is read
593
+ * from the site itself: the most read page that ends with the slug of one
594
+ * of the collection's published entries gives it, as the segment before
595
+ * that slug. With none among them, the collection's own slug is asked.
596
+ */
597
+ private siteSegment;
598
+ /** The site's most read pages over the learning period, kept like the names. */
599
+ private mostReadPaths;
588
600
  private entrySlug;
589
601
  /**
590
602
  * Published entries by slug and collections by slug, to name the most read
@@ -725,14 +737,14 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
725
737
  input: void;
726
738
  output: {
727
739
  type: "commune" | "intercommunality" | "syndicate" | "other";
740
+ description: string | null;
728
741
  id: number;
729
742
  name: string;
730
- slug: string;
731
- description: string | null;
732
743
  updatedBy: string | null;
733
744
  legacyExtra: Record<string, unknown> | null;
734
745
  createdAt: string;
735
746
  updatedAt: string;
747
+ slug: string;
736
748
  address: {
737
749
  street?: string | undefined;
738
750
  postalCode?: string | undefined;
@@ -759,14 +771,14 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
759
771
  };
760
772
  output: {
761
773
  type: "commune" | "intercommunality" | "syndicate" | "other";
774
+ description: string | null;
762
775
  id: number;
763
776
  name: string;
764
- slug: string;
765
- description: string | null;
766
777
  updatedBy: string | null;
767
778
  legacyExtra: Record<string, unknown> | null;
768
779
  createdAt: string;
769
780
  updatedAt: string;
781
+ slug: string;
770
782
  address: {
771
783
  street?: string | undefined;
772
784
  postalCode?: string | undefined;
@@ -780,9 +792,9 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
780
792
  update: _trpc_server.TRPCMutationProcedure<{
781
793
  input: {
782
794
  type?: "commune" | "intercommunality" | "syndicate" | "other" | undefined;
795
+ description?: string | null | undefined;
783
796
  name?: string | undefined;
784
797
  slug?: string | undefined;
785
- description?: string | null | undefined;
786
798
  address?: {
787
799
  street?: string | undefined;
788
800
  postalCode?: string | undefined;
@@ -793,14 +805,14 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
793
805
  };
794
806
  output: {
795
807
  type: "commune" | "intercommunality" | "syndicate" | "other";
808
+ description: string | null;
796
809
  id: number;
797
810
  name: string;
798
- slug: string;
799
- description: string | null;
800
811
  updatedBy: string | null;
801
812
  legacyExtra: Record<string, unknown> | null;
802
813
  createdAt: string;
803
814
  updatedAt: string;
815
+ slug: string;
804
816
  address: {
805
817
  street?: string | undefined;
806
818
  postalCode?: string | undefined;
@@ -1373,38 +1385,38 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
1373
1385
  metaData?: Record<string, unknown> | undefined;
1374
1386
  };
1375
1387
  output: {
1388
+ filename: string;
1389
+ mime: string;
1390
+ metaData: Record<string, unknown> | null;
1391
+ alt: string | null;
1376
1392
  id: string;
1393
+ size: number;
1394
+ caption: string | null;
1395
+ objects: Record<string, unknown>;
1377
1396
  createdBy: string | null;
1378
1397
  updatedBy: string | null;
1379
1398
  legacyExtra: Record<string, unknown> | null;
1380
1399
  createdAt: string;
1381
1400
  updatedAt: string;
1382
- filename: string;
1383
- mime: string;
1384
- size: number;
1385
- alt: string | null;
1386
- caption: string | null;
1387
- objects: Record<string, unknown>;
1388
- metaData: Record<string, unknown> | null;
1389
1401
  };
1390
1402
  meta: object;
1391
1403
  }>;
1392
1404
  list: _trpc_server.TRPCQueryProcedure<{
1393
1405
  input: void;
1394
1406
  output: ({
1407
+ filename: string;
1408
+ mime: string;
1409
+ metaData: Record<string, unknown> | null;
1410
+ alt: string | null;
1395
1411
  id: string;
1412
+ size: number;
1413
+ caption: string | null;
1414
+ objects: Record<string, unknown>;
1396
1415
  createdBy: string | null;
1397
1416
  updatedBy: string | null;
1398
1417
  legacyExtra: Record<string, unknown> | null;
1399
1418
  createdAt: string;
1400
1419
  updatedAt: string;
1401
- filename: string;
1402
- mime: string;
1403
- size: number;
1404
- alt: string | null;
1405
- caption: string | null;
1406
- objects: Record<string, unknown>;
1407
- metaData: Record<string, unknown> | null;
1408
1420
  } & {
1409
1421
  objects: Record<string, string>;
1410
1422
  })[];
@@ -1415,19 +1427,19 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
1415
1427
  id: string;
1416
1428
  };
1417
1429
  output: {
1430
+ filename: string;
1431
+ mime: string;
1432
+ metaData: Record<string, unknown> | null;
1433
+ alt: string | null;
1418
1434
  id: string;
1435
+ size: number;
1436
+ caption: string | null;
1437
+ objects: Record<string, unknown>;
1419
1438
  createdBy: string | null;
1420
1439
  updatedBy: string | null;
1421
1440
  legacyExtra: Record<string, unknown> | null;
1422
1441
  createdAt: string;
1423
1442
  updatedAt: string;
1424
- filename: string;
1425
- mime: string;
1426
- size: number;
1427
- alt: string | null;
1428
- caption: string | null;
1429
- objects: Record<string, unknown>;
1430
- metaData: Record<string, unknown> | null;
1431
1443
  } & {
1432
1444
  objects: Record<string, string>;
1433
1445
  };
@@ -1443,19 +1455,19 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
1443
1455
  };
1444
1456
  };
1445
1457
  output: {
1458
+ filename: string;
1459
+ mime: string;
1460
+ metaData: Record<string, unknown> | null;
1461
+ alt: string | null;
1446
1462
  id: string;
1463
+ size: number;
1464
+ caption: string | null;
1465
+ objects: Record<string, unknown>;
1447
1466
  createdBy: string | null;
1448
1467
  updatedBy: string | null;
1449
1468
  legacyExtra: Record<string, unknown> | null;
1450
1469
  createdAt: string;
1451
1470
  updatedAt: string;
1452
- filename: string;
1453
- mime: string;
1454
- size: number;
1455
- alt: string | null;
1456
- caption: string | null;
1457
- objects: Record<string, unknown>;
1458
- metaData: Record<string, unknown> | null;
1459
1471
  };
1460
1472
  meta: object;
1461
1473
  }>;
@@ -1538,14 +1550,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1538
1550
  list: _trpc_server.TRPCQueryProcedure<{
1539
1551
  input: void;
1540
1552
  output: {
1553
+ description: string | null;
1541
1554
  id: string;
1542
1555
  name: string;
1556
+ createdBy: string | null;
1557
+ updatedBy: string | null;
1558
+ legacyExtra: Record<string, unknown> | null;
1559
+ createdAt: string;
1560
+ updatedAt: string;
1543
1561
  slug: string;
1544
- description: string | null;
1545
1562
  fields: {
1546
1563
  name: string;
1547
1564
  label: string;
1548
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1565
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1549
1566
  required: boolean;
1550
1567
  hidden: boolean;
1551
1568
  options?: string[] | undefined;
@@ -1554,11 +1571,6 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1554
1571
  editor: Record<string, unknown> | null;
1555
1572
  display: Record<string, unknown> | null;
1556
1573
  headings: Record<string, unknown> | null;
1557
- createdBy: string | null;
1558
- updatedBy: string | null;
1559
- legacyExtra: Record<string, unknown> | null;
1560
- createdAt: string;
1561
- updatedAt: string;
1562
1574
  }[];
1563
1575
  meta: object;
1564
1576
  }>;
@@ -1598,7 +1610,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1598
1610
  fields: {
1599
1611
  name: string;
1600
1612
  label: string;
1601
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1613
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1602
1614
  required?: boolean | undefined;
1603
1615
  hidden?: boolean | undefined;
1604
1616
  options?: string[] | undefined;
@@ -1611,14 +1623,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1611
1623
  slug?: string | undefined;
1612
1624
  };
1613
1625
  output: {
1626
+ description: string | null;
1614
1627
  id: string;
1615
1628
  name: string;
1629
+ createdBy: string | null;
1630
+ updatedBy: string | null;
1631
+ legacyExtra: Record<string, unknown> | null;
1632
+ createdAt: string;
1633
+ updatedAt: string;
1616
1634
  slug: string;
1617
- description: string | null;
1618
1635
  fields: {
1619
1636
  name: string;
1620
1637
  label: string;
1621
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1638
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1622
1639
  required: boolean;
1623
1640
  hidden: boolean;
1624
1641
  options?: string[] | undefined;
@@ -1627,11 +1644,6 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1627
1644
  editor: Record<string, unknown> | null;
1628
1645
  display: Record<string, unknown> | null;
1629
1646
  headings: Record<string, unknown> | null;
1630
- createdBy: string | null;
1631
- updatedBy: string | null;
1632
- legacyExtra: Record<string, unknown> | null;
1633
- createdAt: string;
1634
- updatedAt: string;
1635
1647
  };
1636
1648
  meta: object;
1637
1649
  }>;
@@ -1639,16 +1651,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1639
1651
  input: {
1640
1652
  id: string;
1641
1653
  data: {
1654
+ description?: string | null | undefined;
1642
1655
  name?: string | undefined;
1643
1656
  slug?: string | undefined;
1644
- description?: string | null | undefined;
1645
1657
  editor?: Record<string, unknown> | null | undefined;
1646
1658
  display?: Record<string, unknown> | null | undefined;
1647
1659
  headings?: Record<string, unknown> | null | undefined;
1648
1660
  fields?: {
1649
1661
  name: string;
1650
1662
  label: string;
1651
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1663
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1652
1664
  required?: boolean | undefined;
1653
1665
  hidden?: boolean | undefined;
1654
1666
  options?: string[] | undefined;
@@ -1657,14 +1669,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1657
1669
  };
1658
1670
  };
1659
1671
  output: {
1672
+ description: string | null;
1660
1673
  id: string;
1661
1674
  name: string;
1675
+ createdBy: string | null;
1676
+ updatedBy: string | null;
1677
+ legacyExtra: Record<string, unknown> | null;
1678
+ createdAt: string;
1679
+ updatedAt: string;
1662
1680
  slug: string;
1663
- description: string | null;
1664
1681
  fields: {
1665
1682
  name: string;
1666
1683
  label: string;
1667
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1684
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1668
1685
  required: boolean;
1669
1686
  hidden: boolean;
1670
1687
  options?: string[] | undefined;
@@ -1673,11 +1690,6 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1673
1690
  editor: Record<string, unknown> | null;
1674
1691
  display: Record<string, unknown> | null;
1675
1692
  headings: Record<string, unknown> | null;
1676
- createdBy: string | null;
1677
- updatedBy: string | null;
1678
- legacyExtra: Record<string, unknown> | null;
1679
- createdAt: string;
1680
- updatedAt: string;
1681
1693
  };
1682
1694
  meta: object;
1683
1695
  }>;
@@ -1836,12 +1848,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1836
1848
  output: {
1837
1849
  id: string;
1838
1850
  data: Record<string, unknown>;
1839
- slug: string;
1840
1851
  createdBy: string | null;
1841
1852
  updatedBy: string | null;
1842
1853
  legacyExtra: Record<string, unknown> | null;
1843
1854
  createdAt: string;
1844
1855
  updatedAt: string;
1856
+ slug: string;
1845
1857
  title: string;
1846
1858
  collectionId: string;
1847
1859
  related: string[] | null;
@@ -1865,12 +1877,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1865
1877
  output: {
1866
1878
  id: string;
1867
1879
  data: Record<string, unknown>;
1868
- slug: string;
1869
1880
  createdBy: string | null;
1870
1881
  updatedBy: string | null;
1871
1882
  legacyExtra: Record<string, unknown> | null;
1872
1883
  createdAt: string;
1873
1884
  updatedAt: string;
1885
+ slug: string;
1874
1886
  title: string;
1875
1887
  collectionId: string;
1876
1888
  related: string[] | null;
package/dist/index.d.ts CHANGED
@@ -3,8 +3,8 @@ import * as _trpc_server from '@trpc/server';
3
3
  import { z } from 'zod';
4
4
  import * as drizzle_orm_bun_sqlite from 'drizzle-orm/bun-sqlite';
5
5
  import { Database } from 'bun:sqlite';
6
- import { s as schema, U as User, S as Session, I as Invitation, A as ApiToken, O as Organization, N as NewOrganization, a as OrganizationInitDto, b as OrganizationUpdateDto, c as NewMedia, M as Media, d as MediaFinalizeDto, e as MediaUpdateDto, C as CollectionDefinition, f as NewCollectionDefinition, E as Entry, g as NewEntry, D as DefinitionCreateDto, h as DefinitionUpdateDto, i as EntrySearchHit, j as EntryCreateDto, k as EntryUpdateDto, l as AudienceAsk, m as AudiencePanelData, n as ErrorType } from './shared/core.bkXizwPE.js';
7
- export { o as AUDIENCE_PERIODS, p as AcceptInvitationDto, q as Address, r as ApiTokenCreateDto, t as AudienceQuery, u as AudienceSummary, v as ERROR_TYPES, w as InviteDto, L as LoginDto, x as MediaRequestUploadDto, y as NewUser, P as PublicUser, R as RequestPasswordResetDto, z as SessionUser, B as UpdateOwnProfileDto, F as UserUpdateDto, G as acceptInvitationDto, H as addressSchema, J as apiTokenCreateDto, K as apiTokens, Q as audienceAskDto, T as audienceQuerySchema, V as audienceSummarySchema, W as collectionDefinitions, X as definitionCreateDto, Y as definitionDto, Z as definitionUpdateDto, _ as entries, $ as entryCreateDto, a0 as entryDto, a1 as entrySearchHitDto, a2 as entryUpdateDto, a3 as invitations, a4 as inviteDto, a5 as isErrorType, a6 as loginDto, a7 as media, a8 as mediaFinalizeDto, a9 as mediaRequestUploadDto, aa as mediaUpdateDto, ab as organization, ac as organizationInitDto, ad as organizationUpdateDto, ae as requestPasswordResetDto, af as sessions, ag as toPublicUser, ah as toSessionUser, ai as updateOwnProfileDto, aj as userUpdateDto, ak as users } from './shared/core.bkXizwPE.js';
6
+ import { s as schema, U as User, S as Session, I as Invitation, A as ApiToken, O as Organization, N as NewOrganization, a as OrganizationInitDto, b as OrganizationUpdateDto, c as NewMedia, M as Media, d as MediaFinalizeDto, e as MediaUpdateDto, C as CollectionDefinition, f as NewCollectionDefinition, E as Entry, g as NewEntry, D as DefinitionCreateDto, h as DefinitionUpdateDto, i as EntrySearchHit, j as EntryCreateDto, k as EntryUpdateDto, l as AudienceAsk, m as AudiencePanelData, n as ErrorType } from './shared/core.D0n0cwjD.js';
7
+ export { o as AUDIENCE_PERIODS, p as AcceptInvitationDto, q as Address, r as ApiTokenCreateDto, t as AudienceQuery, u as AudienceSummary, v as ERROR_TYPES, w as InviteDto, L as LoginDto, x as MediaRequestUploadDto, y as NewUser, P as PublicUser, R as RequestPasswordResetDto, z as SessionUser, B as UpdateOwnProfileDto, F as UserUpdateDto, G as acceptInvitationDto, H as addressSchema, J as apiTokenCreateDto, K as apiTokens, Q as audienceAskDto, T as audienceQuerySchema, V as audienceSummarySchema, W as collectionDefinitions, X as definitionCreateDto, Y as definitionDto, Z as definitionUpdateDto, _ as entries, $ as entryCreateDto, a0 as entryDto, a1 as entrySearchHitDto, a2 as entryUpdateDto, a3 as invitations, a4 as inviteDto, a5 as isErrorType, a6 as loginDto, a7 as media, a8 as mediaFinalizeDto, a9 as mediaRequestUploadDto, aa as mediaUpdateDto, ab as organization, ac as organizationInitDto, ad as organizationUpdateDto, ae as requestPasswordResetDto, af as sessions, ag as toPublicUser, ah as toSessionUser, ai as updateOwnProfileDto, aj as userUpdateDto, ak as users } from './shared/core.D0n0cwjD.js';
8
8
  export { FIELD_TYPES, FieldType, PUBLICATION_STATUSES, PublicationStatus } from './domains/collections/constants.js';
9
9
  export { FIELD_VALUE_SCHEMAS, FieldDefinition, buildDataSchema, fieldDefinitionSchema } from './domains/collections/utils.js';
10
10
  import 'drizzle-orm/sqlite-core';
@@ -567,6 +567,7 @@ declare class AudienceService {
567
567
  private readonly config;
568
568
  private readonly cache;
569
569
  private names;
570
+ private sitePages;
570
571
  private readonly viewers;
571
572
  constructor(collections: CollectionsService, config: {
572
573
  url?: string;
@@ -585,6 +586,17 @@ declare class AudienceService {
585
586
  summary(ask: AudienceAsk, viewer: string): Promise<AudiencePanelData>;
586
587
  /** The source's answer, or `null`: any failure only hides the panel. */
587
588
  private ask;
589
+ /**
590
+ * The segment a collection's pages carry on the public site, which the
591
+ * source filters them on. A theme decides its own addresses: a collection
592
+ * `posts` may live under `/blog`, `events` under `/agenda`. So it is read
593
+ * from the site itself: the most read page that ends with the slug of one
594
+ * of the collection's published entries gives it, as the segment before
595
+ * that slug. With none among them, the collection's own slug is asked.
596
+ */
597
+ private siteSegment;
598
+ /** The site's most read pages over the learning period, kept like the names. */
599
+ private mostReadPaths;
588
600
  private entrySlug;
589
601
  /**
590
602
  * Published entries by slug and collections by slug, to name the most read
@@ -725,14 +737,14 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
725
737
  input: void;
726
738
  output: {
727
739
  type: "commune" | "intercommunality" | "syndicate" | "other";
740
+ description: string | null;
728
741
  id: number;
729
742
  name: string;
730
- slug: string;
731
- description: string | null;
732
743
  updatedBy: string | null;
733
744
  legacyExtra: Record<string, unknown> | null;
734
745
  createdAt: string;
735
746
  updatedAt: string;
747
+ slug: string;
736
748
  address: {
737
749
  street?: string | undefined;
738
750
  postalCode?: string | undefined;
@@ -759,14 +771,14 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
759
771
  };
760
772
  output: {
761
773
  type: "commune" | "intercommunality" | "syndicate" | "other";
774
+ description: string | null;
762
775
  id: number;
763
776
  name: string;
764
- slug: string;
765
- description: string | null;
766
777
  updatedBy: string | null;
767
778
  legacyExtra: Record<string, unknown> | null;
768
779
  createdAt: string;
769
780
  updatedAt: string;
781
+ slug: string;
770
782
  address: {
771
783
  street?: string | undefined;
772
784
  postalCode?: string | undefined;
@@ -780,9 +792,9 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
780
792
  update: _trpc_server.TRPCMutationProcedure<{
781
793
  input: {
782
794
  type?: "commune" | "intercommunality" | "syndicate" | "other" | undefined;
795
+ description?: string | null | undefined;
783
796
  name?: string | undefined;
784
797
  slug?: string | undefined;
785
- description?: string | null | undefined;
786
798
  address?: {
787
799
  street?: string | undefined;
788
800
  postalCode?: string | undefined;
@@ -793,14 +805,14 @@ declare const organizationRouter: _trpc_server.TRPCBuiltRouter<{
793
805
  };
794
806
  output: {
795
807
  type: "commune" | "intercommunality" | "syndicate" | "other";
808
+ description: string | null;
796
809
  id: number;
797
810
  name: string;
798
- slug: string;
799
- description: string | null;
800
811
  updatedBy: string | null;
801
812
  legacyExtra: Record<string, unknown> | null;
802
813
  createdAt: string;
803
814
  updatedAt: string;
815
+ slug: string;
804
816
  address: {
805
817
  street?: string | undefined;
806
818
  postalCode?: string | undefined;
@@ -1373,38 +1385,38 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
1373
1385
  metaData?: Record<string, unknown> | undefined;
1374
1386
  };
1375
1387
  output: {
1388
+ filename: string;
1389
+ mime: string;
1390
+ metaData: Record<string, unknown> | null;
1391
+ alt: string | null;
1376
1392
  id: string;
1393
+ size: number;
1394
+ caption: string | null;
1395
+ objects: Record<string, unknown>;
1377
1396
  createdBy: string | null;
1378
1397
  updatedBy: string | null;
1379
1398
  legacyExtra: Record<string, unknown> | null;
1380
1399
  createdAt: string;
1381
1400
  updatedAt: string;
1382
- filename: string;
1383
- mime: string;
1384
- size: number;
1385
- alt: string | null;
1386
- caption: string | null;
1387
- objects: Record<string, unknown>;
1388
- metaData: Record<string, unknown> | null;
1389
1401
  };
1390
1402
  meta: object;
1391
1403
  }>;
1392
1404
  list: _trpc_server.TRPCQueryProcedure<{
1393
1405
  input: void;
1394
1406
  output: ({
1407
+ filename: string;
1408
+ mime: string;
1409
+ metaData: Record<string, unknown> | null;
1410
+ alt: string | null;
1395
1411
  id: string;
1412
+ size: number;
1413
+ caption: string | null;
1414
+ objects: Record<string, unknown>;
1396
1415
  createdBy: string | null;
1397
1416
  updatedBy: string | null;
1398
1417
  legacyExtra: Record<string, unknown> | null;
1399
1418
  createdAt: string;
1400
1419
  updatedAt: string;
1401
- filename: string;
1402
- mime: string;
1403
- size: number;
1404
- alt: string | null;
1405
- caption: string | null;
1406
- objects: Record<string, unknown>;
1407
- metaData: Record<string, unknown> | null;
1408
1420
  } & {
1409
1421
  objects: Record<string, string>;
1410
1422
  })[];
@@ -1415,19 +1427,19 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
1415
1427
  id: string;
1416
1428
  };
1417
1429
  output: {
1430
+ filename: string;
1431
+ mime: string;
1432
+ metaData: Record<string, unknown> | null;
1433
+ alt: string | null;
1418
1434
  id: string;
1435
+ size: number;
1436
+ caption: string | null;
1437
+ objects: Record<string, unknown>;
1419
1438
  createdBy: string | null;
1420
1439
  updatedBy: string | null;
1421
1440
  legacyExtra: Record<string, unknown> | null;
1422
1441
  createdAt: string;
1423
1442
  updatedAt: string;
1424
- filename: string;
1425
- mime: string;
1426
- size: number;
1427
- alt: string | null;
1428
- caption: string | null;
1429
- objects: Record<string, unknown>;
1430
- metaData: Record<string, unknown> | null;
1431
1443
  } & {
1432
1444
  objects: Record<string, string>;
1433
1445
  };
@@ -1443,19 +1455,19 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
1443
1455
  };
1444
1456
  };
1445
1457
  output: {
1458
+ filename: string;
1459
+ mime: string;
1460
+ metaData: Record<string, unknown> | null;
1461
+ alt: string | null;
1446
1462
  id: string;
1463
+ size: number;
1464
+ caption: string | null;
1465
+ objects: Record<string, unknown>;
1447
1466
  createdBy: string | null;
1448
1467
  updatedBy: string | null;
1449
1468
  legacyExtra: Record<string, unknown> | null;
1450
1469
  createdAt: string;
1451
1470
  updatedAt: string;
1452
- filename: string;
1453
- mime: string;
1454
- size: number;
1455
- alt: string | null;
1456
- caption: string | null;
1457
- objects: Record<string, unknown>;
1458
- metaData: Record<string, unknown> | null;
1459
1471
  };
1460
1472
  meta: object;
1461
1473
  }>;
@@ -1538,14 +1550,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1538
1550
  list: _trpc_server.TRPCQueryProcedure<{
1539
1551
  input: void;
1540
1552
  output: {
1553
+ description: string | null;
1541
1554
  id: string;
1542
1555
  name: string;
1556
+ createdBy: string | null;
1557
+ updatedBy: string | null;
1558
+ legacyExtra: Record<string, unknown> | null;
1559
+ createdAt: string;
1560
+ updatedAt: string;
1543
1561
  slug: string;
1544
- description: string | null;
1545
1562
  fields: {
1546
1563
  name: string;
1547
1564
  label: string;
1548
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1565
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1549
1566
  required: boolean;
1550
1567
  hidden: boolean;
1551
1568
  options?: string[] | undefined;
@@ -1554,11 +1571,6 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1554
1571
  editor: Record<string, unknown> | null;
1555
1572
  display: Record<string, unknown> | null;
1556
1573
  headings: Record<string, unknown> | null;
1557
- createdBy: string | null;
1558
- updatedBy: string | null;
1559
- legacyExtra: Record<string, unknown> | null;
1560
- createdAt: string;
1561
- updatedAt: string;
1562
1574
  }[];
1563
1575
  meta: object;
1564
1576
  }>;
@@ -1598,7 +1610,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1598
1610
  fields: {
1599
1611
  name: string;
1600
1612
  label: string;
1601
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1613
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1602
1614
  required?: boolean | undefined;
1603
1615
  hidden?: boolean | undefined;
1604
1616
  options?: string[] | undefined;
@@ -1611,14 +1623,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1611
1623
  slug?: string | undefined;
1612
1624
  };
1613
1625
  output: {
1626
+ description: string | null;
1614
1627
  id: string;
1615
1628
  name: string;
1629
+ createdBy: string | null;
1630
+ updatedBy: string | null;
1631
+ legacyExtra: Record<string, unknown> | null;
1632
+ createdAt: string;
1633
+ updatedAt: string;
1616
1634
  slug: string;
1617
- description: string | null;
1618
1635
  fields: {
1619
1636
  name: string;
1620
1637
  label: string;
1621
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1638
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1622
1639
  required: boolean;
1623
1640
  hidden: boolean;
1624
1641
  options?: string[] | undefined;
@@ -1627,11 +1644,6 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1627
1644
  editor: Record<string, unknown> | null;
1628
1645
  display: Record<string, unknown> | null;
1629
1646
  headings: Record<string, unknown> | null;
1630
- createdBy: string | null;
1631
- updatedBy: string | null;
1632
- legacyExtra: Record<string, unknown> | null;
1633
- createdAt: string;
1634
- updatedAt: string;
1635
1647
  };
1636
1648
  meta: object;
1637
1649
  }>;
@@ -1639,16 +1651,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1639
1651
  input: {
1640
1652
  id: string;
1641
1653
  data: {
1654
+ description?: string | null | undefined;
1642
1655
  name?: string | undefined;
1643
1656
  slug?: string | undefined;
1644
- description?: string | null | undefined;
1645
1657
  editor?: Record<string, unknown> | null | undefined;
1646
1658
  display?: Record<string, unknown> | null | undefined;
1647
1659
  headings?: Record<string, unknown> | null | undefined;
1648
1660
  fields?: {
1649
1661
  name: string;
1650
1662
  label: string;
1651
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1663
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1652
1664
  required?: boolean | undefined;
1653
1665
  hidden?: boolean | undefined;
1654
1666
  options?: string[] | undefined;
@@ -1657,14 +1669,19 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1657
1669
  };
1658
1670
  };
1659
1671
  output: {
1672
+ description: string | null;
1660
1673
  id: string;
1661
1674
  name: string;
1675
+ createdBy: string | null;
1676
+ updatedBy: string | null;
1677
+ legacyExtra: Record<string, unknown> | null;
1678
+ createdAt: string;
1679
+ updatedAt: string;
1662
1680
  slug: string;
1663
- description: string | null;
1664
1681
  fields: {
1665
1682
  name: string;
1666
1683
  label: string;
1667
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1684
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1668
1685
  required: boolean;
1669
1686
  hidden: boolean;
1670
1687
  options?: string[] | undefined;
@@ -1673,11 +1690,6 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1673
1690
  editor: Record<string, unknown> | null;
1674
1691
  display: Record<string, unknown> | null;
1675
1692
  headings: Record<string, unknown> | null;
1676
- createdBy: string | null;
1677
- updatedBy: string | null;
1678
- legacyExtra: Record<string, unknown> | null;
1679
- createdAt: string;
1680
- updatedAt: string;
1681
1693
  };
1682
1694
  meta: object;
1683
1695
  }>;
@@ -1836,12 +1848,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1836
1848
  output: {
1837
1849
  id: string;
1838
1850
  data: Record<string, unknown>;
1839
- slug: string;
1840
1851
  createdBy: string | null;
1841
1852
  updatedBy: string | null;
1842
1853
  legacyExtra: Record<string, unknown> | null;
1843
1854
  createdAt: string;
1844
1855
  updatedAt: string;
1856
+ slug: string;
1845
1857
  title: string;
1846
1858
  collectionId: string;
1847
1859
  related: string[] | null;
@@ -1865,12 +1877,12 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
1865
1877
  output: {
1866
1878
  id: string;
1867
1879
  data: Record<string, unknown>;
1868
- slug: string;
1869
1880
  createdBy: string | null;
1870
1881
  updatedBy: string | null;
1871
1882
  legacyExtra: Record<string, unknown> | null;
1872
1883
  createdAt: string;
1873
1884
  updatedAt: string;
1885
+ slug: string;
1874
1886
  title: string;
1875
1887
  collectionId: string;
1876
1888
  related: string[] | null;
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import{homedir as St}from"node:os";import{join as L}from"node:path";import{z as r}from"zod";import{Database as Mt}from"bun:sqlite";import{mkdirSync as Dt,existsSync as Tt}from"node:fs";import{drizzle as Ct}from"drizzle-orm/bun-sqlite";import{migrate as Rt}from"drizzle-orm/bun-sqlite/migrator";import{z as kt,B as h,C as p,D as y,F as _,E as w,u as J,a as Z,v as R,w as X,o as ye,x as we,y as fe,m as ee,b as ge,G as k,t as Ee,s as ve,H as b,r as _e,p as Oe,q as Ie,I,J as a,l as Ue,i as Ne,j as K,k as be,h as Ae,f as Se,g as Me,e as De,c as Te}from"./shared/core.BR6-3c3l.mjs";export{A as AUDIENCE_PERIODS,K as addressSchema,d as audienceQuerySchema,n as isErrorType}from"./shared/core.BR6-3c3l.mjs";import{sql as m,eq as c,and as A,isNull as $,gt as q,desc as S,notExists as xt,or as te,lt as Ce,isNotNull as Re,inArray as ie,like as ke,asc as se}from"drizzle-orm";import{S3Client as $t,PutObjectCommand as xe,HeadObjectCommand as Bt,DeleteObjectsCommand as Pt,GetObjectCommand as jt}from"@aws-sdk/client-s3";import{getSignedUrl as $e}from"@aws-sdk/s3-request-presigner";import{initTRPC as Lt,TRPCError as z}from"@trpc/server";import{randomBytes as ne,createHash as Kt}from"node:crypto";import{SignJWT as qt,jwtVerify as zt}from"jose";import{consola as Be}from"consola";import{nanoid as Pe}from"nanoid";import{buildDataSchema as je}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS,fieldDefinitionSchema}from"./domains/collections/utils.mjs";import{PUBLICATION_STATUSES as Le}from"./domains/collections/constants.mjs";export{FIELD_TYPES}from"./domains/collections/constants.mjs";import"drizzle-zod";import"drizzle-orm/sqlite-core";const x=r.string().min(1),Ft=r.object({COMMUN_DATA_DIR:r.string().default(L(St(),".commun")),COMMUN_MIGRATIONS_DIR:r.string().optional(),COMMUN_S3_ENDPOINT:x,COMMUN_S3_REGION:r.string().default("fr-par"),COMMUN_S3_BUCKET:x,COMMUN_S3_ACCESS_KEY:x,COMMUN_S3_SECRET_KEY:x,COMMUN_EMAIL_WEBHOOK_URL:x,COMMUN_EMAIL_WEBHOOK_TOKEN:r.string().optional(),COMMUN_ADMIN_URL:r.string().optional(),COMMUN_JWT_SECRET:x,OPEN_COMMUNE_AUDIENCE_URL:r.url().optional(),OPEN_COMMUNE_AUDIENCE_TOKEN:r.string().optional(),OPEN_COMMUNE_AUDIENCE_VIEWERS:r.string().optional()});function Ke(i=process.env){return Ft.parse({COMMUN_DATA_DIR:i.COMMUN_DATA_DIR,COMMUN_MIGRATIONS_DIR:i.COMMUN_MIGRATIONS_DIR,COMMUN_S3_ENDPOINT:i.COMMUN_S3_ENDPOINT,COMMUN_S3_REGION:i.COMMUN_S3_REGION,COMMUN_S3_BUCKET:i.COMMUN_S3_BUCKET,COMMUN_S3_ACCESS_KEY:i.COMMUN_S3_ACCESS_KEY,COMMUN_S3_SECRET_KEY:i.COMMUN_S3_SECRET_KEY,COMMUN_EMAIL_WEBHOOK_URL:i.COMMUN_EMAIL_WEBHOOK_URL,COMMUN_EMAIL_WEBHOOK_TOKEN:i.COMMUN_EMAIL_WEBHOOK_TOKEN,COMMUN_ADMIN_URL:i.COMMUN_ADMIN_URL,COMMUN_JWT_SECRET:i.COMMUN_JWT_SECRET,OPEN_COMMUNE_AUDIENCE_URL:i.OPEN_COMMUNE_AUDIENCE_URL||void 0,OPEN_COMMUNE_AUDIENCE_TOKEN:i.OPEN_COMMUNE_AUDIENCE_TOKEN||void 0,OPEN_COMMUNE_AUDIENCE_VIEWERS:i.OPEN_COMMUNE_AUDIENCE_VIEWERS||void 0})}function Ht(){const i=import.meta.dir;return i?L(i,"..","..","..","drizzle"):void 0}function qe(i,e){const t=e??Ht();Dt(i,{recursive:!0});const s=new Mt(L(i,"commun.db"));s.exec("PRAGMA journal_mode=WAL"),s.exec("PRAGMA foreign_keys=ON"),s.exec("PRAGMA busy_timeout=5000");const n=Ct({client:s,schema:kt});return t&&Tt(L(t,"meta","_journal.json"))&&Rt(n,{migrationsFolder:t}),n}class Q{constructor(e){this.config=e}static fromEnv(e){return new Q({url:e.COMMUN_EMAIL_WEBHOOK_URL,token:e.COMMUN_EMAIL_WEBHOOK_TOKEN})}async sendEvent(e){const t=await fetch(this.config.url,{method:"POST",headers:{"content-type":"application/json",...this.config.token?{authorization:`Bearer ${this.config.token}`}:{}},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`email webhook ${t.status}: ${(await t.text()).slice(0,200)}`)}}class ze{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(m`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Fe=168*3600,Yt="medias/";class He{constructor(e){this.config=e,this.client=new $t({region:e.region,endpoint:e.endpoint,forcePathStyle:!0,credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,s){return $e(this.client,new xe({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:s}),{expiresIn:Fe})}async put(e,t,s){await this.client.send(new xe({Bucket:this.config.bucket,Key:e,Body:t,ContentType:s}))}async head(e){try{return{size:(await this.client.send(new Bt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Pt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Yt)?Promise.resolve(this.publicUrl(e)):$e(this.client,new jt({Bucket:this.config.bucket,Key:e}),{expiresIn:Fe})}publicUrl(e){const t=this.config.endpoint.replace(/\/+$/,""),s=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${s}`}}function Ye(i){return new He({endpoint:i.COMMUN_S3_ENDPOINT,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const E={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class F extends Error{}function f(i,e){return class extends F{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const re=(i,e)=>i instanceof Error&&i.message.includes("UNIQUE constraint failed")&&i.message.includes(e),H=Lt.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof F?{type:t.type}:{}}}}}),U=H.router,Wt=H.mergeRouters,We=H.procedure,oe=H.middleware,Gt=oe(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof F)throw new z({code:t.trpcCode,message:t.message,cause:t})}return e}),C=We.use(Gt),Ge=i=>oe(({ctx:e,next:t})=>{if(!e.session)throw new z({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new z({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),l=C.use(Ge()),v=C.use(Ge("admin")),Vt=U({ping:C.query(({ctx:i})=>i.services.health.check())});class Ve{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(h).where(c(h.email,e)).get()}async findUserById(e){return this.db.select().from(h).where(c(h.id,e)).get()}async listUsers(){return this.db.select().from(h).all()}async hasAnyUser(){return this.db.select({id:h.id}).from(h).limit(1).all().length>0}async deleteUser(e){this.db.delete(h).where(c(h.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(h).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(c(h.id,t.id)).returning().get():this.db.insert(h).values(e).returning().get()}async insertSession(e){return this.db.insert(p).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:p,user:h}).from(p).innerJoin(h,c(h.id,p.userId)).where(A(c(p.id,e),$(p.revokedAt),q(p.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(p).set({revokedAt:t}).where(c(p.id,e)).run()}async findSessionById(e){return this.db.select().from(p).where(c(p.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(p).where(A(c(p.userId,e),$(p.revokedAt),q(p.expiresAt,t))).orderBy(S(p.createdAt)).all()}async updateUser(e,t){return this.db.update(h).set(t).where(c(h.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(y).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(y).where(A(c(y.tokenHash,e),$(y.usedAt),q(y.expiresAt,t))).get()}async listPendingInvitations(e){return this.db.select().from(y).where(A($(y.usedAt),q(y.expiresAt,e),xt(this.db.select({one:m`1`}).from(h).where(c(h.email,y.email))))).orderBy(S(y.createdAt)).all()}async deleteInvitation(e){return!!this.db.delete(y).where(c(y.id,e)).returning().get()}async markInvitationUsed(e,t){this.db.update(y).set({usedAt:t}).where(c(y.id,e)).run()}async insertApiToken(e){return this.db.insert(_).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(_).where(A(c(_.tokenHash,e),$(_.revokedAt))).get()}async touchApiToken(e,t){this.db.update(_).set({lastUsedAt:t}).where(c(_.id,e)).run()}async revokeApiToken(e,t){this.db.update(_).set({revokedAt:t}).where(c(_.id,e)).run()}async listApiTokens(){return this.db.select({id:_.id,name:_.name,lastUsedAt:_.lastUsedAt,revokedAt:_.revokedAt,createdAt:_.createdAt}).from(_).orderBy(S(_.createdAt)).all()}async purgeExpired(e){this.db.delete(p).where(te(Ce(p.expiresAt,e),Re(p.revokedAt))).run(),this.db.delete(y).where(te(Ce(y.expiresAt,e),Re(y.usedAt))).run()}}const ae=f(w.USER_NOT_FOUND,E.NOT_FOUND),Qe=f(w.SESSION_NOT_FOUND,E.NOT_FOUND),ce=f(w.INVITATION_INVALID,E.BAD_REQUEST),Je=f(w.CANNOT_REMOVE_SELF,E.BAD_REQUEST),Ze=f(w.TOO_MANY_ATTEMPTS,E.TOO_MANY_REQUESTS),B=i=>Kt("sha256").update(i).digest("hex"),M=()=>new Date().toISOString(),Qt=720*3600*1e3,Xe=168*3600*1e3,Jt=Bun.password.hashSync("commun-dummy-password-for-timing"),Zt=5*6e4,Xt=10,P=new Map,et=i=>{const e=Date.now(),t=(P.get(i)??[]).filter(s=>e-s<Zt);return t.length?P.set(i,t):P.delete(i),t},ei=i=>et(i).length>=Xt,ti=i=>{P.set(i,[...et(i),Date.now()])},ii=i=>P.delete(i);class tt{constructor(e,t={}){this.repository=e,this.options=t}jwtKey(){if(!this.options.jwtSecret)throw new Error("COMMUN_JWT_SECRET manquant \u2014 requis pour signer les sessions (fail-fast au boot)");return new TextEncoder().encode(this.options.jwtSecret)}async sendEmailEvent(e){try{await this.options.email?.sendEvent(e)}catch(t){Be.warn(`[email] \xE9chec d'\xE9mission ${e.eventName} \u2192 ${e.email}: ${String(t)}`)}}hashPassword(e){return Bun.password.hash(e)}verifyPassword(e,t){return Bun.password.verify(e,t)}async login(e,t,s){const n=e.toLowerCase();if(ei(n))throw new Ze;const o=await this.repository.findUserByEmail(n),d=await this.verifyPassword(t,o?.passwordHash??Jt);return!o?.passwordHash||!d?(ti(n),null):(ii(n),this.createSession(o,s))}async createSession(e,t){const s=new Date(Date.now()+Qt).toISOString(),n=await this.repository.insertSession({userId:e.id,expiresAt:s,ua:t?.ua??null,ip:t?.ip??null});return{token:await new qt({session:n.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(s)).sign(this.jwtKey()),session:{sessionId:n.id,user:e,expiresAt:s}}}async verifySession(e){let t;try{const{payload:n}=await zt(e,this.jwtKey());if(typeof n.session!="string")return null;t=n.session}catch{return null}const s=await this.repository.findActiveSessionWithUser(t,M());return s?{sessionId:s.session.id,user:s.user,expiresAt:s.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,M())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,M())).map(s=>({id:s.id,createdAt:s.createdAt,expiresAt:s.expiresAt,ua:s.ua,ip:s.ip,current:s.id===t}))}async revokeOwnSession(e,t){const s=await this.repository.findSessionById(t);if(!s||s.userId!==e)throw new Qe(`session not found: ${t}`);await this.repository.revokeSession(t,M())}async purgeExpired(){await this.repository.purgeExpired(M())}async createInvitation(e){const t=ne(32).toString("base64url"),s=new Date(Date.now()+Xe).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:B(t),expiresAt:s}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:s}}async listPendingInvitations(){return(await this.repository.listPendingInvitations(M())).map(({id:e,email:t,role:s,expiresAt:n})=>({id:e,email:t,role:s,expiresAt:n}))}async revokeInvitation(e){if(!await this.repository.deleteInvitation(e))throw new ce}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const s=ne(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:B(s),expiresAt:new Date(Date.now()+Xe).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${s}`}})}async acceptInvitation(e,t){const s=await this.repository.findValidInvitation(B(e),M());if(!s)throw new ce;const n=await this.repository.findUserByEmail(s.email),o=t.name?.trim()||n?.name||s.email.split("@")[0]||"Membre",d=await this.repository.activateUser({email:s.email,name:o,passwordHash:await this.hashPassword(t.password),role:s.role});return await this.repository.markInvitationUsed(s.id,M()),d}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new ae(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new Je;await this.repository.deleteUser(t)}async updateUser(e,t){const s=await this.repository.updateUser(e,t);if(!s)throw new ae(`user not found: ${e}`);return s}async createApiToken(e){const t=`commun_${ne(24).toString("base64url")}`,s=await this.repository.insertApiToken({name:e,tokenHash:B(t)});return{token:t,record:s}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(B(e));return t?(await this.repository.touchApiToken(t.id,M()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,M())}async listApiTokens(){return this.repository.listApiTokens()}}const it=U({login:C.input(ye).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new z({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:X(t.session.user,{audience:i.services.audience.visibleTo(t.session.user.email)})}}),logout:l.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:l.query(({ctx:i})=>({user:X(i.session.user,{audience:i.services.audience.visibleTo(i.session.user.email)})})),sessions:U({list:l.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:l.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:C.input(Z).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:R(t)}}),requestPasswordReset:C.input(J).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),st=U({list:v.query(async({ctx:i})=>(await i.services.users.listUsers()).map(R)),directory:l.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:v.input(r.object({id:r.string()})).query(async({ctx:i,input:e})=>R(await i.services.users.getUser(e.id))),invite:v.input(ee).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:v.input(fe).mutation(async({ctx:i,input:e})=>R(await i.services.users.updateUser(e.id,e.data))),updateOwnProfile:l.input(we).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.updateUser(i.session.user.id,e);return{user:R(t)}}),remove:v.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),nt=U({list:v.query(({ctx:i})=>i.services.users.listApiTokens()),create:v.input(ge).mutation(async({ctx:i,input:e})=>{const{token:t,record:s}=await i.services.users.createApiToken(e.name);return{token:t,id:s.id,name:s.name}}),revoke:v.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),rt=U({create:v.input(ee).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),list:v.query(({ctx:i})=>i.services.users.listPendingInvitations()),revoke:v.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeInvitation(e.id),{revoked:e.id})),accept:C.input(Z).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:R(t)}}),requestPasswordReset:C.input(J).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))});class ot{constructor(e){this.db=e}async get(){return this.db.select().from(k).where(c(k.id,1)).get()}async insert(e){return this.db.insert(k).values({...e,id:1}).returning().get()}async update(e){return this.db.update(k).set(e).where(c(k.id,1)).returning().get()}}const at=f(w.ORGANIZATION_NOT_INITIALIZED,E.NOT_FOUND),ct=f(w.ORGANIZATION_ALREADY_INITIALIZED,E.BAD_REQUEST),lt=f(w.DEPLOY_HOOK_MISSING,E.BAD_REQUEST),le=f(w.DEPLOY_FAILED,E.INTERNAL_SERVER_ERROR),si=3e4;class dt{constructor(e,t={}){this.repository=e,this.options=t}async get(){return await this.repository.get()??null}async init(e){if(await this.repository.get())throw new ct;return this.repository.insert(e)}async update(e,t){const s=await this.repository.update({...e,updatedBy:t??null});if(!s)throw new at;return s}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new lt;const t=this.options.fetchImpl??fetch;let s;try{s=await t(e,{signal:AbortSignal.timeout(si)})}catch(n){throw new le(`deploy hook unreachable: ${n instanceof Error?n.message:String(n)}`)}if(!s.ok)throw new le(`deploy hook: ${s.status} ${s.statusText}`);return{status:s.status}}}const ut=U({get:l.query(({ctx:i})=>i.services.organization.get()),init:v.input(ve).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:v.input(Ee).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:l.mutation(({ctx:i})=>i.services.organization.deploy())});class ht{constructor(e){this.db=e}async insert(e){return this.db.insert(b).values(e).returning().get()}async findById(e){return this.db.select().from(b).where(c(b.id,e)).get()}async list(){return this.db.select().from(b).orderBy(S(b.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(b).where(m`json_extract(${b.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(b).set(t).where(c(b.id,e)).returning().get()}async delete(e){this.db.delete(b).where(c(b.id,e)).run()}}const Y=f(w.MEDIA_NOT_FOUND,E.NOT_FOUND),de=f(w.UNSUPPORTED_MIME,E.BAD_REQUEST),pt=f(w.UPLOAD_INCOMPLETE,E.BAD_REQUEST),ue=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"]),ni=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],he=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",mt="medias/";class yt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,s){if(!ue.has(t))throw new de(`unsupported mime type: ${t}`);const n=`${mt}${Pe(10)}/${he(e)}`;return{key:n,url:await this.storage.presignedPutUrl(n,t,s)}}async finalize(e,t){const s=await this.storage.head(e.key);if(!s)throw new pt(`object not found in storage: ${e.key}`);const n=await this.repository.insert({filename:he(e.filename),mime:e.mime,size:s.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Be.info(`[media] resize \xE0 impl\xE9menter pour ${n.id} (${ni.join(", ")})`),n}async uploadDirect(e,t,s,n,o){if(!ue.has(t))throw new de(`unsupported mime type: ${t}`);const d=`${mt}${Pe(10)}/${he(e)}`;return await this.storage.put(d,s,t),this.finalize({key:d,filename:e,mime:t,metaData:n},o)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,s){const n=await this.repository.update(e,{...t,updatedBy:s??null});if(!n)throw new Y(`media not found: ${e}`);return n}async remove(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);const s=t.objects;await this.storage.remove([s.original,...Object.values(s.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async objectUrls(e){const t=e.objects,s={original:await this.storage.url(t.original)};for(const[n,o]of Object.entries(t.variants??{}))s[n]=await this.storage.url(o);return s}}const wt=U({requestUpload:l.input(Ie).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:l.input(Oe).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:l.query(({ctx:i})=>i.services.media.listResolved()),get:l.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:l.input(r.object({id:r.string(),data:_e})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:l.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))});class ft{constructor(e){this.db=e}async list(){return this.db.select().from(I).all()}async findBySlug(e){return this.db.select().from(I).where(c(I.slug,e)).get()}async findById(e){return this.db.select().from(I).where(c(I.id,e)).get()}async findByLegacyId(e){return this.db.select().from(I).where(m`json_extract(${I.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(I).values(e).returning().get()}async update(e,t){return this.db.update(I).set(t).where(c(I.id,e)).returning().get()}async delete(e){return this.db.delete(I).where(c(I.id,e)).returning().get()}}const ri="[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*";class gt{constructor(e){this.db=e}async list(e){return this.db.select().from(a).where(c(a.collectionId,e)).orderBy(S(a.updatedAt)).all()}narrowing(e){const t=[];if(e.collectionId&&t.push(c(a.collectionId,e.collectionId)),e.status?.length&&t.push(ie(a.status,e.status)),e.search?.trim()&&t.push(this.matching(e.search)),(e.date?.gte||e.date?.lte)&&t.push(m`exists (select 1 from ${this.spans()} where ${this.within(e.date)})`),e.references?.length){const s=m.join(e.references.map(n=>m`${n}`),m`, `);t.push(m`exists (select 1 from json_tree(${a.data}) where type = 'text' and value in (${s}))`)}return t.length>0?A(...t):void 0}spans(){return m`(select min(value) as span_start, max(value) as span_end from json_tree(${a.data})
2
- where type = 'text' and value glob ${ri}
3
- group by case when path = '$' or typeof(key) = 'integer' then id else parent end)`}within(e={}){const t=[];return e.gte&&t.push(m`substr(span_end, 1, ${e.gte.length}) >= ${e.gte}`),e.lte&&t.push(m`substr(span_start, 1, ${e.lte.length}) <= ${e.lte}`),t.length>0?A(...t):m`1`}dateKey(e,t){const s=t?m`max(span_start)`:m`min(span_start)`;return m`(select ${s} from ${this.spans()} where ${this.within(e)})`}matching(e){const t=`%${e.trim()}%`;return te(ke(a.title,t),ke(a.data,t))}async search(e){const t=[this.matching(e.search)];return e.collectionIds?.length&&t.push(ie(a.collectionId,e.collectionIds)),e.status?.length&&t.push(ie(a.status,e.status)),this.db.select().from(a).where(A(...t)).orderBy(S(a.updatedAt)).limit(e.limit).all()}async countMatching(e){const[t]=this.db.select({total:m`count(*)`}).from(a).where(this.narrowing(e)).all();return t?.total??0}async listRecent(e){return this.db.select().from(a).orderBy(S(a.updatedAt)).limit(e).all()}async listPaginated(e){const t=e.order??(e.date?"date_asc":"recent"),s=o=>{const d=this.dateKey(e.date,o);return[m`${d} is null`,o?S(d):se(d)]},n={recent:()=>[S(a.updatedAt)],oldest:()=>[se(a.updatedAt)],title:()=>[se(a.title)],date_asc:()=>s(!1),date_desc:()=>s(!0)};return this.db.select().from(a).where(this.narrowing(e)).orderBy(...n[t]()).limit(e.limit).offset(e.skip).all()}async listPublished(e){return this.db.select().from(a).where(A(c(a.collectionId,e),c(a.status,"published"))).orderBy(S(a.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(a).where(A(c(a.collectionId,e),c(a.slug,t))).get()}async findById(e){return this.db.select().from(a).where(c(a.id,e)).get()}async findByDataField(e,t,s){return this.db.select().from(a).where(A(c(a.collectionId,e),m`json_extract(${a.data}, ${`$.${t}`}) = ${s}`)).get()}async insert(e){return this.db.insert(a).values(e).returning().get()}async update(e,t){return this.db.update(a).set(t).where(c(a.id,e)).returning().get()}async delete(e){return this.db.delete(a).where(c(a.id,e)).returning().get()}}const W=f(w.COLLECTION_NOT_FOUND,E.NOT_FOUND),G=f(w.ENTRY_NOT_FOUND,E.NOT_FOUND),Et=f(w.INVALID_ENTRY_DATA,E.BAD_REQUEST),pe=f(w.DUPLICATE_SLUG,E.BAD_REQUEST);function vt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function V(i,e){const t=[];for(const s of i){if(s.type!=="relation")continue;const n=e[s.name];typeof n=="string"&&n?t.push(n):Array.isArray(n)&&t.push(...n.filter(o=>typeof o=="string"))}return[...new Set(t)]}class _t{constructor(e,t,s){this.definitions=e,this.entries=t,this.media=s}async listDefinitions(){return this.definitions.list()}async getDefinition(e){const t=await this.definitions.findBySlug(e)??await this.definitions.findById(e);if(!t)throw new W(`collection not found: ${e}`);return t}async createDefinition(e,t){const s=e.slug||await this.uniqueDefinitionSlug(vt(e.name));try{return await this.definitions.insert({...e,slug:s,createdBy:t??null,updatedBy:t??null})}catch(n){throw this.definitionSlugConflict(n,s)}}async updateDefinition(e,t,s){const n=await this.definitions.update(e,{...t,updatedBy:s??null}).catch(o=>{throw this.definitionSlugConflict(o,t.slug??"")});if(!n)throw new W(`collection not found: ${e}`);return n}async removeDefinition(e){if(!await this.definitions.delete(e))throw new W(`collection not found: ${e}`)}validateData(e,t){const s=je(e.fields).safeParse(t);if(!s.success)throw new Et(`invalid data for collection ${e.slug}: ${s.error.message}`);return s.data}async listEntries(e){return this.entries.list((await this.getDefinition(e)).id)}async getEntry(e){const t=await this.entries.findById(e);if(!t)throw new G(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){return this.entries.listPaginated({...t,collectionId:await this.collectionIdOf(e),skip:t.skip??0,limit:t.limit??20})}async collectionIdOf(e){return e?(await this.getDefinition(e)).id:void 0}async listRecentEntries(e=5){return this.entries.listRecent(e)}async countEntries(e,t={}){return this.entries.countMatching({...t,collectionId:await this.collectionIdOf(e)})}async searchEntries(e){const t=e.collections?.length?await Promise.all(e.collections.map(n=>this.getDefinition(n))):await this.definitions.list(),s=new Map(t.map(n=>[n.id,n.slug]));return(await this.entries.search({search:e.query,collectionIds:e.collections?.length?[...s.keys()]:void 0,status:e.status,limit:e.limit??20})).map(n=>({...n,collectionSlug:s.get(n.collectionId)??""}))}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,s){const n=await this.getDefinition(e),o=this.validateData(n,t.data),d=await this.uniqueEntrySlug(n.id,t.slug||vt(t.title)),u=await this.entries.insert({...t,slug:d,data:o,collectionId:n.id,createdBy:s??null,updatedBy:s??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(n,u.id,[],V(n.fields,o)),u}async updateEntry(e,t,s){const n=await this.entries.findById(e);if(!n)throw new G(`entry not found: ${e}`);const o=await this.getDefinition(n.collectionId),d=new Set(o.fields.map(N=>N.name)),u=Object.fromEntries(Object.entries(n.data??{}).filter(([N])=>!d.has(N))),O=t.data?{...n.data,...t.data}:n.data,g=Object.fromEntries(Object.entries(O).filter(([N])=>d.has(N)||N in(t.data??{}))),D=t.data?{...u,...this.validateData(o,g)}:void 0,T={...t,updatedBy:s??null};D&&(T.data=D),t.status==="published"&&!t.publishedAt&&(T.publishedAt=new Date().toISOString());try{const N=await this.entries.update(e,T);return D&&await this.linkRelations(o,e,V(o.fields,n.data),V(o.fields,D)),t.related&&await this.linkRelations(o,e,n.related??[],t.related),N}catch(N){throw this.entrySlugConflict(N,o.slug,t.slug??n.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new G(`entry not found: ${e}`);const s=await this.getDefinition(t.collectionId);await this.linkRelations(s,e,V(s.fields,t.data),[]),await this.entries.delete(e)}definitionSlugConflict(e,t){return re(e,"collection_definitions.slug")?new pe(`le slug "${t}" est d\xE9j\xE0 celui d'une collection`):e}entrySlugConflict(e,t,s){return re(e,"entries.slug")?new pe(`le slug "${s}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let s=t;for(let n=1;await this.entries.findBySlug(e,s);n++)s=`${t}-${n}`;return s}async uniqueDefinitionSlug(e){let t=e;for(let s=1;await this.definitions.findBySlug(t);s++)t=`${e}-${s}`;return t}async linkRelations(e,t,s,n){const o=n.filter(u=>!s.includes(u)),d=s.filter(u=>!n.includes(u));for(const u of o){const O=await this.entries.findById(u);if(!O)continue;const g=new Set(O.related??[]);g.add(t),await this.entries.update(u,{related:[...g]})}for(const u of d){const O=await this.entries.findById(u);O&&await this.entries.update(u,{related:(O.related??[]).filter(g=>g!==t)})}}}const me=r.string().describe("Id or slug of the collection"),Ot=r.array(r.enum(Le)).optional().describe("Keep only entries in these publication statuses"),It=r.string().regex(/^\d{4}(-(0[1-9]|1[0-2])(-(0[1-9]|[12]\d|3[01]))?)?$/,"An ISO 8601 date: YYYY, YYYY-MM or YYYY-MM-DD"),Ut={collectionId:me.optional().describe("Id or slug of the collection; every collection of the site when omitted"),status:Ot,search:r.string().max(200).optional().describe("Keep only entries whose title or field values contain this text"),date:r.object({gte:It.optional().describe("From this date, included"),lte:It.optional().describe("Up to this date, included")}).optional().describe('Keep only entries with a date in this period, read from any of their fields (the sessions of an event). Each bound is an ISO 8601 date at the precision meant, and is compared at that precision: {gte:"2026",lte:"2026"} is the year 2026, {gte:"2026-11",lte:"2026-11"} November 2026, {gte:"<today>"} what is to come, {lte:"<today>"} what is past. An entry is kept when one of its dates, or the span of a session, overlaps the period. Entries with no date are left out'),references:r.array(r.string()).optional().describe("Keep only entries whose fields reference one of these entries, by id (a theme, a place)")},Nt=U({list:l.query(({ctx:i})=>i.services.collections.listDefinitions()),get:l.input(r.object({idOrSlug:me})).output(Me).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:v.input(Se).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:v.input(r.object({id:r.string(),data:Ae})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:v.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:U({get:l.input(r.object({id:r.string().describe("Id of the entry")})).output(K).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),search:l.input(r.object({query:r.string().trim().min(1).max(200).describe("Text to look for"),collections:r.array(me).optional().describe("Search only these collections (ids or slugs); all of them when omitted"),status:Ot,limit:r.number().int().min(1).max(50).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(be)).query(({ctx:i,input:e})=>i.services.collections.searchEntries(e)),list:l.input(r.object({...Ut,order:r.enum(["recent","oldest","title","date_asc","date_desc"]).optional().describe("recent (last updated first, the default), oldest, title, date_asc (the earliest date first, the default with a period) or date_desc (the latest first: the last one held)"),skip:r.number().int().min(0).optional().describe("Entries to skip, for paging"),limit:r.number().int().min(1).max(100).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(K)).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),recent:l.input(r.object({limit:r.number().int().min(1).max(20).optional()}).optional()).output(r.array(K)).query(({ctx:i,input:e})=>i.services.collections.listRecentEntries(e?.limit)),count:l.input(r.object(Ut)).query(({ctx:i,input:e})=>i.services.collections.countEntries(e.collectionId,e)),create:l.input(r.object({collectionId:r.string(),data:Ne})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:l.input(r.object({id:r.string(),data:Ue})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:l.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})}),j=f(w.AUDIENCE_UNAVAILABLE,E.NOT_FOUND),oi=6e4,ai=10*6e4,ci=2e3;class bt{constructor(e,t){this.collections=e,this.config=t,this.viewers=(t.viewers??"").split(",").map(s=>s.trim().toLowerCase()).filter(Boolean)}cache=new Map;names;viewers;visibleTo(e){return this.config.url?!this.viewers.length||this.viewers.includes(e.trim().toLowerCase()):!1}async summary(e,t){if(!this.config.url)throw new j("no audience source");if(!this.visibleTo(t))throw new j("not among the viewers");const s=`${e.period}:${e.collection??""}:${e.entry??""}`,n=this.cache.get(s);if(n&&Date.now()-n.at<oi)return n.value;const o=e.entry?await this.entrySlug(e.entry):void 0;if(e.entry&&!o)throw new j(`unknown entry ${e.entry}`);const d=await this.ask(this.config.url,new URLSearchParams({period:String(e.period),...e.collection?{collection:e.collection}:{},...o?{entry:o}:{}}));if(!d)throw new j("the source did not answer");const u=await this.knownNames(),O={...d,top:(d.top??[]).map(g=>{const D=g.path.split("/").filter(Boolean),T=u.entries.get(D.at(-1)??""),N=!T&&D.length===1&&g.collection?u.collections.get(g.collection):void 0;return{path:g.path,collection:g.collection??null,visits:g.views,title:g.path==="/"?"Accueil":T?.title??N??g.path,entryId:T?.id??null}})};return this.cache.set(s,{at:Date.now(),value:O}),O}async ask(e,t){const s=this.config.fetchImpl??fetch;try{const n=await s(`${e.replace(/\/$/,"")}/summary?${t}`,{headers:this.config.token?{authorization:`Bearer ${this.config.token}`}:{},signal:AbortSignal.timeout(ci)});if(!n.ok)return null;const o=De.safeParse(await n.json());return o.success?o.data:null}catch{return null}}async entrySlug(e){try{return(await this.collections.getEntry(e)).slug||void 0}catch{return}}async knownNames(){if(this.names&&Date.now()-this.names.at<ai)return this.names;const e=new Map,t=new Map;for(const s of await this.collections.listDefinitions()){t.set(s.slug,s.name);for(const n of await this.collections.listPublishedEntries(s.id))e.set(n.slug,{id:n.id,title:n.title})}return this.names={at:Date.now(),entries:e,collections:t},this.names}}const At=U({summary:l.input(Te).query(({ctx:i,input:e})=>i.services.audience.summary(e,i.session.user.email))});function li({env:i}={}){const e=i??Ke(),t=qe(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),s=Ye(e),n=Q.fromEnv(e),o=new tt(new Ve(t),{email:n,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),d=new ht(t),u=new yt(d,s),O=new _t(new ft(t),new gt(t),u),g=new dt(new ot(t)),D=new bt(O,{url:e.OPEN_COMMUNE_AUDIENCE_URL,token:e.OPEN_COMMUNE_AUDIENCE_TOKEN,viewers:e.OPEN_COMMUNE_AUDIENCE_VIEWERS}),T={health:new ze(t),users:o,organization:g,media:u,collections:O,audience:D};return{env:e,db:t,storage:s,services:T}}const di=U({health:Vt,auth:it,users:st,invitations:rt,apiTokens:nt,organization:ut,media:wt,collections:Nt,audience:At});export{ue as ALLOWED_MIME,bt as AudienceService,j as AudienceUnavailableError,Je as CannotRemoveSelfError,W as CollectionNotFoundError,_t as CollectionsService,ft as DefinitionRepository,le as DeployFailedError,lt as DeployHookMissingError,F as DomainError,pe as DuplicateSlugError,w as ERROR_TYPES,Q as EmailService,G as EntryNotFoundError,gt as EntryRepository,ze as HealthService,Et as InvalidEntryDataError,ce as InvitationInvalidError,Y as MediaNotFoundError,ht as MediaRepository,yt as MediaService,ct as OrganizationAlreadyInitializedError,at as OrganizationNotInitializedError,ot as OrganizationRepository,dt as OrganizationService,Le as PUBLICATION_STATUSES,He as S3Storage,Qe as SessionNotFoundError,Ze as TooManyAttemptsError,de as UnsupportedMimeError,pt as UploadIncompleteError,ae as UserNotFoundError,Ve as UsersRepository,tt as UsersService,Z as acceptInvitationDto,v as adminProcedure,ge as apiTokenCreateDto,_ as apiTokens,nt as apiTokensRouter,di as appRouter,Te as audienceAskDto,At as audienceRouter,De as audienceSummarySchema,it as authRouter,je as buildDataSchema,I as collectionDefinitions,Nt as collectionsRouter,qe as connectDb,li as createCore,Ye as createStorage,f as createTypedError,Se as definitionCreateDto,Me as definitionDto,Ae as definitionUpdateDto,a as entries,Ne as entryCreateDto,K as entryDto,be as entrySearchHitDto,Ue as entryUpdateDto,y as invitations,rt as invitationsRouter,ee as inviteDto,re as isUniqueViolation,ye as loginDto,b as media,Oe as mediaFinalizeDto,Ie as mediaRequestUploadDto,wt as mediaRouter,_e as mediaUpdateDto,Wt as mergeRouters,oe as middleware,k as organization,ve as organizationInitDto,ut as organizationRouter,Ee as organizationUpdateDto,Ke as parseEnv,C as procedure,l as protectedProcedure,We as publicProcedure,J as requestPasswordResetDto,U as router,p as sessions,R as toPublicUser,X as toSessionUser,we as updateOwnProfileDto,fe as userUpdateDto,h as users,st as usersRouter};
1
+ import{homedir as Dt}from"node:os";import{join as L}from"node:path";import{z as r}from"zod";import{Database as Tt}from"bun:sqlite";import{mkdirSync as Rt,existsSync as Ct}from"node:fs";import{drizzle as kt}from"drizzle-orm/bun-sqlite";import{migrate as xt}from"drizzle-orm/bun-sqlite/migrator";import{z as $t,B as h,C as p,D as y,F as v,E as w,u as J,a as Z,v as C,w as X,o as ye,x as we,y as fe,m as ee,b as ge,G as k,t as Ee,s as ve,H as N,r as _e,p as Oe,q as Ue,I,J as a,l as Ie,i as be,j as K,k as Ne,h as Ae,f as Se,g as Me,e as De,c as Te}from"./shared/core.BR6-3c3l.mjs";export{A as AUDIENCE_PERIODS,K as addressSchema,d as audienceQuerySchema,n as isErrorType}from"./shared/core.BR6-3c3l.mjs";import{sql as m,eq as c,and as S,isNull as $,gt as q,desc as M,notExists as Bt,or as te,lt as Re,isNotNull as Ce,inArray as ie,like as ke,asc as se}from"drizzle-orm";import{S3Client as Pt,PutObjectCommand as xe,HeadObjectCommand as jt,DeleteObjectsCommand as Lt,GetObjectCommand as Kt}from"@aws-sdk/client-s3";import{getSignedUrl as $e}from"@aws-sdk/s3-request-presigner";import{initTRPC as qt,TRPCError as z}from"@trpc/server";import{randomBytes as ne,createHash as zt}from"node:crypto";import{SignJWT as Ft,jwtVerify as Ht}from"jose";import{consola as Be}from"consola";import{nanoid as Pe}from"nanoid";import{buildDataSchema as je}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS,fieldDefinitionSchema}from"./domains/collections/utils.mjs";import{PUBLICATION_STATUSES as Le}from"./domains/collections/constants.mjs";export{FIELD_TYPES}from"./domains/collections/constants.mjs";import"drizzle-zod";import"drizzle-orm/sqlite-core";const x=r.string().min(1),Yt=r.object({COMMUN_DATA_DIR:r.string().default(L(Dt(),".commun")),COMMUN_MIGRATIONS_DIR:r.string().optional(),COMMUN_S3_ENDPOINT:x,COMMUN_S3_REGION:r.string().default("fr-par"),COMMUN_S3_BUCKET:x,COMMUN_S3_ACCESS_KEY:x,COMMUN_S3_SECRET_KEY:x,COMMUN_EMAIL_WEBHOOK_URL:x,COMMUN_EMAIL_WEBHOOK_TOKEN:r.string().optional(),COMMUN_ADMIN_URL:r.string().optional(),COMMUN_JWT_SECRET:x,OPEN_COMMUNE_AUDIENCE_URL:r.url().optional(),OPEN_COMMUNE_AUDIENCE_TOKEN:r.string().optional(),OPEN_COMMUNE_AUDIENCE_VIEWERS:r.string().optional()});function Ke(i=process.env){return Yt.parse({COMMUN_DATA_DIR:i.COMMUN_DATA_DIR,COMMUN_MIGRATIONS_DIR:i.COMMUN_MIGRATIONS_DIR,COMMUN_S3_ENDPOINT:i.COMMUN_S3_ENDPOINT,COMMUN_S3_REGION:i.COMMUN_S3_REGION,COMMUN_S3_BUCKET:i.COMMUN_S3_BUCKET,COMMUN_S3_ACCESS_KEY:i.COMMUN_S3_ACCESS_KEY,COMMUN_S3_SECRET_KEY:i.COMMUN_S3_SECRET_KEY,COMMUN_EMAIL_WEBHOOK_URL:i.COMMUN_EMAIL_WEBHOOK_URL,COMMUN_EMAIL_WEBHOOK_TOKEN:i.COMMUN_EMAIL_WEBHOOK_TOKEN,COMMUN_ADMIN_URL:i.COMMUN_ADMIN_URL,COMMUN_JWT_SECRET:i.COMMUN_JWT_SECRET,OPEN_COMMUNE_AUDIENCE_URL:i.OPEN_COMMUNE_AUDIENCE_URL||void 0,OPEN_COMMUNE_AUDIENCE_TOKEN:i.OPEN_COMMUNE_AUDIENCE_TOKEN||void 0,OPEN_COMMUNE_AUDIENCE_VIEWERS:i.OPEN_COMMUNE_AUDIENCE_VIEWERS||void 0})}function Wt(){const i=import.meta.dir;return i?L(i,"..","..","..","drizzle"):void 0}function qe(i,e){const t=e??Wt();Rt(i,{recursive:!0});const s=new Tt(L(i,"commun.db"));s.exec("PRAGMA journal_mode=WAL"),s.exec("PRAGMA foreign_keys=ON"),s.exec("PRAGMA busy_timeout=5000");const n=kt({client:s,schema:$t});return t&&Ct(L(t,"meta","_journal.json"))&&xt(n,{migrationsFolder:t}),n}class Q{constructor(e){this.config=e}static fromEnv(e){return new Q({url:e.COMMUN_EMAIL_WEBHOOK_URL,token:e.COMMUN_EMAIL_WEBHOOK_TOKEN})}async sendEvent(e){const t=await fetch(this.config.url,{method:"POST",headers:{"content-type":"application/json",...this.config.token?{authorization:`Bearer ${this.config.token}`}:{}},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`email webhook ${t.status}: ${(await t.text()).slice(0,200)}`)}}class ze{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(m`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Fe=168*3600,Gt="medias/";class He{constructor(e){this.config=e,this.client=new Pt({region:e.region,endpoint:e.endpoint,forcePathStyle:!0,credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,s){return $e(this.client,new xe({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:s}),{expiresIn:Fe})}async put(e,t,s){await this.client.send(new xe({Bucket:this.config.bucket,Key:e,Body:t,ContentType:s}))}async head(e){try{return{size:(await this.client.send(new jt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Lt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Gt)?Promise.resolve(this.publicUrl(e)):$e(this.client,new Kt({Bucket:this.config.bucket,Key:e}),{expiresIn:Fe})}publicUrl(e){const t=this.config.endpoint.replace(/\/+$/,""),s=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${s}`}}function Ye(i){return new He({endpoint:i.COMMUN_S3_ENDPOINT,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const g={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class F extends Error{}function f(i,e){return class extends F{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const re=(i,e)=>i instanceof Error&&i.message.includes("UNIQUE constraint failed")&&i.message.includes(e),H=qt.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof F?{type:t.type}:{}}}}}),b=H.router,Vt=H.mergeRouters,We=H.procedure,oe=H.middleware,Qt=oe(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof F)throw new z({code:t.trpcCode,message:t.message,cause:t})}return e}),T=We.use(Qt),Ge=i=>oe(({ctx:e,next:t})=>{if(!e.session)throw new z({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new z({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),l=T.use(Ge()),E=T.use(Ge("admin")),Jt=b({ping:T.query(({ctx:i})=>i.services.health.check())});class Ve{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(h).where(c(h.email,e)).get()}async findUserById(e){return this.db.select().from(h).where(c(h.id,e)).get()}async listUsers(){return this.db.select().from(h).all()}async hasAnyUser(){return this.db.select({id:h.id}).from(h).limit(1).all().length>0}async deleteUser(e){this.db.delete(h).where(c(h.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(h).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(c(h.id,t.id)).returning().get():this.db.insert(h).values(e).returning().get()}async insertSession(e){return this.db.insert(p).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:p,user:h}).from(p).innerJoin(h,c(h.id,p.userId)).where(S(c(p.id,e),$(p.revokedAt),q(p.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(p).set({revokedAt:t}).where(c(p.id,e)).run()}async findSessionById(e){return this.db.select().from(p).where(c(p.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(p).where(S(c(p.userId,e),$(p.revokedAt),q(p.expiresAt,t))).orderBy(M(p.createdAt)).all()}async updateUser(e,t){return this.db.update(h).set(t).where(c(h.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(y).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(y).where(S(c(y.tokenHash,e),$(y.usedAt),q(y.expiresAt,t))).get()}async listPendingInvitations(e){return this.db.select().from(y).where(S($(y.usedAt),q(y.expiresAt,e),Bt(this.db.select({one:m`1`}).from(h).where(c(h.email,y.email))))).orderBy(M(y.createdAt)).all()}async deleteInvitation(e){return!!this.db.delete(y).where(c(y.id,e)).returning().get()}async markInvitationUsed(e,t){this.db.update(y).set({usedAt:t}).where(c(y.id,e)).run()}async insertApiToken(e){return this.db.insert(v).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(v).where(S(c(v.tokenHash,e),$(v.revokedAt))).get()}async touchApiToken(e,t){this.db.update(v).set({lastUsedAt:t}).where(c(v.id,e)).run()}async revokeApiToken(e,t){this.db.update(v).set({revokedAt:t}).where(c(v.id,e)).run()}async listApiTokens(){return this.db.select({id:v.id,name:v.name,lastUsedAt:v.lastUsedAt,revokedAt:v.revokedAt,createdAt:v.createdAt}).from(v).orderBy(M(v.createdAt)).all()}async purgeExpired(e){this.db.delete(p).where(te(Re(p.expiresAt,e),Ce(p.revokedAt))).run(),this.db.delete(y).where(te(Re(y.expiresAt,e),Ce(y.usedAt))).run()}}const ae=f(w.USER_NOT_FOUND,g.NOT_FOUND),Qe=f(w.SESSION_NOT_FOUND,g.NOT_FOUND),ce=f(w.INVITATION_INVALID,g.BAD_REQUEST),Je=f(w.CANNOT_REMOVE_SELF,g.BAD_REQUEST),Ze=f(w.TOO_MANY_ATTEMPTS,g.TOO_MANY_REQUESTS),B=i=>zt("sha256").update(i).digest("hex"),D=()=>new Date().toISOString(),Zt=720*3600*1e3,Xe=168*3600*1e3,Xt=Bun.password.hashSync("commun-dummy-password-for-timing"),ei=5*6e4,ti=10,P=new Map,et=i=>{const e=Date.now(),t=(P.get(i)??[]).filter(s=>e-s<ei);return t.length?P.set(i,t):P.delete(i),t},ii=i=>et(i).length>=ti,si=i=>{P.set(i,[...et(i),Date.now()])},ni=i=>P.delete(i);class tt{constructor(e,t={}){this.repository=e,this.options=t}jwtKey(){if(!this.options.jwtSecret)throw new Error("COMMUN_JWT_SECRET manquant \u2014 requis pour signer les sessions (fail-fast au boot)");return new TextEncoder().encode(this.options.jwtSecret)}async sendEmailEvent(e){try{await this.options.email?.sendEvent(e)}catch(t){Be.warn(`[email] \xE9chec d'\xE9mission ${e.eventName} \u2192 ${e.email}: ${String(t)}`)}}hashPassword(e){return Bun.password.hash(e)}verifyPassword(e,t){return Bun.password.verify(e,t)}async login(e,t,s){const n=e.toLowerCase();if(ii(n))throw new Ze;const o=await this.repository.findUserByEmail(n),u=await this.verifyPassword(t,o?.passwordHash??Xt);return!o?.passwordHash||!u?(si(n),null):(ni(n),this.createSession(o,s))}async createSession(e,t){const s=new Date(Date.now()+Zt).toISOString(),n=await this.repository.insertSession({userId:e.id,expiresAt:s,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Ft({session:n.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(s)).sign(this.jwtKey()),session:{sessionId:n.id,user:e,expiresAt:s}}}async verifySession(e){let t;try{const{payload:n}=await Ht(e,this.jwtKey());if(typeof n.session!="string")return null;t=n.session}catch{return null}const s=await this.repository.findActiveSessionWithUser(t,D());return s?{sessionId:s.session.id,user:s.user,expiresAt:s.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,D())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,D())).map(s=>({id:s.id,createdAt:s.createdAt,expiresAt:s.expiresAt,ua:s.ua,ip:s.ip,current:s.id===t}))}async revokeOwnSession(e,t){const s=await this.repository.findSessionById(t);if(!s||s.userId!==e)throw new Qe(`session not found: ${t}`);await this.repository.revokeSession(t,D())}async purgeExpired(){await this.repository.purgeExpired(D())}async createInvitation(e){const t=ne(32).toString("base64url"),s=new Date(Date.now()+Xe).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:B(t),expiresAt:s}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:s}}async listPendingInvitations(){return(await this.repository.listPendingInvitations(D())).map(({id:e,email:t,role:s,expiresAt:n})=>({id:e,email:t,role:s,expiresAt:n}))}async revokeInvitation(e){if(!await this.repository.deleteInvitation(e))throw new ce}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const s=ne(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:B(s),expiresAt:new Date(Date.now()+Xe).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${s}`}})}async acceptInvitation(e,t){const s=await this.repository.findValidInvitation(B(e),D());if(!s)throw new ce;const n=await this.repository.findUserByEmail(s.email),o=t.name?.trim()||n?.name||s.email.split("@")[0]||"Membre",u=await this.repository.activateUser({email:s.email,name:o,passwordHash:await this.hashPassword(t.password),role:s.role});return await this.repository.markInvitationUsed(s.id,D()),u}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new ae(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new Je;await this.repository.deleteUser(t)}async updateUser(e,t){const s=await this.repository.updateUser(e,t);if(!s)throw new ae(`user not found: ${e}`);return s}async createApiToken(e){const t=`commun_${ne(24).toString("base64url")}`,s=await this.repository.insertApiToken({name:e,tokenHash:B(t)});return{token:t,record:s}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(B(e));return t?(await this.repository.touchApiToken(t.id,D()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,D())}async listApiTokens(){return this.repository.listApiTokens()}}const it=b({login:T.input(ye).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new z({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:X(t.session.user,{audience:i.services.audience.visibleTo(t.session.user.email)})}}),logout:l.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:l.query(({ctx:i})=>({user:X(i.session.user,{audience:i.services.audience.visibleTo(i.session.user.email)})})),sessions:b({list:l.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:l.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:T.input(Z).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:C(t)}}),requestPasswordReset:T.input(J).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),st=b({list:E.query(async({ctx:i})=>(await i.services.users.listUsers()).map(C)),directory:l.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:E.input(r.object({id:r.string()})).query(async({ctx:i,input:e})=>C(await i.services.users.getUser(e.id))),invite:E.input(ee).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:E.input(fe).mutation(async({ctx:i,input:e})=>C(await i.services.users.updateUser(e.id,e.data))),updateOwnProfile:l.input(we).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.updateUser(i.session.user.id,e);return{user:C(t)}}),remove:E.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),nt=b({list:E.query(({ctx:i})=>i.services.users.listApiTokens()),create:E.input(ge).mutation(async({ctx:i,input:e})=>{const{token:t,record:s}=await i.services.users.createApiToken(e.name);return{token:t,id:s.id,name:s.name}}),revoke:E.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),rt=b({create:E.input(ee).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),list:E.query(({ctx:i})=>i.services.users.listPendingInvitations()),revoke:E.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeInvitation(e.id),{revoked:e.id})),accept:T.input(Z).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:C(t)}}),requestPasswordReset:T.input(J).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))});class ot{constructor(e){this.db=e}async get(){return this.db.select().from(k).where(c(k.id,1)).get()}async insert(e){return this.db.insert(k).values({...e,id:1}).returning().get()}async update(e){return this.db.update(k).set(e).where(c(k.id,1)).returning().get()}}const at=f(w.ORGANIZATION_NOT_INITIALIZED,g.NOT_FOUND),ct=f(w.ORGANIZATION_ALREADY_INITIALIZED,g.BAD_REQUEST),lt=f(w.DEPLOY_HOOK_MISSING,g.BAD_REQUEST),le=f(w.DEPLOY_FAILED,g.INTERNAL_SERVER_ERROR),ri=3e4;class ut{constructor(e,t={}){this.repository=e,this.options=t}async get(){return await this.repository.get()??null}async init(e){if(await this.repository.get())throw new ct;return this.repository.insert(e)}async update(e,t){const s=await this.repository.update({...e,updatedBy:t??null});if(!s)throw new at;return s}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new lt;const t=this.options.fetchImpl??fetch;let s;try{s=await t(e,{signal:AbortSignal.timeout(ri)})}catch(n){throw new le(`deploy hook unreachable: ${n instanceof Error?n.message:String(n)}`)}if(!s.ok)throw new le(`deploy hook: ${s.status} ${s.statusText}`);return{status:s.status}}}const dt=b({get:l.query(({ctx:i})=>i.services.organization.get()),init:E.input(ve).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:E.input(Ee).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:l.mutation(({ctx:i})=>i.services.organization.deploy())});class ht{constructor(e){this.db=e}async insert(e){return this.db.insert(N).values(e).returning().get()}async findById(e){return this.db.select().from(N).where(c(N.id,e)).get()}async list(){return this.db.select().from(N).orderBy(M(N.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(N).where(m`json_extract(${N.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(N).set(t).where(c(N.id,e)).returning().get()}async delete(e){this.db.delete(N).where(c(N.id,e)).run()}}const Y=f(w.MEDIA_NOT_FOUND,g.NOT_FOUND),ue=f(w.UNSUPPORTED_MIME,g.BAD_REQUEST),pt=f(w.UPLOAD_INCOMPLETE,g.BAD_REQUEST),de=new Set(["image/jpeg","image/png","image/webp","image/gif","application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet"]),oi=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],he=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",mt="medias/";class yt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,s){if(!de.has(t))throw new ue(`unsupported mime type: ${t}`);const n=`${mt}${Pe(10)}/${he(e)}`;return{key:n,url:await this.storage.presignedPutUrl(n,t,s)}}async finalize(e,t){const s=await this.storage.head(e.key);if(!s)throw new pt(`object not found in storage: ${e.key}`);const n=await this.repository.insert({filename:he(e.filename),mime:e.mime,size:s.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Be.info(`[media] resize \xE0 impl\xE9menter pour ${n.id} (${oi.join(", ")})`),n}async uploadDirect(e,t,s,n,o){if(!de.has(t))throw new ue(`unsupported mime type: ${t}`);const u=`${mt}${Pe(10)}/${he(e)}`;return await this.storage.put(u,s,t),this.finalize({key:u,filename:e,mime:t,metaData:n},o)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,s){const n=await this.repository.update(e,{...t,updatedBy:s??null});if(!n)throw new Y(`media not found: ${e}`);return n}async remove(e){const t=await this.repository.findById(e);if(!t)throw new Y(`media not found: ${e}`);const s=t.objects;await this.storage.remove([s.original,...Object.values(s.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async objectUrls(e){const t=e.objects,s={original:await this.storage.url(t.original)};for(const[n,o]of Object.entries(t.variants??{}))s[n]=await this.storage.url(o);return s}}const wt=b({requestUpload:l.input(Ue).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:l.input(Oe).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:l.query(({ctx:i})=>i.services.media.listResolved()),get:l.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:l.input(r.object({id:r.string(),data:_e})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:l.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))});class ft{constructor(e){this.db=e}async list(){return this.db.select().from(I).all()}async findBySlug(e){return this.db.select().from(I).where(c(I.slug,e)).get()}async findById(e){return this.db.select().from(I).where(c(I.id,e)).get()}async findByLegacyId(e){return this.db.select().from(I).where(m`json_extract(${I.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(I).values(e).returning().get()}async update(e,t){return this.db.update(I).set(t).where(c(I.id,e)).returning().get()}async delete(e){return this.db.delete(I).where(c(I.id,e)).returning().get()}}const ai="[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*";class gt{constructor(e){this.db=e}async list(e){return this.db.select().from(a).where(c(a.collectionId,e)).orderBy(M(a.updatedAt)).all()}narrowing(e){const t=[];if(e.collectionId&&t.push(c(a.collectionId,e.collectionId)),e.status?.length&&t.push(ie(a.status,e.status)),e.search?.trim()&&t.push(this.matching(e.search)),(e.date?.gte||e.date?.lte)&&t.push(m`exists (select 1 from ${this.spans()} where ${this.within(e.date)})`),e.references?.length){const s=m.join(e.references.map(n=>m`${n}`),m`, `);t.push(m`exists (select 1 from json_tree(${a.data}) where type = 'text' and value in (${s}))`)}return t.length>0?S(...t):void 0}spans(){return m`(select min(value) as span_start, max(value) as span_end from json_tree(${a.data})
2
+ where type = 'text' and value glob ${ai}
3
+ group by case when path = '$' or typeof(key) = 'integer' then id else parent end)`}within(e={}){const t=[];return e.gte&&t.push(m`substr(span_end, 1, ${e.gte.length}) >= ${e.gte}`),e.lte&&t.push(m`substr(span_start, 1, ${e.lte.length}) <= ${e.lte}`),t.length>0?S(...t):m`1`}dateKey(e,t){const s=t?m`max(span_start)`:m`min(span_start)`;return m`(select ${s} from ${this.spans()} where ${this.within(e)})`}matching(e){const t=`%${e.trim()}%`;return te(ke(a.title,t),ke(a.data,t))}async search(e){const t=[this.matching(e.search)];return e.collectionIds?.length&&t.push(ie(a.collectionId,e.collectionIds)),e.status?.length&&t.push(ie(a.status,e.status)),this.db.select().from(a).where(S(...t)).orderBy(M(a.updatedAt)).limit(e.limit).all()}async countMatching(e){const[t]=this.db.select({total:m`count(*)`}).from(a).where(this.narrowing(e)).all();return t?.total??0}async listRecent(e){return this.db.select().from(a).orderBy(M(a.updatedAt)).limit(e).all()}async listPaginated(e){const t=e.order??(e.date?"date_asc":"recent"),s=o=>{const u=this.dateKey(e.date,o);return[m`${u} is null`,o?M(u):se(u)]},n={recent:()=>[M(a.updatedAt)],oldest:()=>[se(a.updatedAt)],title:()=>[se(a.title)],date_asc:()=>s(!1),date_desc:()=>s(!0)};return this.db.select().from(a).where(this.narrowing(e)).orderBy(...n[t]()).limit(e.limit).offset(e.skip).all()}async listPublished(e){return this.db.select().from(a).where(S(c(a.collectionId,e),c(a.status,"published"))).orderBy(M(a.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(a).where(S(c(a.collectionId,e),c(a.slug,t))).get()}async findById(e){return this.db.select().from(a).where(c(a.id,e)).get()}async findByDataField(e,t,s){return this.db.select().from(a).where(S(c(a.collectionId,e),m`json_extract(${a.data}, ${`$.${t}`}) = ${s}`)).get()}async insert(e){return this.db.insert(a).values(e).returning().get()}async update(e,t){return this.db.update(a).set(t).where(c(a.id,e)).returning().get()}async delete(e){return this.db.delete(a).where(c(a.id,e)).returning().get()}}const W=f(w.COLLECTION_NOT_FOUND,g.NOT_FOUND),G=f(w.ENTRY_NOT_FOUND,g.NOT_FOUND),Et=f(w.INVALID_ENTRY_DATA,g.BAD_REQUEST),pe=f(w.DUPLICATE_SLUG,g.BAD_REQUEST);function vt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function V(i,e){const t=[];for(const s of i){if(s.type!=="relation")continue;const n=e[s.name];typeof n=="string"&&n?t.push(n):Array.isArray(n)&&t.push(...n.filter(o=>typeof o=="string"))}return[...new Set(t)]}class _t{constructor(e,t,s){this.definitions=e,this.entries=t,this.media=s}async listDefinitions(){return this.definitions.list()}async getDefinition(e){const t=await this.definitions.findBySlug(e)??await this.definitions.findById(e);if(!t)throw new W(`collection not found: ${e}`);return t}async createDefinition(e,t){const s=e.slug||await this.uniqueDefinitionSlug(vt(e.name));try{return await this.definitions.insert({...e,slug:s,createdBy:t??null,updatedBy:t??null})}catch(n){throw this.definitionSlugConflict(n,s)}}async updateDefinition(e,t,s){const n=await this.definitions.update(e,{...t,updatedBy:s??null}).catch(o=>{throw this.definitionSlugConflict(o,t.slug??"")});if(!n)throw new W(`collection not found: ${e}`);return n}async removeDefinition(e){if(!await this.definitions.delete(e))throw new W(`collection not found: ${e}`)}validateData(e,t){const s=je(e.fields).safeParse(t);if(!s.success)throw new Et(`invalid data for collection ${e.slug}: ${s.error.message}`);return s.data}async listEntries(e){return this.entries.list((await this.getDefinition(e)).id)}async getEntry(e){const t=await this.entries.findById(e);if(!t)throw new G(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){return this.entries.listPaginated({...t,collectionId:await this.collectionIdOf(e),skip:t.skip??0,limit:t.limit??20})}async collectionIdOf(e){return e?(await this.getDefinition(e)).id:void 0}async listRecentEntries(e=5){return this.entries.listRecent(e)}async countEntries(e,t={}){return this.entries.countMatching({...t,collectionId:await this.collectionIdOf(e)})}async searchEntries(e){const t=e.collections?.length?await Promise.all(e.collections.map(n=>this.getDefinition(n))):await this.definitions.list(),s=new Map(t.map(n=>[n.id,n.slug]));return(await this.entries.search({search:e.query,collectionIds:e.collections?.length?[...s.keys()]:void 0,status:e.status,limit:e.limit??20})).map(n=>({...n,collectionSlug:s.get(n.collectionId)??""}))}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,s){const n=await this.getDefinition(e),o=this.validateData(n,t.data),u=await this.uniqueEntrySlug(n.id,t.slug||vt(t.title)),d=await this.entries.insert({...t,slug:u,data:o,collectionId:n.id,createdBy:s??null,updatedBy:s??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(n,d.id,[],V(n.fields,o)),d}async updateEntry(e,t,s){const n=await this.entries.findById(e);if(!n)throw new G(`entry not found: ${e}`);const o=await this.getDefinition(n.collectionId),u=new Set(o.fields.map(O=>O.name)),d=Object.fromEntries(Object.entries(n.data??{}).filter(([O])=>!u.has(O))),U=t.data?{...n.data,...t.data}:n.data,A=Object.fromEntries(Object.entries(U).filter(([O])=>u.has(O)||O in(t.data??{}))),_=t.data?{...d,...this.validateData(o,A)}:void 0,R={...t,updatedBy:s??null};_&&(R.data=_),t.status==="published"&&!t.publishedAt&&(R.publishedAt=new Date().toISOString());try{const O=await this.entries.update(e,R);return _&&await this.linkRelations(o,e,V(o.fields,n.data),V(o.fields,_)),t.related&&await this.linkRelations(o,e,n.related??[],t.related),O}catch(O){throw this.entrySlugConflict(O,o.slug,t.slug??n.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new G(`entry not found: ${e}`);const s=await this.getDefinition(t.collectionId);await this.linkRelations(s,e,V(s.fields,t.data),[]),await this.entries.delete(e)}definitionSlugConflict(e,t){return re(e,"collection_definitions.slug")?new pe(`le slug "${t}" est d\xE9j\xE0 celui d'une collection`):e}entrySlugConflict(e,t,s){return re(e,"entries.slug")?new pe(`le slug "${s}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let s=t;for(let n=1;await this.entries.findBySlug(e,s);n++)s=`${t}-${n}`;return s}async uniqueDefinitionSlug(e){let t=e;for(let s=1;await this.definitions.findBySlug(t);s++)t=`${e}-${s}`;return t}async linkRelations(e,t,s,n){const o=n.filter(d=>!s.includes(d)),u=s.filter(d=>!n.includes(d));for(const d of o){const U=await this.entries.findById(d);if(!U)continue;const A=new Set(U.related??[]);A.add(t),await this.entries.update(d,{related:[...A]})}for(const d of u){const U=await this.entries.findById(d);U&&await this.entries.update(d,{related:(U.related??[]).filter(A=>A!==t)})}}}const me=r.string().describe("Id or slug of the collection"),Ot=r.array(r.enum(Le)).optional().describe("Keep only entries in these publication statuses"),Ut=r.string().regex(/^\d{4}(-(0[1-9]|1[0-2])(-(0[1-9]|[12]\d|3[01]))?)?$/,"An ISO 8601 date: YYYY, YYYY-MM or YYYY-MM-DD"),It={collectionId:me.optional().describe("Id or slug of the collection; every collection of the site when omitted"),status:Ot,search:r.string().max(200).optional().describe("Keep only entries whose title or field values contain this text"),date:r.object({gte:Ut.optional().describe("From this date, included"),lte:Ut.optional().describe("Up to this date, included")}).optional().describe('Keep only entries with a date in this period, read from any of their fields (the sessions of an event). Each bound is an ISO 8601 date at the precision meant, and is compared at that precision: {gte:"2026",lte:"2026"} is the year 2026, {gte:"2026-11",lte:"2026-11"} November 2026, {gte:"<today>"} what is to come, {lte:"<today>"} what is past. An entry is kept when one of its dates, or the span of a session, overlaps the period. Entries with no date are left out'),references:r.array(r.string()).optional().describe("Keep only entries whose fields reference one of these entries, by id (a theme, a place)")},bt=b({list:l.query(({ctx:i})=>i.services.collections.listDefinitions()),get:l.input(r.object({idOrSlug:me})).output(Me).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:E.input(Se).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:E.input(r.object({id:r.string(),data:Ae})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:E.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:b({get:l.input(r.object({id:r.string().describe("Id of the entry")})).output(K).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),search:l.input(r.object({query:r.string().trim().min(1).max(200).describe("Text to look for"),collections:r.array(me).optional().describe("Search only these collections (ids or slugs); all of them when omitted"),status:Ot,limit:r.number().int().min(1).max(50).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(Ne)).query(({ctx:i,input:e})=>i.services.collections.searchEntries(e)),list:l.input(r.object({...It,order:r.enum(["recent","oldest","title","date_asc","date_desc"]).optional().describe("recent (last updated first, the default), oldest, title, date_asc (the earliest date first, the default with a period) or date_desc (the latest first: the last one held)"),skip:r.number().int().min(0).optional().describe("Entries to skip, for paging"),limit:r.number().int().min(1).max(100).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(K)).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),recent:l.input(r.object({limit:r.number().int().min(1).max(20).optional()}).optional()).output(r.array(K)).query(({ctx:i,input:e})=>i.services.collections.listRecentEntries(e?.limit)),count:l.input(r.object(It)).query(({ctx:i,input:e})=>i.services.collections.countEntries(e.collectionId,e)),create:l.input(r.object({collectionId:r.string(),data:be})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:l.input(r.object({id:r.string(),data:Ie})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:l.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})}),j=f(w.AUDIENCE_UNAVAILABLE,g.NOT_FOUND),ci=6e4,Nt=10*6e4,li=2e3,ui=5,di=90;class At{constructor(e,t){this.collections=e,this.config=t,this.viewers=(t.viewers??"").split(",").map(s=>s.trim().toLowerCase()).filter(Boolean)}cache=new Map;names;sitePages;viewers;visibleTo(e){return this.config.url?!this.viewers.length||this.viewers.includes(e.trim().toLowerCase()):!1}async summary(e,t){if(!this.config.url)throw new j("no audience source");if(!this.visibleTo(t))throw new j("not among the viewers");const s=`${e.period}:${e.collection??""}:${e.entry??""}`,n=this.cache.get(s);if(n&&Date.now()-n.at<ci)return n.value;const o=e.entry?await this.entrySlug(e.entry):void 0;if(e.entry&&!o)throw new j(`unknown entry ${e.entry}`);const u=e.collection?await this.siteSegment(e.collection):void 0,d=await this.ask(this.config.url,new URLSearchParams({period:String(e.period),...u?{collection:u}:{},...o?{entry:o}:{}}));if(!d)throw new j("the source did not answer");const U=await this.knownNames(),A={...d,top:(d.top??[]).slice(0,ui).map(_=>{const R=_.path.split("/").filter(Boolean),O=U.entries.get(R.at(-1)??""),Mt=!O&&R.length===1&&_.collection?U.collections.get(_.collection):void 0;return{path:_.path,collection:_.collection??null,visits:_.views,title:_.path==="/"?"Accueil":O?.title??Mt??_.path,entryId:O?.id??null}})};return this.cache.set(s,{at:Date.now(),value:A}),A}async ask(e,t){const s=this.config.fetchImpl??fetch;try{const n=await s(`${e.replace(/\/$/,"")}/summary?${t}`,{headers:this.config.token?{authorization:`Bearer ${this.config.token}`}:{},signal:AbortSignal.timeout(li)});if(!n.ok)return null;const o=De.safeParse(await n.json());return o.success?o.data:null}catch{return null}}async siteSegment(e){const t=await this.mostReadPaths();if(!t.length)return e;let s;try{s=new Set((await this.collections.listPublishedEntries(e)).map(n=>n.slug))}catch{return e}for(const n of t){const o=n.split("/").filter(Boolean),u=o.at(-1);if(o.length>=2&&u&&s.has(u))return o.at(-2)}return e}async mostReadPaths(){if(this.sitePages&&Date.now()-this.sitePages.at<Nt)return this.sitePages.paths;if(!this.config.url)return[];const e=await this.ask(this.config.url,new URLSearchParams({period:String(di)}));if(!e)return[];const t=(e.top??[]).map(s=>s.path);return this.sitePages={at:Date.now(),paths:t},t}async entrySlug(e){try{return(await this.collections.getEntry(e)).slug||void 0}catch{return}}async knownNames(){if(this.names&&Date.now()-this.names.at<Nt)return this.names;const e=new Map,t=new Map;for(const s of await this.collections.listDefinitions()){t.set(s.slug,s.name);for(const n of await this.collections.listPublishedEntries(s.id))e.set(n.slug,{id:n.id,title:n.title})}return this.names={at:Date.now(),entries:e,collections:t},this.names}}const St=b({summary:l.input(Te).query(({ctx:i,input:e})=>i.services.audience.summary(e,i.session.user.email))});function hi({env:i}={}){const e=i??Ke(),t=qe(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),s=Ye(e),n=Q.fromEnv(e),o=new tt(new Ve(t),{email:n,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),u=new ht(t),d=new yt(u,s),U=new _t(new ft(t),new gt(t),d),A=new ut(new ot(t)),_=new At(U,{url:e.OPEN_COMMUNE_AUDIENCE_URL,token:e.OPEN_COMMUNE_AUDIENCE_TOKEN,viewers:e.OPEN_COMMUNE_AUDIENCE_VIEWERS}),R={health:new ze(t),users:o,organization:A,media:d,collections:U,audience:_};return{env:e,db:t,storage:s,services:R}}const pi=b({health:Jt,auth:it,users:st,invitations:rt,apiTokens:nt,organization:dt,media:wt,collections:bt,audience:St});export{de as ALLOWED_MIME,At as AudienceService,j as AudienceUnavailableError,Je as CannotRemoveSelfError,W as CollectionNotFoundError,_t as CollectionsService,ft as DefinitionRepository,le as DeployFailedError,lt as DeployHookMissingError,F as DomainError,pe as DuplicateSlugError,w as ERROR_TYPES,Q as EmailService,G as EntryNotFoundError,gt as EntryRepository,ze as HealthService,Et as InvalidEntryDataError,ce as InvitationInvalidError,Y as MediaNotFoundError,ht as MediaRepository,yt as MediaService,ct as OrganizationAlreadyInitializedError,at as OrganizationNotInitializedError,ot as OrganizationRepository,ut as OrganizationService,Le as PUBLICATION_STATUSES,He as S3Storage,Qe as SessionNotFoundError,Ze as TooManyAttemptsError,ue as UnsupportedMimeError,pt as UploadIncompleteError,ae as UserNotFoundError,Ve as UsersRepository,tt as UsersService,Z as acceptInvitationDto,E as adminProcedure,ge as apiTokenCreateDto,v as apiTokens,nt as apiTokensRouter,pi as appRouter,Te as audienceAskDto,St as audienceRouter,De as audienceSummarySchema,it as authRouter,je as buildDataSchema,I as collectionDefinitions,bt as collectionsRouter,qe as connectDb,hi as createCore,Ye as createStorage,f as createTypedError,Se as definitionCreateDto,Me as definitionDto,Ae as definitionUpdateDto,a as entries,be as entryCreateDto,K as entryDto,Ne as entrySearchHitDto,Ie as entryUpdateDto,y as invitations,rt as invitationsRouter,ee as inviteDto,re as isUniqueViolation,ye as loginDto,N as media,Oe as mediaFinalizeDto,Ue as mediaRequestUploadDto,wt as mediaRouter,_e as mediaUpdateDto,Vt as mergeRouters,oe as middleware,k as organization,ve as organizationInitDto,dt as organizationRouter,Ee as organizationUpdateDto,Ke as parseEnv,T as procedure,l as protectedProcedure,We as publicProcedure,J as requestPasswordResetDto,b as router,p as sessions,C as toPublicUser,X as toSessionUser,we as updateOwnProfileDto,fe as userUpdateDto,h as users,st as usersRouter};
@@ -5,8 +5,8 @@ import { FIELD_TYPES, FieldType, PUBLICATION_STATUSES } from '../domains/collect
5
5
  import { FieldDefinition, fieldDefinitionSchema } from '../domains/collections/utils.mjs';
6
6
 
7
7
  declare const definitionCreateDto: z.ZodObject<{
8
- name: z.ZodString;
9
8
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
9
+ name: z.ZodString;
10
10
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
11
11
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
12
12
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -16,13 +16,13 @@ declare const definitionCreateDto: z.ZodObject<{
16
16
  type: z.ZodEnum<{
17
17
  number: "number";
18
18
  boolean: "boolean";
19
- json: "json";
20
19
  date: "date";
20
+ media: "media";
21
+ json: "json";
21
22
  text: "text";
23
+ select: "select";
22
24
  "rich-text": "rich-text";
23
- media: "media";
24
25
  relation: "relation";
25
- select: "select";
26
26
  steps: "steps";
27
27
  }>;
28
28
  required: z.ZodDefault<z.ZodBoolean>;
@@ -36,9 +36,9 @@ declare const definitionCreateDto: z.ZodObject<{
36
36
  in: {};
37
37
  }>;
38
38
  declare const definitionUpdateDto: z.ZodObject<{
39
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
39
40
  name: z.ZodOptional<z.ZodString>;
40
41
  slug: z.ZodOptional<z.ZodString>;
41
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
42
42
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
43
43
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
44
44
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -48,13 +48,13 @@ declare const definitionUpdateDto: z.ZodObject<{
48
48
  type: z.ZodEnum<{
49
49
  number: "number";
50
50
  boolean: "boolean";
51
- json: "json";
52
51
  date: "date";
52
+ media: "media";
53
+ json: "json";
53
54
  text: "text";
55
+ select: "select";
54
56
  "rich-text": "rich-text";
55
- media: "media";
56
57
  relation: "relation";
57
- select: "select";
58
58
  steps: "steps";
59
59
  }>;
60
60
  required: z.ZodDefault<z.ZodBoolean>;
@@ -151,7 +151,7 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
151
151
  data: {
152
152
  name: string;
153
153
  label: string;
154
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
154
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
155
155
  required: boolean;
156
156
  hidden: boolean;
157
157
  options?: string[] | undefined;
@@ -171,7 +171,7 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
171
171
  $type: {
172
172
  name: string;
173
173
  label: string;
174
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
174
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
175
175
  required: boolean;
176
176
  hidden: boolean;
177
177
  options?: string[] | undefined;
@@ -337,13 +337,13 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
337
337
  type: z.ZodUnion<[z.ZodEnum<{
338
338
  number: "number";
339
339
  boolean: "boolean";
340
- json: "json";
341
340
  date: "date";
341
+ media: "media";
342
+ json: "json";
342
343
  text: "text";
344
+ select: "select";
343
345
  "rich-text": "rich-text";
344
- media: "media";
345
346
  relation: "relation";
346
- select: "select";
347
347
  steps: "steps";
348
348
  }>, z.ZodString]>;
349
349
  required: z.ZodDefault<z.ZodBoolean>;
@@ -717,9 +717,9 @@ declare const organizationInitDto: z.ZodObject<{
717
717
  syndicate: "syndicate";
718
718
  other: "other";
719
719
  }>>;
720
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
720
721
  name: z.ZodString;
721
722
  slug: z.ZodString;
722
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
723
723
  address: z.ZodOptional<z.ZodNullable<z.ZodType<{
724
724
  street?: string | undefined;
725
725
  postalCode?: string | undefined;
@@ -750,9 +750,9 @@ declare const organizationUpdateDto: z.ZodObject<{
750
750
  syndicate: "syndicate";
751
751
  other: "other";
752
752
  }>>;
753
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
753
754
  name: z.ZodOptional<z.ZodString>;
754
755
  slug: z.ZodOptional<z.ZodString>;
755
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
756
756
  address: z.ZodOptional<z.ZodNullable<z.ZodType<{
757
757
  street?: string | undefined;
758
758
  postalCode?: string | undefined;
@@ -1945,7 +1945,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1945
1945
  data: {
1946
1946
  name: string;
1947
1947
  label: string;
1948
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1948
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1949
1949
  required: boolean;
1950
1950
  hidden: boolean;
1951
1951
  options?: string[] | undefined;
@@ -1965,7 +1965,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1965
1965
  $type: {
1966
1966
  name: string;
1967
1967
  label: string;
1968
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1968
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1969
1969
  required: boolean;
1970
1970
  hidden: boolean;
1971
1971
  options?: string[] | undefined;
@@ -5,8 +5,8 @@ import { FIELD_TYPES, FieldType, PUBLICATION_STATUSES } from '../domains/collect
5
5
  import { FieldDefinition, fieldDefinitionSchema } from '../domains/collections/utils.js';
6
6
 
7
7
  declare const definitionCreateDto: z.ZodObject<{
8
- name: z.ZodString;
9
8
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
9
+ name: z.ZodString;
10
10
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
11
11
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
12
12
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -16,13 +16,13 @@ declare const definitionCreateDto: z.ZodObject<{
16
16
  type: z.ZodEnum<{
17
17
  number: "number";
18
18
  boolean: "boolean";
19
- json: "json";
20
19
  date: "date";
20
+ media: "media";
21
+ json: "json";
21
22
  text: "text";
23
+ select: "select";
22
24
  "rich-text": "rich-text";
23
- media: "media";
24
25
  relation: "relation";
25
- select: "select";
26
26
  steps: "steps";
27
27
  }>;
28
28
  required: z.ZodDefault<z.ZodBoolean>;
@@ -36,9 +36,9 @@ declare const definitionCreateDto: z.ZodObject<{
36
36
  in: {};
37
37
  }>;
38
38
  declare const definitionUpdateDto: z.ZodObject<{
39
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
39
40
  name: z.ZodOptional<z.ZodString>;
40
41
  slug: z.ZodOptional<z.ZodString>;
41
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
42
42
  editor: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
43
43
  display: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
44
44
  headings: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
@@ -48,13 +48,13 @@ declare const definitionUpdateDto: z.ZodObject<{
48
48
  type: z.ZodEnum<{
49
49
  number: "number";
50
50
  boolean: "boolean";
51
- json: "json";
52
51
  date: "date";
52
+ media: "media";
53
+ json: "json";
53
54
  text: "text";
55
+ select: "select";
54
56
  "rich-text": "rich-text";
55
- media: "media";
56
57
  relation: "relation";
57
- select: "select";
58
58
  steps: "steps";
59
59
  }>;
60
60
  required: z.ZodDefault<z.ZodBoolean>;
@@ -151,7 +151,7 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
151
151
  data: {
152
152
  name: string;
153
153
  label: string;
154
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
154
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
155
155
  required: boolean;
156
156
  hidden: boolean;
157
157
  options?: string[] | undefined;
@@ -171,7 +171,7 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
171
171
  $type: {
172
172
  name: string;
173
173
  label: string;
174
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
174
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
175
175
  required: boolean;
176
176
  hidden: boolean;
177
177
  options?: string[] | undefined;
@@ -337,13 +337,13 @@ declare const definitionDto: drizzle_zod.BuildSchema<"select", {
337
337
  type: z.ZodUnion<[z.ZodEnum<{
338
338
  number: "number";
339
339
  boolean: "boolean";
340
- json: "json";
341
340
  date: "date";
341
+ media: "media";
342
+ json: "json";
342
343
  text: "text";
344
+ select: "select";
343
345
  "rich-text": "rich-text";
344
- media: "media";
345
346
  relation: "relation";
346
- select: "select";
347
347
  steps: "steps";
348
348
  }>, z.ZodString]>;
349
349
  required: z.ZodDefault<z.ZodBoolean>;
@@ -717,9 +717,9 @@ declare const organizationInitDto: z.ZodObject<{
717
717
  syndicate: "syndicate";
718
718
  other: "other";
719
719
  }>>;
720
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
720
721
  name: z.ZodString;
721
722
  slug: z.ZodString;
722
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
723
723
  address: z.ZodOptional<z.ZodNullable<z.ZodType<{
724
724
  street?: string | undefined;
725
725
  postalCode?: string | undefined;
@@ -750,9 +750,9 @@ declare const organizationUpdateDto: z.ZodObject<{
750
750
  syndicate: "syndicate";
751
751
  other: "other";
752
752
  }>>;
753
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
753
754
  name: z.ZodOptional<z.ZodString>;
754
755
  slug: z.ZodOptional<z.ZodString>;
755
- description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
756
756
  address: z.ZodOptional<z.ZodNullable<z.ZodType<{
757
757
  street?: string | undefined;
758
758
  postalCode?: string | undefined;
@@ -1945,7 +1945,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1945
1945
  data: {
1946
1946
  name: string;
1947
1947
  label: string;
1948
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1948
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1949
1949
  required: boolean;
1950
1950
  hidden: boolean;
1951
1951
  options?: string[] | undefined;
@@ -1965,7 +1965,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1965
1965
  $type: {
1966
1966
  name: string;
1967
1967
  label: string;
1968
- type: "number" | "boolean" | "json" | "date" | "text" | "rich-text" | "media" | "relation" | "select" | "steps";
1968
+ type: "number" | "boolean" | "date" | "media" | "json" | "text" | "select" | "rich-text" | "relation" | "steps";
1969
1969
  required: boolean;
1970
1970
  hidden: boolean;
1971
1971
  options?: string[] | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-commune/core",
3
- "version": "0.2.18",
3
+ "version": "0.2.19",
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",