@collective-intelligence/external-apps-server-sdk-payload 0.0.0-stage → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/AGENTS.md +49 -0
  2. package/README.md +121 -2
  3. package/dist/ci-generate/declarations/ci-generate/generate.d.ts +10 -0
  4. package/dist/ci-generate/declarations/entrypoints/ci-generate.d.ts +6 -0
  5. package/dist/ci-generate/declarations/knowledge/body.d.ts +32 -0
  6. package/dist/ci-generate/declarations/knowledge/files.d.ts +42 -0
  7. package/dist/ci-generate/declarations/knowledge/manifest.d.ts +19 -0
  8. package/dist/ci-generate/declarations/package/builder.d.ts +63 -0
  9. package/dist/ci-generate/declarations/package/contract.d.ts +16 -0
  10. package/dist/ci-generate/declarations/package/stamped-fields.d.ts +7 -0
  11. package/dist/ci-generate/declarations/plugin/editor-field.d.ts +20 -0
  12. package/dist/ci-generate/declarations/plugin/integration-user.d.ts +11 -0
  13. package/dist/ci-generate/declarations/plugin/parts.d.ts +81 -0
  14. package/dist/ci-generate.d.ts +1 -0
  15. package/dist/ci-generate.js +2 -0
  16. package/dist/index/declarations/ci-generate/generate.d.ts +10 -0
  17. package/dist/index/declarations/entrypoints/index.d.ts +6 -0
  18. package/dist/index/declarations/knowledge/body.d.ts +32 -0
  19. package/dist/index/declarations/knowledge/files.d.ts +42 -0
  20. package/dist/index/declarations/knowledge/identity.d.ts +27 -0
  21. package/dist/index/declarations/knowledge/manifest.d.ts +19 -0
  22. package/dist/index/declarations/knowledge/push-job.d.ts +8 -0
  23. package/dist/index/declarations/knowledge/source.d.ts +24 -0
  24. package/dist/index/declarations/operations/conflict.d.ts +22 -0
  25. package/dist/index/declarations/operations/markdown.d.ts +25 -0
  26. package/dist/index/declarations/operations/operations.d.ts +30 -0
  27. package/dist/index/declarations/operations/write-back.d.ts +8 -0
  28. package/dist/index/declarations/package/builder.d.ts +63 -0
  29. package/dist/index/declarations/package/contract.d.ts +16 -0
  30. package/dist/index/declarations/package/stamped-fields.d.ts +7 -0
  31. package/dist/index/declarations/plugin/editor-field.d.ts +20 -0
  32. package/dist/index/declarations/plugin/grant-store.d.ts +21 -0
  33. package/dist/index/declarations/plugin/integration-user.d.ts +11 -0
  34. package/dist/index/declarations/plugin/parts.d.ts +81 -0
  35. package/dist/index/declarations/plugin/plugin.d.ts +10 -0
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.js +7 -0
  38. package/dist/package.d.ts +134 -0
  39. package/dist/package.js +24 -0
  40. package/docs/guide/ai/index.md +379 -0
  41. package/docs/guide/ai/studio.md +245 -0
  42. package/docs/guide/data/connectors.md +267 -0
  43. package/docs/guide/data/datasets.md +145 -0
  44. package/docs/guide/data/documents.md +235 -0
  45. package/docs/guide/data/index.md +62 -0
  46. package/docs/guide/data/knowledge.md +214 -0
  47. package/docs/guide/develop/extensions.md +299 -0
  48. package/docs/guide/develop/external-apps.md +289 -0
  49. package/docs/guide/develop/infrastructure.md +135 -0
  50. package/docs/guide/develop/sdks.md +252 -0
  51. package/docs/guide/index.md +83 -0
  52. package/docs/guide/platform/access.md +311 -0
  53. package/docs/guide/platform/architecture.md +166 -0
  54. package/docs/guide/platform/built-ins.md +225 -0
  55. package/docs/guide/platform/entrypoints.md +320 -0
  56. package/docs/guide/scenarios/index.md +130 -0
  57. package/docs/guide/template/index.md +295 -0
  58. package/docs/guide/template/state-machines.md +294 -0
  59. package/docs/payload-connector.md +890 -0
  60. package/docs/payload-page-editor-skill.md +284 -0
  61. package/package.json +79 -4
@@ -0,0 +1,27 @@
1
+ /** The Publication State of an item (Q16, Q65). */
2
+ export type PublicationState = "draft" | "published";
3
+ /**
4
+ * One item of a Payload Document: the document id, the language only for a
5
+ * collection with localized fields, and the Publication State (Q54, Q68).
6
+ */
7
+ export type ItemIdentity = Readonly<{
8
+ id: number | string;
9
+ language?: string | undefined;
10
+ state: PublicationState;
11
+ }>;
12
+ declare const itemIdentityText: unique symbol;
13
+ /**
14
+ * An encoded Item Identity. It is the remote id of a record and the value of
15
+ * each relation field that names the item, so both always match (Q15).
16
+ */
17
+ export type ItemIdentityText = string & Readonly<{
18
+ [itemIdentityText]: true;
19
+ }>;
20
+ export declare const encodeItemIdentity: ({ id, language, state }: ItemIdentity) => ItemIdentityText;
21
+ /**
22
+ * Decodes the text of an Item Identity, or gives `undefined` when the text is
23
+ * not the encoding of one. Only the exact encoding decodes, so a decoded
24
+ * identity encodes to the same text.
25
+ */
26
+ export declare const decodeItemIdentity: (text: string) => ItemIdentity | undefined;
27
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { GatewayKnowledgeRelation, GatewayPublicationState } from "@collective-intelligence/external-apps-server-sdk/gateway/contracts";
2
+ import type { ResourceDefinition, ResourceJsonValue } from "@collective-intelligence/external-apps-server-sdk/resources";
3
+ import type { SanitizedConfig } from "payload";
4
+ type JsonObject = Readonly<Record<string, ResourceJsonValue>>;
5
+ /** The manifest part of one exposed Payload Collection (ARC-003). */
6
+ export type PayloadKnowledgeResource = Readonly<{
7
+ definition: ResourceDefinition<JsonObject>;
8
+ /** Only for a collection with drafts (Q65). */
9
+ publicationState?: GatewayPublicationState;
10
+ relations: readonly GatewayKnowledgeRelation[];
11
+ }>;
12
+ /**
13
+ * Turns the exposed Payload Collections of a site into the Knowledge
14
+ * resources of its Gateway manifest, from `configToJSONSchema` and each
15
+ * collection's flattened fields (Q53). A Payload global is never a resource
16
+ * (INV-001).
17
+ */
18
+ export declare const payloadKnowledgeResources: (config: SanitizedConfig, slugs: readonly string[]) => readonly PayloadKnowledgeResource[];
19
+ export {};
@@ -0,0 +1,8 @@
1
+ import type { PayloadPluginPart } from "../plugin/parts.js";
2
+ /**
3
+ * The Push Job: a publish, unpublish, manual draft save, move to trash or
4
+ * delete of an exposed document queues one `ciGatewayPush` job on the
5
+ * `ci-gateway` queue in the change's transaction; an autosave queues none
6
+ * (Q9, Q19, Q46, Q86).
7
+ */
8
+ export declare const pushJobPart: PayloadPluginPart;
@@ -0,0 +1,24 @@
1
+ import type { ResourceRecord } from "@collective-intelligence/external-apps-server-sdk/resources";
2
+ import type { Payload, Where } from "payload";
3
+ import type { PayloadDocument, PayloadPluginPart, PayloadPluginSettings } from "../plugin/parts.js";
4
+ import type { ItemIdentityText } from "./identity.js";
5
+ /** One item of a Payload Document as a Knowledge record. */
6
+ export type PayloadRecord = ResourceRecord<PayloadDocument> & Readonly<{
7
+ id: ItemIdentityText;
8
+ }>;
9
+ /** Reads the items of a collection's documents that match `where`. */
10
+ export type PayloadRecordReader = (collection: string, where?: Where) => Promise<readonly PayloadRecord[]>;
11
+ /**
12
+ * Reads the items of the exposed collections as the Integration User, with
13
+ * the site's access rules on (Q45): one item for each locale with a
14
+ * translation (Q12, Q23), or one without a language for a collection without
15
+ * localized fields (Q68), and for each Publication State that a document has
16
+ * (Q16). Each record holds the fields of the collection's Knowledge resource
17
+ * in manifest order.
18
+ */
19
+ export declare const payloadRecords: ({ payload, settings }: Readonly<{
20
+ payload: Payload;
21
+ settings: PayloadPluginSettings;
22
+ }>) => PayloadRecordReader;
23
+ /** The record source: items per language and Publication State (ARC-004). */
24
+ export declare const sourcePart: PayloadPluginPart;
@@ -0,0 +1,22 @@
1
+ import type { TypeWithTimestamps } from "payload";
2
+ import type { PayloadPluginPart } from "../plugin/parts.js";
3
+ /** The document of a plugin update and the revision that the Agent read of it. */
4
+ type ReadRevision = Readonly<{
5
+ collection: string;
6
+ id: TypeWithTimestamps["id"];
7
+ revision: string;
8
+ }>;
9
+ /**
10
+ * The request context of a plugin update, which holds the revision that the
11
+ * Agent read for the edit conflict check (FLOW-005-STEP-005).
12
+ */
13
+ export declare const readRevisionContext: (read: ReadRevision) => {
14
+ [x: string]: string;
15
+ };
16
+ /**
17
+ * The edit conflict check inside Payload's update of a writable collection:
18
+ * an update fails with a conflict when the stored revision is not the
19
+ * revision the Agent read (ARC-006, FLOW-005-STEP-005, Q27, Q106).
20
+ */
21
+ export declare const conflictPart: PayloadPluginPart;
22
+ export {};
@@ -0,0 +1,25 @@
1
+ import type { ResourceJsonValue } from "@collective-intelligence/external-apps-server-sdk/resources";
2
+ import type { FlattenedField, SanitizedConfig } from "payload";
3
+ import type { PayloadDocument } from "../plugin/parts.js";
4
+ /** A field value that a write cannot take: its path from the document root, and why. */
5
+ export type FieldError = Readonly<{
6
+ message: string;
7
+ path: string;
8
+ }>;
9
+ /**
10
+ * The write data of a document with each rich-text value that is Markdown
11
+ * text converted with the field's own Lexical editor config, at any depth of
12
+ * groups, tabs, arrays and blocks (Q26). Other values stay JSON. A Markdown
13
+ * value of a field with another editor is a field error.
14
+ */
15
+ export declare const markdownToRichText: ({ config, data, fields }: Readonly<{
16
+ config: SanitizedConfig;
17
+ data: PayloadDocument;
18
+ fields: readonly FlattenedField[];
19
+ }>) => {
20
+ data: Readonly<Record<string, ResourceJsonValue>>;
21
+ errors: Readonly<{
22
+ message: string;
23
+ path: string;
24
+ }>[];
25
+ };
@@ -0,0 +1,30 @@
1
+ import type { Payload, SanitizedCollectionConfig } from "payload";
2
+ import type { PayloadDocument, PayloadPluginPart } from "../plugin/parts.js";
3
+ /** The hidden field that keeps the idempotency key of a `create` (Q118). */
4
+ export declare const createKeyField = "ciCreateKey";
5
+ /**
6
+ * The fields of a collection that only Payload and the plugin write: the
7
+ * document id, Payload's stamp fields with the Publication State, each hidden
8
+ * field such as `ciCreateKey`, and the CI Editor field. A CI write refuses a
9
+ * value for one, so that only publish, unpublish and delete change the
10
+ * Publication State or the trash. A create in a collection with a custom ID
11
+ * field sends the id, because the site makes it; an update never changes the
12
+ * id, because the id names the document.
13
+ */
14
+ export type Write = "create" | "update";
15
+ export declare const controlFields: (collection: SanitizedCollectionConfig, write: Write) => ReadonlySet<string>;
16
+ export declare const documentOf: (value: unknown) => PayloadDocument;
17
+ /**
18
+ * Runs the create of a create key once (Q118): a retry gives the document
19
+ * that the first call made. The key is unique, so a retry that runs while the
20
+ * first create still runs fails its insert once the first commits, and then
21
+ * gives that document too. The key lookup is the plugin's own check on its
22
+ * hidden field, which Payload queries only without access rules; the create
23
+ * keeps them.
24
+ */
25
+ export declare const createOnce: <A>(payload: Payload, collection: string, key: string, create: () => Promise<A>) => Promise<(import("payload").JsonObject & import("payload").TypeWithID) | A>;
26
+ /**
27
+ * The six operations of the Payload Operation Contract, served as the
28
+ * Integration User with the site's access rules on (ARC-006, Q45).
29
+ */
30
+ export declare const operationsPart: PayloadPluginPart;
@@ -0,0 +1,8 @@
1
+ import type { PayloadPluginPart } from "../plugin/parts.js";
2
+ /**
3
+ * The Knowledge write-back of each writable collection: CI's Remote-first
4
+ * write of a Knowledge edit, create, delete or restore reaches Payload
5
+ * through the Gateway's Knowledge record routes, as the Integration User with
6
+ * the site's access rules on (ARC-013, FLOW-006, Q30, Q45).
7
+ */
8
+ export declare const writeBackPart: PayloadPluginPart;
@@ -0,0 +1,63 @@
1
+ import type { ComponentManifest, ComponentPresentation, DeclarationHandle, DeclaredComponent, JsonObject, KnowledgeConnectorInstanceDeclaration, KnowledgeConnectorInstanceEntityBinding, KnowledgeConnectorInstanceSchedule, KnowledgeEntitySchemaDeclaration, PackageDependency } from "@collective-intelligence/extensions-sdk";
2
+ /**
3
+ * The Payload Declarations File that `payload ci-generate` writes from the
4
+ * site's Payload configuration, as JSON. A JSON import types each string as
5
+ * `string`, so the builder checks the field types and cardinalities.
6
+ */
7
+ export type PayloadDeclarationsFile = Readonly<{
8
+ collections: Readonly<Record<string, Readonly<{
9
+ /** The schema fields; each reads the `remote` field: the field map. */
10
+ fields: Readonly<Record<string, Readonly<{
11
+ options?: readonly string[];
12
+ remote: string;
13
+ /** `boolean`, `number`, `string` or `string_select`. */
14
+ type: string;
15
+ }>>>;
16
+ label: string;
17
+ /** Each relation field and the collection whose items it names. */
18
+ relations: readonly Readonly<{
19
+ /** `one` or `many`. */
20
+ cardinality: string;
21
+ field: string;
22
+ target: string;
23
+ }>[];
24
+ /** The entity schema of the collection in the Gateway manifest (AC-121). */
25
+ schema: JsonObject;
26
+ }>>>;
27
+ }>;
28
+ export type PayloadKnowledgeInput<File extends PayloadDeclarationsFile, Collection extends Extract<keyof File["collections"], string> = Extract<keyof File["collections"], string>> = Readonly<{
29
+ /**
30
+ * The chosen collections, each with the package's binding choices (Q105).
31
+ * Leave a collection out to not choose it: each key gets a schema.
32
+ */
33
+ collections: Readonly<Record<Collection, Readonly<Pick<KnowledgeConnectorInstanceEntityBinding, "draftImport" | "importExclusionRules">>>>;
34
+ domainFqn: string;
35
+ gateway: DeclarationHandle<"externalAppGateway">;
36
+ /** The connector instance; each schema FQN is `<fqn>.<collection>`. */
37
+ manifest: ComponentManifest;
38
+ presentation: ComponentPresentation;
39
+ /** Each schedule runs a full import of every chosen collection (Q18). */
40
+ schedules?: readonly Readonly<Pick<KnowledgeConnectorInstanceSchedule, "cronExpression" | "key">>[];
41
+ }>;
42
+ /**
43
+ * The declared Knowledge of the chosen collections: the schema of each, by
44
+ * collection name, and the connector instance; `components` lists them all.
45
+ */
46
+ export type PayloadKnowledge<Collection extends string = string> = Readonly<{
47
+ components: readonly DeclaredComponent<KnowledgeConnectorInstanceDeclaration | KnowledgeEntitySchemaDeclaration>[];
48
+ connectorInstance: DeclaredComponent<KnowledgeConnectorInstanceDeclaration>;
49
+ schemas: Readonly<Record<Collection, DeclaredComponent<KnowledgeEntitySchemaDeclaration>>>;
50
+ }>;
51
+ /**
52
+ * The package dependencies of a Payload Site's extension package: the
53
+ * connector instance runs on the Knowledge Gateway template of the External
54
+ * Apps package (Q17).
55
+ */
56
+ export declare const payloadPackageDependencies: readonly PackageDependency[];
57
+ /**
58
+ * Declares the Knowledge of the chosen collections from the Payload
59
+ * Declarations File (Q99, Q105, Q17): a relation to a chosen collection fills
60
+ * a relation field through a `reference` rule; a relation to any other
61
+ * collection keeps its `<field>_title` text (Q117).
62
+ */
63
+ export declare const payloadKnowledge: <const File extends PayloadDeclarationsFile, Collection extends Extract<keyof File["collections"], string>>(file: File, input: PayloadKnowledgeInput<File, Collection>) => PayloadKnowledge<Collection>;
@@ -0,0 +1,16 @@
1
+ import type { OperationDomainDeclaration, PortableOperationDeclaration, PortableOperationGatewayContract } from "@collective-intelligence/extensions-sdk";
2
+ /** The six operations that every Payload Site serves (Q59, Q93). */
3
+ export type PayloadOperationId = "create" | "delete" | "publish" | "read" | "unpublish" | "update";
4
+ /** The Payload Operation Contract; its type keeps each operation id. */
5
+ export type PayloadOperationContract = Omit<PortableOperationGatewayContract, "operationDomains"> & Readonly<{
6
+ operationDomains: readonly OperationDomainDeclaration<PortableOperationDeclaration & Readonly<{
7
+ canonicalReference: string;
8
+ id: PayloadOperationId;
9
+ }>>[];
10
+ }>;
11
+ /**
12
+ * The fixed operation contract of every Payload Site: six operations, each
13
+ * with a plain-text `collection` input. Only an SDK upgrade changes it. An
14
+ * extension package passes it to one `declareExternalAppGateway` call.
15
+ */
16
+ export declare const payloadOperationContract: PayloadOperationContract;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The fields that Payload stamps; `_status` holds the Publication State. A
3
+ * Knowledge write never writes them (Q40): the site refuses them, and a
4
+ * package binding imports them only. This module imports nothing, so the
5
+ * Payload package entry stays free of Payload.
6
+ */
7
+ export declare const stampedFields: ReadonlySet<string>;
@@ -0,0 +1,20 @@
1
+ import type { GatewayWriteActor } from "@collective-intelligence/external-apps-server-sdk/auth";
2
+ import type { RequestContext } from "payload";
3
+ import type { PayloadPluginPart } from "./parts.js";
4
+ /**
5
+ * The CI Editor field on each writable collection (Q79). It is stored on the
6
+ * Payload Document only: the Knowledge manifest leaves it out.
7
+ */
8
+ export declare const editorField = "ciEditor";
9
+ /**
10
+ * The request context of a CI write: the CI user's name and email from the
11
+ * Write Actor. A CI write without a Write Actor has none.
12
+ */
13
+ export declare const editorContext: (actor: GatewayWriteActor | undefined) => RequestContext;
14
+ /**
15
+ * Adds the CI Editor field to each writable collection: hidden in the edit
16
+ * view and read-only, but stored with each version, so version history shows
17
+ * the CI user of each CI write to the site's admin users (ARC-006, Q45). An
18
+ * API-hidden field would not show there.
19
+ */
20
+ export declare const editorFieldPart: PayloadPluginPart;
@@ -0,0 +1,21 @@
1
+ import type { ConfidentialCredentials } from "@collective-intelligence/external-apps-server-sdk";
2
+ import type { GatewayConnectionGrant, GatewayPackageEnrollmentGrant } from "@collective-intelligence/external-apps-server-sdk/auth";
3
+ import type { Payload } from "payload";
4
+ import type { PayloadCiTrust, PayloadPluginPart } from "./parts.js";
5
+ /** The package grants of the site, each with the client secret that CI gave it at enrollment. */
6
+ export declare const readConnectionGrants: (payload: Payload) => Promise<readonly GatewayPackageEnrollmentGrant[]>;
7
+ /**
8
+ * The Gateway Connections that the Push Job pushes to, each with the client
9
+ * credentials that it signs in with: a package grant with the client secret
10
+ * that CI gave it at enrollment, and on the Dashboard path a grant of
11
+ * setup-credential enrollment with the client secret of the administrator's
12
+ * confidential External App (Q109, Q113, AC-200).
13
+ */
14
+ export declare const readPushConnections: (payload: Payload, ci: PayloadCiTrust | undefined) => Promise<readonly (GatewayConnectionGrant & ConfidentialCredentials)[]>;
15
+ /**
16
+ * The connection grant store. With the CI trust option, the site enrolls its
17
+ * package Gateway Connection and stores the client secret with its grant, or
18
+ * enrolls the Gateway Connection of its Dashboard registration with the setup
19
+ * credential; it checks every CI caller against the grants (Q31, Q109, Q113).
20
+ */
21
+ export declare const grantStorePart: PayloadPluginPart;
@@ -0,0 +1,11 @@
1
+ import type { Payload } from "payload";
2
+ import type { PayloadPluginSettings } from "./parts.js";
3
+ /**
4
+ * The Integration User, as the `user` of a Local API call or a request:
5
+ * each part reads and writes as this user, with the site's access rules on
6
+ * (Q45).
7
+ */
8
+ export declare const readIntegrationUser: (payload: Payload, settings: PayloadPluginSettings) => Promise<{
9
+ collection: string;
10
+ id: number | string;
11
+ }>;
@@ -0,0 +1,81 @@
1
+ import type { ConfidentialCredentials } from "@collective-intelligence/external-apps-server-sdk";
2
+ import type { GatewayPackageEnrollmentConfig } from "@collective-intelligence/external-apps-server-sdk/auth";
3
+ import type { GatewayKernelConfig } from "@collective-intelligence/external-apps-server-sdk/gateway";
4
+ import type { GatewayKnowledgeResourceExposure, GatewayOperationHandler } from "@collective-intelligence/external-apps-server-sdk/gateway/contracts";
5
+ import type { ResourceJsonValue } from "@collective-intelligence/external-apps-server-sdk/resources";
6
+ import type { Config, Payload, PayloadTypes } from "payload";
7
+ import type { PayloadOperationId } from "../package/contract.js";
8
+ /** The Gateway path under the site's Payload API route (Q44). */
9
+ export declare const gatewayMountPath = "/ci-gateway";
10
+ /** A Payload Document as the Payload Plugin reads it. */
11
+ export type PayloadDocument = Readonly<Record<string, ResourceJsonValue>>;
12
+ /**
13
+ * CI trust: the Gateway URL that CI signs caller tokens for, the CI tenants
14
+ * that the site trusts, and how CI connects the site. A package Gateway names
15
+ * the packages that may enroll it. A Gateway that an administrator registers
16
+ * in the Dashboard has the setup credentials of its registration and the
17
+ * client credentials of the administrator's confidential External App, which
18
+ * its Push Job signs in with (Q31, AC-200). Without CI trust, the Gateway
19
+ * refuses every CI call.
20
+ */
21
+ export type PayloadCiTrust = Omit<GatewayPackageEnrollmentConfig, "allowedPackages" | "store"> & Readonly<{
22
+ allowedPackages?: GatewayPackageEnrollmentConfig["allowedPackages"];
23
+ dashboard?: Readonly<{
24
+ app: ConfidentialCredentials;
25
+ setupCredentials: readonly string[];
26
+ }>;
27
+ }>;
28
+ /** The settings of one exposed Payload Collection. */
29
+ export type PayloadCollectionOptions = Readonly<{
30
+ /** Field paths that the Document Body skips (Q21). */
31
+ bodyExclude?: readonly string[];
32
+ /** The URL Rule: the Public URL of a document (Q22). */
33
+ urlRule: (document: PayloadDocument) => string;
34
+ /** The page-write operations can write the collection (Q59). */
35
+ writable?: boolean;
36
+ }>;
37
+ /**
38
+ * The `ciPayloadPlugin` options. With the site's generated Payload types, the
39
+ * exposed collections accept only Payload Collection slugs, never a global
40
+ * (INV-001).
41
+ */
42
+ export type CiPayloadPluginOptions<Types extends Pick<PayloadTypes, "collections"> = PayloadTypes> = Readonly<{
43
+ ci?: PayloadCiTrust;
44
+ collections: Readonly<Partial<Record<Extract<keyof Types["collections"], string>, PayloadCollectionOptions>>>;
45
+ /** The Integration User: the plugin reads and writes as this user, with the site's access rules on (Q45). */
46
+ integrationUser: Readonly<{
47
+ collection: Extract<keyof Types["collections"], string>;
48
+ id: number | string;
49
+ }>;
50
+ }>;
51
+ /** The plugin options as each part reads them. */
52
+ export type PayloadPluginSettings = Readonly<{
53
+ ci?: PayloadCiTrust;
54
+ collections: Readonly<Partial<Record<string, PayloadCollectionOptions>>>;
55
+ integrationUser: Readonly<{
56
+ collection: string;
57
+ id: number | string;
58
+ }>;
59
+ }>;
60
+ /** What one part serves through the Gateway of a running site. */
61
+ export type PayloadServing = Readonly<{
62
+ /** Checks CI callers and enrolls Gateway Connections. */
63
+ connection?: Partial<Pick<GatewayKernelConfig, "enrollConnection" | "enrollPackageConnection" | "verifyCaller" | "verifySetupCredential">>;
64
+ /** Adds the part's record handlers and capabilities to the Knowledge resource of one exposed collection. */
65
+ knowledge?: (exposure: GatewayKnowledgeResourceExposure) => GatewayKnowledgeResourceExposure;
66
+ /** Handlers of the Payload Operation Contract. */
67
+ operations?: Partial<Record<PayloadOperationId, GatewayOperationHandler>>;
68
+ }>;
69
+ /**
70
+ * One part of the Payload Plugin. `plugin.ts` composes the parts, so each
71
+ * concern keeps its own module (Migration Ledger M1 to M7, M9).
72
+ */
73
+ export type PayloadPluginPart = Readonly<{
74
+ /** Adds the part's collections, fields, hooks, jobs or `bin` scripts to the site configuration. */
75
+ config?: (config: Config, settings: PayloadPluginSettings) => Config;
76
+ /** Made once for each Payload instance, at the first Gateway request. */
77
+ serve?: (site: Readonly<{
78
+ payload: Payload;
79
+ settings: PayloadPluginSettings;
80
+ }>) => PayloadServing;
81
+ }>;
@@ -0,0 +1,10 @@
1
+ import type { PayloadTypes, Plugin } from "payload";
2
+ import type { CiPayloadPluginOptions, PayloadPluginPart } from "./parts.js";
3
+ /** Composes a Payload Plugin from its parts. */
4
+ export declare const payloadPlugin: (parts: readonly PayloadPluginPart[]) => <Types extends Pick<PayloadTypes, "collections"> = PayloadTypes>(options: CiPayloadPluginOptions<Types>) => Plugin;
5
+ /**
6
+ * The Payload Plugin: one entry in `payload.config` serves the exposed
7
+ * Payload Collections through a Gateway under the site's Payload API route,
8
+ * such as `/api/ci-gateway` (Q2, Q44).
9
+ */
10
+ export declare const ciPayloadPlugin: <Types extends Pick<PayloadTypes, "collections"> = import("payload").UntypedPayloadTypes>(options: CiPayloadPluginOptions<Types>) => Plugin;
@@ -0,0 +1 @@
1
+ export * from "./index/declarations/entrypoints/index.js"
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import{GatewayCallerAuthError as GatewayCallerAuthError2}from"@collective-intelligence/external-apps-server-sdk/auth";import{createGatewayKernel,defineGateway,GatewayOperationError as GatewayOperationError4}from"@collective-intelligence/external-apps-server-sdk/gateway";import{formatAdminURL}from"payload/shared";import{fileURLToPath}from"node:url";var objectOf=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value)?Object.fromEntries(Object.entries(value)):undefined;var rowsOf=(value)=>Array.isArray(value)?value.flatMap((row)=>{const data=objectOf(row);return data===undefined?[]:[data]}):[];var blockOf=(config,field,row)=>[...field.blocks,...field.blockReferences??[]].map((reference)=>typeof reference==="string"?config.blocks?.find(({slug})=>slug===reference):reference).find((candidate)=>candidate?.slug===row.blockType);var subfields=(config,field,value)=>{if(field.type==="blocks"){return rowsOf(value).flatMap((data)=>{const block=blockOf(config,field,data);return block===undefined?[]:[{data,fields:block.flattenedFields,path:`${field.name}.${block.slug}`}]})}if(!("flattenedFields"in field)){return[]}return rowsOf(field.type==="array"?value:[value??null]).map((row)=>({data:row,fields:field.flattenedFields,path:field.name}))};var texts=(value)=>[value].flat().filter((text)=>typeof text==="string"&&text!=="");var inline=(node)=>{if(typeof node.text==="string"){return node.text}return node.type==="linebreak"?`
2
+ `:rowsOf(node.children).map(inline).join("")};var listLines=(list,indent)=>{const lines=[];let items=0;let marker="";for(const item of rowsOf(list.children)){const children=rowsOf(item.children);const text=children.filter(({type})=>type!=="list").map(inline).join("");const nested=children.filter(({type})=>type==="list");if(text!==""||nested.length===0){items+=1;marker=list.listType==="number"?`${String(items)}.`:"-";lines.push(`${indent}${marker} ${text}`)}const under=`${indent}${" ".repeat(marker.length+1)}`;lines.push(...nested.flatMap((child)=>listLines(child,under)))}return lines};var markdown=(node)=>{switch(node.type){case"heading":{const level=Number(String(node.tag).slice(1));return[`${"#".repeat(level)} ${inline(node)}`]}case"list":{return[listLines(node,"").join(`
3
+ `)]}case"quote":{return[`> ${inline(node)}`]}case"table":{return[rowsOf(node.children).map((row)=>rowsOf(row.children).map((cell)=>rowsOf(cell.children).flatMap(markdown).join(" ")).join(" | ")).join(`
4
+ `)]}default:{return texts(inline(node))}}};var documentBody=({collection,config,document,skip=[]})=>{const skipped=new Set(skip);const paragraphs=(fields,data,prefix)=>fields.flatMap((field)=>{const path=`${prefix}${field.name}`;if(field.admin?.hidden===true||skipped.has(path)){return[]}const value=data[field.name];switch(field.type){case"richText":{const root=objectOf(objectOf(value)?.root);return rowsOf(root?.children).flatMap(markdown)}case"text":case"textarea":{return path===collection.admin.useAsTitle?texts(value).map((title)=>`# ${title}`):texts(value)}default:{return subfields(config,field,value).flatMap((nested)=>paragraphs(nested.fields,nested.data,`${prefix}${nested.path}.`))}}});return paragraphs(collection.flattenedFields,document,"").join(`
5
+
6
+ `)};import{configToJSONSchema}from"payload";import{fieldIsLocalized,hasDraftsEnabled}from"payload/shared";import*as Predicate from"effect/Predicate";var editorField="ciEditor";var contextKey="ciGatewayEditor";var editorContext=(actor)=>actor===undefined?{}:{[contextKey]:`${actor.name} <${actor.email}>`};var ownEditor=({context})=>{const editor=context[contextKey];return Predicate.isString(editor)?editor:null};var adminUsersOnly=({req:{payload,user}})=>user?.collection===payload.config.admin.user;var editorFieldPart={config:(config,settings)=>({...config,collections:(config.collections??[]).map((collection)=>settings.collections[collection.slug]?.writable===true?{...collection,fields:[...collection.fields,{access:{read:adminUsersOnly},admin:{hidden:true,readOnly:true},hooks:{beforeChange:[ownEditor]},label:"CI Editor",name:editorField,type:"text"}]}:collection)})};import{createHash,createHmac,timingSafeEqual}from"node:crypto";var readIntegrationUser=async(payload,settings)=>{const{collection,id}=settings.integrationUser;const user=await payload.findByID({collection,depth:0,disableErrors:true,id});if(user===null){throw new TypeError(`The Integration User ${String(id)} is not in the ${collection} collection`)}return{...user,collection}};var gatewayMountPath="/ci-gateway";var linkLifetimeSeconds=60*60;var filesPath=`${gatewayMountPath}/files`;var signature=(payload,{collection,filename},expires)=>createHmac("sha256",createHmac("sha256",payload.secret).update("ciPayloadPlugin file link").digest()).update(`${collection}\x00${filename}\x00${expires}`).digest();var fileLinker=(payload,gatewayUrl)=>(file)=>{const expires=String(Math.floor(Date.now()/1000)+linkLifetimeSeconds);const url=new URL("files",gatewayUrl.endsWith("/")?gatewayUrl:`${gatewayUrl}/`);url.search=new URLSearchParams({collection:file.collection,expires,filename:file.filename,signature:signature(payload,file,expires).toString("base64url")}).toString();return{url:url.href,url_expires_at:new Date(Number(expires)*1000).toISOString()}};var linkedFile=(payload,link)=>{const collection=link.get("collection");const filename=link.get("filename");const expires=link.get("expires");const given=link.get("signature");if(collection===null||filename===null||expires===null||given===null||!(Number(expires)*1000>Date.now())){return}const file={collection,filename};const expected=signature(payload,file,expires);const actual=Buffer.from(given,"base64url");return actual.length===expected.length&&timingSafeEqual(actual,expected)?file:undefined};var isUploadField=(field)=>field.type==="upload";var fileSourceSchema={additionalProperties:false,description:"A stored file of the site. CI imports it only into a mapped Knowledge File field.",properties:{external_hash:{type:"string"},external_modified_at:{format:"date-time",type:"string"},filename:{type:"string"},source_id:{type:"string"},url:{format:"uri",type:"string"},url_expires_at:{format:"date-time",type:"string"}},required:["external_hash","external_modified_at","filename","source_id","url","url_expires_at"]};var uploadFieldSchema=(field)=>field.hasMany===true?{items:{...fileSourceSchema,type:"object"},type:"array"}:{...fileSourceSchema,type:["object","null"]};var sha256=(text)=>createHash("sha256").update(text).digest("base64url");var fileSource=(field,entry)=>{const polymorphic=Array.isArray(field.relationTo);const reference=polymorphic?objectOf(entry):undefined;const collection=polymorphic?reference?.relationTo:field.relationTo;const doc=objectOf(polymorphic?reference?.value:entry);const{filename,filesize,id,updatedAt}=doc??{};if(typeof collection!=="string"||typeof filename!=="string"||filename===""||typeof updatedAt!=="string"){return}return{file:{collection,filename},source:{external_hash:sha256([collection,String(id),filename,String(filesize),updatedAt].join("\x00")),external_modified_at:updatedAt,filename,source_id:`${collection}:${String(id)}`}}};var documentFiles=(fields,doc,link)=>{const files=fields.map((field)=>({field,sources:[doc[field.name]??[]].flat().flatMap((entry)=>{const found=fileSource(field,entry);if(link===undefined||found===undefined){return[]}return[{linked:{...found.source,...link(found.file)},revision:found.source}]})}));const values=(key)=>Object.fromEntries(files.map(({field,sources})=>{const[first]=sources;if(field.hasMany===true){return[field.name,sources.map((source)=>source[key])]}return[field.name,first===undefined?null:first[key]]}));return{linked:values("linked"),revision:values("revision")}};var refused=()=>Response.json({error:"The file link is not valid or has expired"},{status:403});var payloadFileRoute=(payload,collection)=>{const endpoints=payload.collections[collection]?.config.endpoints;return endpoints===false||endpoints===undefined?undefined:endpoints.find(({method,path})=>method==="get"&&path==="/file/:filename")};var serveFile=(settings)=>async(req)=>{const{payload}=req;const file=linkedFile(payload,req.searchParams);if(file===undefined){return refused()}const route=payloadFileRoute(payload,file.collection);if(route===undefined){return refused()}req.user=await readIntegrationUser(payload,settings);req.routeParams={collection:file.collection,filename:file.filename};const response=await route.handler(req);const headers=new Headers(response.headers);headers.set("cache-control","private, no-store");headers.set("content-disposition",`attachment; filename*=UTF-8''${encodeURIComponent(file.filename)}`);return new Response(response.body,{headers,status:response.status,statusText:response.statusText})};var filePart={config:(config,settings)=>{const endpoint={handler:serveFile(settings),method:"get",path:filesPath};return{...config,endpoints:[endpoint,...config.endpoints??[]]}}};var publicationState={draftValue:"draft",field:"ciPublicationState"};var object=(value)=>{if(value===undefined||value===null||typeof value!=="object"||Array.isArray(value)){throw new TypeError("The Payload JSON schema is not an object")}return Object.fromEntries(Object.entries(value))};var definitionRef=/^#\/definitions\/(?<name>.+)$/u;var referencedDefinitions=(schema,definitions,found=new Map)=>{if(typeof schema!=="object"||schema===null){return found}const name="$ref"in schema?definitionRef.exec(String(schema.$ref))?.groups?.name:undefined;const definition=name===undefined?undefined:definitions[name];if(name!==undefined&&definition!==undefined&&!found.has(name)){found.set(name,definition);referencedDefinitions(definition,definitions,found)}for(const value of Object.values(schema)){referencedDefinitions(value,definitions,found)}return found};var withRelatedIds=(schema,collections)=>{if(Array.isArray(schema)){return schema.map((entry)=>withRelatedIds(entry,collections))}if(typeof schema!=="object"||schema===null){return schema}const{oneOf,...node}=Object.fromEntries(Object.entries(schema).map(([key,value])=>[key,withRelatedIds(value,collections)]));if(!Array.isArray(oneOf)){return oneOf===undefined?node:{...node,oneOf}}const ids=oneOf.filter((alternative)=>{const name=typeof alternative==="object"&&alternative!==null&&"$ref"in alternative?definitionRef.exec(String(alternative.$ref))?.groups?.name:undefined;return name===undefined||!collections.has(name)});if(ids.length===oneOf.length){return{...node,oneOf}}const[id]=ids;return ids.length===1&&id!==undefined?{...node,...object(id)}:{...node,oneOf:ids}};var payloadKnowledgeResources=(config,slugs)=>{const collectionOf=(slug)=>{const collection=config.collections.find((candidate)=>candidate.slug===slug);if(collection===undefined){throw new TypeError(`ciPayloadPlugin names "${slug}", which is not a Payload Collection of the site`)}return collection};const definitions=object(withRelatedIds(object(configToJSONSchema(config,config.db.defaultIDType)).definitions,new Set(config.collections.map(({slug})=>slug))));const locales=config.localization===false?[]:config.localization.localeCodes;const block=(reference)=>typeof reference==="string"?config.blocks?.find(({slug})=>slug===reference):reference;const hasLocalizedField=(fields)=>fields.some((field)=>fieldIsLocalized(field)||("flattenedFields"in field)&&hasLocalizedField(field.flattenedFields)||field.type==="blocks"&&[...field.blocks,...field.blockReferences??[]].some((reference)=>hasLocalizedField(block(reference)?.flattenedFields??[])));const identityFields=(collection)=>["id",...locales.length>0&&hasLocalizedField(collection.flattenedFields)?["ciLanguage"]:[],"ciPublicationState"];return slugs.map(collectionOf).map((collection)=>{const entity=object(definitions[collection.slug]);const payloadProperties=object(entity.properties);const kept=new Set(["id",...collection.flattenedFields.filter((field)=>field.hidden!==true&&field.name!==editorField).map(({name})=>name)]);const properties={};const add=(name,schema)=>{if(name in properties){throw new TypeError(`The field "${name}" of "${collection.slug}" has the name of a field that the Payload Plugin adds`)}properties[name]=schema};const relations=[];for(const[name,schema]of Object.entries(payloadProperties)){const field=collection.flattenedFields.find((candidate)=>candidate.name===name);if(field?.type==="relationship"){const{relationTo}=field;const polymorphic=Array.isArray(relationTo);const cardinality=field.hasMany===true?"many":"one";const nullable=polymorphic||field.required!==true;const text=(description)=>({description,type:nullable?["string","null"]:"string"});const identities=(description)=>cardinality==="many"?{description,items:{type:"string"},type:nullable?["array","null"]:"array"}:text(description);for(const target of Array.isArray(relationTo)?relationTo:[relationTo]){const relationField=polymorphic?`${name}_${target}`:name;add(relationField,identities(`Item Identity of a ${target} item.`));add(`${relationField}_title`,text(`Title of the related ${target} document.`));relations.push({cardinality,field:relationField,targetIdentityFields:identityFields(collectionOf(target)),targetResourceId:target})}}else if(field?.type==="upload"&&kept.has(name)){add(name,uploadFieldSchema(field))}else if(kept.has(name)){add(name,schema)}}const drafts=hasDraftsEnabled(collection);const[,...itemFields]=identityFields(collection);add("ciBody",{description:"Document Body: all visible text of the document as Markdown.",type:"string"});add("ciUrl",{description:"Public URL of the live page of the item.",type:"string"});add("ciPublicationState",{description:"Publication State of the item.",enum:drafts?["draft","published"]:["published"],type:"string"});if(itemFields.includes("ciLanguage")){add("ciLanguage",{description:"Locale of the item.",enum:locales,type:"string"})}const required=[...(Array.isArray(entity.required)?entity.required:[]).filter((name)=>(String(name)in properties)),...itemFields,"ciBody","ciUrl"];const definition={capabilities:{search:true},concurrency:"revision",id:collection.slug,identity:{fields:[{name:"id",type:object(payloadProperties.id).type==="number"?"number":"string"},...itemFields.map((name)=>({name,type:"string"}))]},query:{filterableFields:[],pagination:{modes:["cursor"]},sortableFields:[]},schemas:{entity:{...entity,definitions:Object.fromEntries(referencedDefinitions(properties,definitions)),properties,required}},version:"1"};return drafts?{definition,publicationState,relations}:{definition,relations}})};var customKey="ciPayloadPlugin";var generatePart={config:(config,settings)=>({...config,bin:[...config.bin??[],{key:"ci-generate",get scriptPath(){return fileURLToPath(import.meta.resolve("@collective-intelligence/external-apps-server-sdk-payload/ci-generate"))}}],custom:{...config.custom,[customKey]:Object.keys(settings.collections)}})};import{createGatewayIngestionClient}from"@collective-intelligence/external-apps-server-sdk/gateway";import*as Predicate3 from"effect/Predicate";import{createGatewayConnectionAuthentication,createGatewayPackageEnrollment,GatewayCallerAuthError}from"@collective-intelligence/external-apps-server-sdk/auth";import{createHash as createHash2}from"node:crypto";import{commitTransaction,createLocalReq,initTransaction,killTransaction}from"payload";var grants="ci-gateway-grants";var replays="ci-gateway-replays";var connectionFields=["connectionId","issuer","organizationId"];var grantFields=["audience","clientId","clientSecret","connectionId","gatewayFqn","issuer","manifestHash","organizationId","packageFqn","packageInstallationId"];var internal={access:{create:()=>false,delete:()=>false,read:()=>false,update:()=>false},admin:{hidden:true},lockDocuments:false};var collections=[{...internal,fields:[{name:"key",required:true,type:"text",unique:true},...grantFields.map((name)=>({name,type:"text"}))],slug:grants},{...internal,fields:[{name:"requestId",required:true,type:"text",unique:true},{name:"expiresAt",required:true,type:"number"}],slug:replays}];var sha2562=(text)=>createHash2("sha256").update(text).digest("hex");var grantKey=({connectionId,issuer,organizationId})=>sha2562(`${issuer}\x00${organizationId}\x00${connectionId}`);var findGrant=async(payload,grant,req)=>{const{docs}=await payload.find({collection:grants,limit:1,pagination:false,req,where:{key:{equals:grantKey(grant)}}});return docs[0]};var consume=async(payload,requestId,expiresAt,req)=>{const key=sha2562(requestId);try{await payload.create({collection:replays,data:{expiresAt,requestId:key},req})}catch(error){await killTransaction(req);const{totalDocs}=await payload.count({collection:replays,where:{requestId:{equals:key}}});if(totalDocs>0){return false}throw error}await payload.delete({collection:replays,req,where:{expiresAt:{less_than_equal:Date.now()}}});return true};var removeReplaced=async(payload,grant,same,req)=>{await payload.delete({collection:grants,req,where:{and:[{issuer:{equals:grant.issuer}},{organizationId:{equals:grant.organizationId}},{key:{not_equals:grantKey(grant)}},same]}})};var grantStore=(payload)=>({has:async(grant)=>await findGrant(payload,grant,await createLocalReq({},payload))!==undefined,put:async(grant)=>{const req=await createLocalReq({},payload);if(await findGrant(payload,grant,req)===undefined){await payload.create({collection:grants,data:{...grant,key:grantKey(grant)},req})}await removeReplaced(payload,grant,{packageInstallationId:{exists:false}},req)},remove:async(grant)=>{await payload.delete({collection:grants,where:{key:{equals:grantKey(grant)}}})}});var replayStore=(payload)=>({consume:async(requestId,expiresAt)=>await consume(payload,requestId,expiresAt,await createLocalReq({},payload))});var enrollmentStore=(payload)=>({enroll:async({grant,requestId,expiresAt})=>{const expired=()=>{if(expiresAt<=Date.now()){throw new GatewayCallerAuthError("unauthenticated","Enrollment token expired before commit")}};const req=await createLocalReq({},payload);const owned=await initTransaction(req);try{expired();if(!await consume(payload,requestId,expiresAt,req)){return false}const existing=await findGrant(payload,grant,req);if(existing?.packageInstallationId!==undefined&&existing.packageInstallationId!==null&&(existing.packageInstallationId!==grant.packageInstallationId||existing.packageFqn!==grant.packageFqn||existing.gatewayFqn!==grant.gatewayFqn)){throw new GatewayCallerAuthError("authorization_denied","Connection belongs to another package Gateway")}const data={...grant,key:grantKey(grant)};await(existing===undefined?payload.create({collection:grants,data,req}):payload.update({collection:grants,data,id:existing.id,req}));await removeReplaced(payload,grant,{and:[{packageFqn:{equals:grant.packageFqn}},{gatewayFqn:{equals:grant.gatewayFqn}}]},req);expired();if(owned){await commitTransaction(req)}return true}catch(error){await killTransaction(req);throw error}}});var isPackageGrant=(doc)=>grantFields.every((name)=>typeof doc[name]==="string");var readConnectionGrants=async(payload)=>{const{docs}=await payload.find({collection:grants,pagination:false});return docs.filter(isPackageGrant)};var isSetupGrant=(doc)=>connectionFields.every((name)=>typeof doc[name]==="string");var readPushConnections=async(payload,ci)=>{const packageGrants=await readConnectionGrants(payload);if(ci?.dashboard===undefined){return packageGrants}const{app}=ci.dashboard;const{docs}=await payload.find({collection:grants,pagination:false,where:{packageInstallationId:{exists:false}}});return[...packageGrants,...docs.filter(isSetupGrant).map(({connectionId,issuer,organizationId})=>({...app,connectionId,issuer,organizationId}))]};var grantStorePart={config:(config,{ci})=>{if(ci!==undefined&&(ci.allowedPackages??[]).length===0&&ci.dashboard===undefined){throw new TypeError("ciPayloadPlugin: `ci` needs `allowedPackages` for a package Gateway, or `dashboard` for a Gateway that an administrator registers in the Dashboard")}return{...config,collections:[...config.collections??[],...collections]}},serve:({payload,settings:{ci}})=>{if(ci===undefined){return{}}const{allowedPackages=[],dashboard,...trust}=ci;const{enrollConnection,verifyCaller,verifySetupCredential}=createGatewayConnectionAuthentication({...trust,grants:grantStore(payload),replayStore:replayStore(payload),setupCredentials:()=>Promise.resolve(dashboard?.setupCredentials??[])});const connection=dashboard===undefined?{verifyCaller}:{enrollConnection,verifyCaller,verifySetupCredential};if(allowedPackages.length===0){return{connection}}const{enrollPackageConnection}=createGatewayPackageEnrollment({...trust,allowedPackages,store:enrollmentStore(payload)});return{connection:{...connection,enrollPackageConnection}}}};var encodeItemIdentity=({id,language,state})=>Buffer.from(JSON.stringify(language===undefined?[id,state]:[id,language,state])).toString("base64url");var decodeItemIdentity=(text)=>{let parts;try{parts=JSON.parse(Buffer.from(text,"base64url").toString("utf-8"))}catch{return}if(!Array.isArray(parts)||parts.length!==2&&parts.length!==3){return}const[id,language,state]=parts.length===2?[parts[0],undefined,parts[1]]:parts;if(typeof id!=="number"&&typeof id!=="string"||language!==undefined&&typeof language!=="string"||state!=="draft"&&state!=="published"){return}const identity={id,language,state};return encodeItemIdentity(identity)===text?identity:undefined};import{isResourceJsonValue,resourceFailure,resourceSuccess}from"@collective-intelligence/external-apps-server-sdk/resources";import*as Predicate2 from"effect/Predicate";import{createHash as createHash3}from"node:crypto";import{fieldIsLocalized as fieldIsLocalized2,hasDraftsEnabled as hasDraftsEnabled2}from"payload/shared";var sha2563=(text)=>createHash3("sha256").update(text).digest("base64url");var document=(value)=>{const json=JSON.parse(JSON.stringify(value));const data=isResourceJsonValue(json)?objectOf(json):undefined;if(data===undefined){throw new TypeError("Payload gave a document that is not a JSON object")}return data};var documentId=(value)=>{if(typeof value!=="number"&&typeof value!=="string"){throw new TypeError("Payload gave a document without an id")}return value};var relationsOf=(collection)=>collection.flattenedFields.flatMap((field)=>{if(field.type!=="relationship"){return[]}const polymorphic=Array.isArray(field.relationTo);return[field.relationTo].flat().map((target)=>({field:polymorphic?`${field.name}_${target}`:field.name,many:field.hasMany===true,polymorphic,source:field.name,target}))});var unpopulated=(polymorphic,entry)=>{const reference=objectOf(entry);if(reference===undefined){return entry}return polymorphic?{...reference,value:unpopulated(false,reference.value??null)}:reference.id??entry};var withRelatedIds2=(config,fields,data)=>Object.fromEntries(Object.entries(data).map(([name,value])=>{const field=fields.find((candidate)=>candidate.name===name);switch(field?.type){case"array":case"blocks":{const fieldsOf=(row)=>field.type==="array"?field.flattenedFields:blockOf(config,field,row)?.flattenedFields;return[name,Array.isArray(value)?value.map((entry)=>{const row=objectOf(entry);const rowFields=row===undefined?undefined:fieldsOf(row);return row===undefined||rowFields===undefined?entry:withRelatedIds2(config,rowFields,row)}):value]}case"group":case"tab":{const group=objectOf(value);return[name,group===undefined?value:withRelatedIds2(config,field.flattenedFields,group)]}case"join":{const join=objectOf(value);const polymorphic=Array.isArray(field.collection);return[name,join===undefined||!Array.isArray(join.docs)?value:{...join,docs:join.docs.map((entry)=>unpopulated(polymorphic,entry))}]}case"relationship":case"upload":{const polymorphic=Array.isArray(field.relationTo);return[name,Array.isArray(value)?value.map((entry)=>unpopulated(polymorphic,entry)):unpopulated(polymorphic,value)]}default:{return[name,value]}}}));var referenceOf=(relation,entry)=>{if(!relation.polymorphic){return entry}const polymorphic=objectOf(entry);return polymorphic?.relationTo===relation.target?polymorphic.value:null};var filled=(value)=>value!==undefined&&value!==null&&value!==""&&!(Array.isArray(value)&&value.length===0);var translated=(config,fields,data)=>fields.some((field)=>fieldIsLocalized2(field)?filled(data[field.name]):subfields(config,field,data[field.name]).some((nested)=>translated(config,nested.fields,nested.data)));var payloadRecords=({payload,settings})=>{const{config}=payload;const exposed=Object.keys(settings.collections);const targets=config.collections.filter(({slug})=>exposed.includes(slug)).flatMap((collection)=>relationsOf(collection).map(({target})=>target));const definitions=new Map(payloadKnowledgeResources(config,[...new Set([...exposed,...targets])]).map(({definition})=>[definition.id,definition]));const localized=(slug)=>definitions.get(slug)?.identity.fields.some(({name})=>name==="ciLanguage")===true;const localization=config.localization===false?undefined:config.localization;const relatedItems=(relation,value,{language,state})=>{const titleField=config.collections.find(({slug})=>slug===relation.target)?.admin.useAsTitle;const targetLanguage=localized(relation.target)?language??localization?.defaultLocale:undefined;return[value??[]].flat().flatMap((entry)=>{const reference=referenceOf(relation,entry);if(reference===null||reference===undefined){return[]}const related=objectOf(reference);const id=documentId(related===undefined?reference:related.id);const title=titleField===undefined?undefined:related?.[titleField];const text=Predicate2.isString(title)&&title!==""?title:String(id);return[{identity:encodeItemIdentity({id,language:targetLanguage,state:"published"}),title:state==="published"&&related?._status==="draft"?undefined:text}]})};const link=settings.ci===undefined?undefined:fileLinker(payload,settings.ci.audience);return async(slug,where)=>{const definition=definitions.get(slug);const collection=payload.collections[slug]?.config;const options=settings.collections[slug];if(definition===undefined||collection===undefined||options===undefined){throw new TypeError(`ciPayloadPlugin does not expose "${slug}"`)}const relations=relationsOf(collection);const uploads=collection.flattenedFields.filter(isUploadField);const properties=Object.keys(objectOf(definition.schemas.entity.properties)??{});const drafts=hasDraftsEnabled2(collection);const languages=localized(slug)?localization?.localeCodes??[]:[undefined];const states=drafts?["published","draft"]:["published"];const user=await readIntegrationUser(payload,settings);const record=(doc,variant)=>{const{language,state}=variant;const variantFields=language===undefined?{ciPublicationState:state}:{ciLanguage:language,ciPublicationState:state};const added={...variantFields,...Object.fromEntries(relations.flatMap((relation)=>{const related=relatedItems(relation,doc[relation.source],variant);const identities=related.map(({identity})=>identity);const titles=related.flatMap(({title})=>title===undefined?[]:[title]);return[[relation.field,relation.many?identities:identities[0]??null],[`${relation.field}_title`,titles.length===0?null:titles.join(", ")]]})),ciBody:documentBody({collection,config,document:doc,skip:options.bodyExclude}),ciUrl:options.urlRule({...doc,...variantFields})};const stored=withRelatedIds2(config,collection.flattenedFields,doc);const valueOf=(derived)=>Object.fromEntries(properties.flatMap((name)=>{const field=name in derived?derived[name]:stored[name];return field===undefined?[]:[[name,field]]}));const files=documentFiles(uploads,doc,link);return{id:encodeItemIdentity({id:documentId(doc.id),language,state}),revision:sha2563(JSON.stringify(valueOf({...added,...files.revision}))),value:valueOf({...added,...files.linked})}};const read=async(variant)=>{const query={collection:slug,depth:1,draft:variant.state==="draft",fallbackLocale:false,overrideAccess:false,pagination:false,sort:"id",user};const{docs}=await payload.find(Object.assign(query,variant.language===undefined?{}:{locale:variant.language},where===undefined?{}:{where}));return docs.map(document).filter((doc)=>(!drafts||doc._status===variant.state)&&(variant.language===undefined||translated(config,collection.flattenedFields,doc))).map((doc)=>record(doc,variant))};const variants=languages.flatMap((language)=>states.map((state)=>({language,state})));const records=await Promise.all(variants.map(read));return records.flat()}};var served=(exposure,read)=>{const{resource}=exposure;const{authorization,definition}=resource;return{...exposure,resource:{...resource,authorization:authorization.list===undefined?authorization:{...authorization,get:authorization.list},definition:{...definition,capabilities:{...definition.capabilities,get:true}},execute:async(request,context,options)=>{if(request.operation!=="get"){return await resource.execute(request,context,options)}const identity=decodeItemIdentity(request.id);const records=identity===undefined?[]:await read(request.resourceId,{id:{equals:identity.id}});const record=records.find(({id})=>id===request.id);return record===undefined?resourceFailure(request.requestId,{code:"not_found",message:"The site has no item with this Item Identity",retryable:false}):resourceSuccess(request.requestId,record)},scan:async({page,pageSize,requestId,resourceId,watermark})=>{const records=await read(resourceId);const current=sha2563(records.map(({id,revision})=>`${id} ${revision}`).join(`
7
+ `));if(watermark!==undefined&&watermark!==current){return resourceFailure(requestId,{code:"conflict",message:"The collection changed during the scan; restart it",retryable:false})}return resourceSuccess(requestId,{items:records.slice((page-1)*pageSize,page*pageSize),page,pageSize,pagination:"page",totalItems:records.length,totalPages:Math.ceil(records.length/pageSize),watermark:current})}}}};var sourcePart={serve:(site)=>{const read=payloadRecords(site);return{knowledge:(exposure)=>served(exposure,read)}}};var task="ciGatewayPush";var queue="ci-gateway";var autosaving="ciGatewayAutosaving";var pushTimeoutMs=30000;var identities=(config,{collection,id})=>{const[resource]=payloadKnowledgeResources(config,[collection]);const languages=config.localization!==false&&resource?.definition.identity.fields.some(({name})=>name==="ciLanguage")===true?config.localization.localeCodes:[undefined];const states=resource?.publicationState===undefined?["published"]:["published","draft"];return languages.flatMap((language)=>states.map((state)=>({id,language,state})))};var itemRecord=({id,revision,value})=>{const record={externalId:id,revision,value};return Predicate3.isString(value.updatedAt)?{...record,updatedAt:value.updatedAt}:record};var pushTask=(settings)=>({handler:async({inlineTask,input,req:{payload}})=>{const connections=await readPushConnections(payload,settings.ci);const clients=connections.flatMap((connection)=>{const trusted=settings.ci?.trustedIssuers.find(({issuer})=>issuer===connection.issuer);if(trusted===undefined){return[]}const client={authentication:{credentials:{clientId:connection.clientId,clientSecret:connection.clientSecret},mode:"service"},installationId:connection.connectionId,organizationId:connection.organizationId,tenantUrl:trusted.tenantUrl};const fetch=settings.ci?.fetch;return[{client:createGatewayIngestionClient(fetch===undefined?client:{...client,fetch}),id:`push ${connection.issuer} ${connection.organizationId} ${connection.connectionId}`}]});if(clients.length===0){return{output:{}}}const runAt=new Date().toISOString();const items=await payloadRecords({payload,settings})(input.collection,{id:{equals:input.id}});const current=new Set(items.map(({id})=>id));const records=[...items.map(itemRecord),...identities(payload.config,input).map(encodeItemIdentity).filter((externalId)=>!current.has(externalId)).map((externalId)=>({deletedAt:runAt,externalId,revision:runAt,updatedAt:runAt,value:{}}))];const pushes=await Promise.allSettled(clients.map(({client,id})=>inlineTask(id,{task:async()=>{await client.pushByCollection(input.collection,{batchId:crypto.randomUUID(),records,signal:AbortSignal.timeout(pushTimeoutMs)});return{output:{}}}})));const failed=pushes.filter(({status})=>status==="rejected");if(failed.length>0){throw new Error(`The push failed on ${String(failed.length)} of ${String(clients.length)} Gateway Connections`)}return{output:{}}},retries:{attempts:5,backoff:{delay:60000,type:"exponential"}},slug:task});var queuePush=async(req,input)=>{await req.payload.jobs.queue({input,queue,req,task})};var markAutosave=({args,operation,req})=>{if(operation==="create"||operation==="update"){req.context[autosaving]=args.autosave===true}return args};var changed=async({collection,context,doc,req})=>{if(context[autosaving]!==true){await queuePush(req,{collection:collection.slug,id:doc.id})}return doc};var deleted=async({collection,id,req})=>{await queuePush(req,{collection:collection.slug,id})};var withHooks=({hooks,...collection})=>({...collection,hooks:{...hooks,afterChange:[...hooks?.afterChange??[],changed],afterDelete:[...hooks?.afterDelete??[],deleted],beforeOperation:[...hooks?.beforeOperation??[],markAutosave]}});var pushJobPart={config:(config,settings)=>{const exposed=Object.keys(settings.collections);return{...config,collections:(config.collections??[]).map((collection)=>exposed.includes(collection.slug)?withHooks(collection):collection),jobs:{...config.jobs,tasks:[...config.jobs?.tasks??[],pushTask(settings)]}}}};import{GatewayOperationError}from"@collective-intelligence/external-apps-server-sdk/gateway";var contextKey2=({collection,id})=>`ciReadRevision:${collection}:${String(id)}`;var readRevisionContext=(read)=>({[contextKey2(read)]:read.revision});var checkRevision=({collection,context,data,operation,originalDoc})=>{if(operation!=="update"||originalDoc===undefined){return data}const{id,updatedAt}=originalDoc;const read=context[contextKey2({collection:collection.slug,id})];if(read!==undefined&&read!==updatedAt){throw new GatewayOperationError("conflict",`The document "${String(id)}" changed after the read: read it again`)}return data};var withRevisionCheck=({hooks,...collection})=>({...collection,hooks:{...hooks,beforeChange:[...hooks?.beforeChange??[],checkRevision]}});var conflictPart={config:(config,settings)=>({...config,collections:(config.collections??[]).map((collection)=>settings.collections[collection.slug]?.writable===true?withRevisionCheck(collection):collection)})};import{GatewayOperationError as GatewayOperationError2}from"@collective-intelligence/external-apps-server-sdk/gateway";import{isResourceJsonValue as isResourceJsonValue2}from"@collective-intelligence/external-apps-server-sdk/resources";import*as Predicate4 from"effect/Predicate";import{APIError,Locked,ValidationError}from"payload";import{hasDraftsEnabled as hasDraftsEnabled3}from"payload/shared";var stampedFields=new Set(["_status","createdAt","deletedAt","updatedAt"]);var element=(type,children,extra={})=>({children:[...children],direction:null,format:"",indent:0,type,version:1,...extra});var formatBits={bold:1,inlineCode:16,italic:2,strikethrough:4};var textNode=(text,formats)=>({detail:0,format:[...formats].reduce((sum,format)=>sum+formatBits[format],0),mode:"normal",style:"",text,type:"text",version:1});var inlineRules=[{feature:"inlineCode",pattern:/`(?<inner>[^`]+)`/u},{feature:"link",pattern:/\[(?<inner>[^\]]+)\]\((?<url>[^)\s]+)\)/u},{feature:"bold",pattern:/\*\*(?<inner>.+?)\*\*|(?<!\w)__(?<under>.+?)__(?!\w)/u},{feature:"strikethrough",pattern:/~~(?<inner>.+?)~~/u},{feature:"italic",pattern:/\*(?<inner>[^*]+)\*|(?<!\w)_(?<under>[^_]+)_(?!\w)/u}];var inline2=(text,features,formats=new Set)=>{const[found]=inlineRules.filter(({feature})=>features.has(feature)).flatMap(({feature,pattern})=>{const match=pattern.exec(text);return match===null?[]:[{feature,match}]}).sort((left,right)=>left.match.index-right.match.index);if(found===undefined){return text===""?[]:[textNode(text,formats)]}const{feature,match}=found;const inner=match.groups?.inner??match.groups?.under??"";const marked=()=>{if(feature==="link"){return[element("link",inline2(inner,features,formats),{fields:{linkType:"custom",newTab:false,url:match.groups?.url??""},version:3})]}const nested=new Set([...formats,feature]);return feature==="inlineCode"?[textNode(inner,nested)]:inline2(inner,features,nested)};return[...inline2(text.slice(0,match.index),features,formats),...marked(),...inline2(text.slice(match.index+match[0].length),features,formats)]};var blockRules=[{feature:"horizontalRule",kind:"rule",pattern:/^(?:-{3,}|\*{3,}|_{3,})\s*$/u},{feature:"heading",kind:"heading",pattern:/^(?<marks>#{1,6})\s+(?<text>.*)$/u},{feature:"unorderedList",kind:"bullet",pattern:/^[-*+]\s+(?<text>.*)$/u},{feature:"orderedList",kind:"number",pattern:/^(?<start>\d+)[.)]\s+(?<text>.*)$/u},{feature:"blockquote",kind:"quote",pattern:/^>\s?(?<text>.*)$/u}];var lineOf=(line,features)=>{if(line.trim()===""){return{kind:"blank",level:0,text:""}}for(const{feature,kind,pattern}of blockRules){const match=features.has(feature)?pattern.exec(line):null;if(match!==null){const groups=match.groups??{};return{kind,level:groups.marks?.length??Number(groups.start??1),text:groups.text??""}}}return{kind:"paragraph",level:0,text:line.trim()}};var nodeOf=({first,lines},features)=>{switch(first.kind){case"bullet":case"number":{const start=first.kind==="number"?first.level:1;return element("list",lines.map((line,index)=>element("listitem",inline2(line,features),{value:start+index})),{listType:first.kind,start,tag:first.kind==="number"?"ol":"ul"})}case"heading":{return element("heading",inline2(first.text,features),{tag:`h${String(first.level)}`})}case"quote":{return element("quote",lines.flatMap((line,index)=>[...index===0?[]:[{type:"linebreak",version:1}],...inline2(line,features)]))}case"rule":{return{type:"horizontalrule",version:1}}default:{return element("paragraph",inline2(lines.join(" "),features),{textFormat:0,textStyle:""})}}};var groupable=new Set(["bullet","number","paragraph","quote"]);var editorState=(markdown,features)=>{const groups=[];for(const text of markdown.split(/\r?\n/u)){const line=lineOf(text,features);const last=groups.at(-1);if(last!==undefined&&last.first.kind===line.kind&&groupable.has(line.kind)){last.lines.push(line.text)}else{groups.push({first:line,lines:[line.text]})}}return{root:element("root",groups.filter(({first})=>first.kind!=="blank").map((group)=>nodeOf(group,features)))}};var lexicalFeatures=(editor)=>{const config=editor instanceof Object&&"editorConfig"in editor?editor.editorConfig:undefined;const features=config instanceof Object&&"features"in config?config.features:undefined;const enabled=features instanceof Object&&"enabledFeatures"in features?features.enabledFeatures:undefined;return Array.isArray(enabled)?new Set(enabled.map(String)):undefined};var markdownToRichText=({config,data,fields})=>{const errors=[];const blockFields=(field,row)=>field.type==="blocks"?[...field.blocks,...field.blockReferences??[]].map((reference)=>typeof reference==="string"?config.blocks?.find(({slug})=>slug===reference):reference).find((block)=>block?.slug===row.blockType)?.flattenedFields:undefined;const richText=(field,value,path)=>{if(typeof value!=="string"){return value}const features=lexicalFeatures(field.editor);if(features===undefined){errors.push({message:"Markdown needs the Lexical editor on this field",path});return value}return editorState(value,features)};const convertRow=(of,row,prefix)=>Object.fromEntries(Object.entries(row).map(([name,value])=>{const field=of.find((candidate)=>candidate.name===name);const path=`${prefix}${name}`;const nested=(entry,at)=>{const nestedRow=objectOf(entry);const nestedFields=field===undefined||nestedRow===undefined?undefined:blockFields(field,nestedRow)??("flattenedFields"in field?field.flattenedFields:undefined);return nestedRow===undefined||nestedFields===undefined?entry:convertRow(nestedFields,nestedRow,`${at}.`)};if(field?.type==="richText"){return[name,richText(field,value,path)]}return[name,Array.isArray(value)?value.map((entry,index)=>nested(entry,`${path}.${String(index)}`)):nested(value,path)]}));return{data:convertRow(fields,data,""),errors}};var createKeyField="ciCreateKey";var updateKeyField="ciUpdateKey";var updateKeyContext="ciGatewayUpdateKey";var ownUpdateKey=({context})=>{const key=context[updateKeyContext];return Predicate4.isString(key)?key:null};var controlFields=(collection,write)=>{const siteMakesId=write==="create"&&collection.flattenedFields.some(({name})=>name==="id");return new Set([...siteMakesId?[]:["id"],editorField,...stampedFields,...collection.flattenedFields.filter((field)=>field.hidden===true).map(({name})=>name)])};var fieldErrors=(errors)=>new GatewayOperationError2("invalid_request",`Invalid fields: ${errors.map(({message,path})=>`${path}: ${message}`).join("; ")}`);var collectionRefusal=(slug,reason)=>new GatewayOperationError2("invalid_request",`The collection "${slug}" is not ${reason}; the read operation lists the collections`);var siteRefusal=(error)=>{if(error instanceof ValidationError){return fieldErrors(error.data.errors)}if(error instanceof Locked){return new GatewayOperationError2("conflict",error.message)}if(error instanceof APIError&&error.status<500){return new GatewayOperationError2(error.status===403?"authorization_denied":"invalid_request",error.message)}return error};var documentOf=(value)=>{const json=JSON.parse(JSON.stringify(value));const doc=isResourceJsonValue2(json)?objectOf(json):undefined;if(doc===undefined){throw new TypeError("Payload gave a document that is not a JSON object")}return doc};var savedOf=(doc)=>{const{id,updatedAt:revision}=doc;if(typeof id!=="number"&&typeof id!=="string"||typeof revision!=="string"){throw new TypeError("Payload gave a document without an id or updatedAt")}return{id:String(id),revision}};var createOnce=async(payload,collection,key,create)=>{const first=async()=>{const{docs}=await payload.find({collection,depth:0,limit:1,overrideAccess:true,where:{[createKeyField]:{equals:key}}});return docs[0]};const found=await first();if(found!==undefined){return found}try{return await create()}catch(error){const made=await first();if(made===undefined){throw error}return made}};var updateOnce=async(payload,target,key,update)=>{if(key!==undefined){const newest=await payload.findByID({...target,depth:0,disableErrors:true,draft:true,overrideAccess:true,showHiddenFields:true});if(newest!==null&&documentOf(newest)[updateKeyField]===key){return newest}}return await update()};var saveOnSite=async(write)=>{try{return savedOf(documentOf(await write()))}catch(error){throw siteRefusal(error)}};var operations=({payload,settings})=>{const integrationUser=async()=>await readIntegrationUser(payload,settings);const collections=Object.entries(settings.collections).flatMap(([slug,options])=>{const collection=payload.collections[slug]?.config;return collection===undefined||options===undefined?[]:[{collection,writable:options.writable===true}]});const listed=collections.map(({collection,writable})=>({drafts:hasDraftsEnabled3(collection),slug:collection.slug,trash:collection.trash===true,writable}));const exposed=(slug)=>{const found=collections.find(({collection})=>collection.slug===slug);if(found===undefined){throw collectionRefusal(slug,"exposed")}return found};const writable=(slug)=>{const found=exposed(slug);if(!found.writable){throw collectionRefusal(slug,"writable")}return found.collection};const{localization}=payload.config;const inLocale=(locale)=>{if(locale===undefined){return{}}if(localization===false||!localization.localeCodes.includes(locale)){throw new GatewayOperationError2("invalid_request",localization===false?"The site has no localization: send no locale":`The site has no locale "${locale}"; its locales are ${localization.localeCodes.join(", ")}`)}return{locale}};const writeData=(collection,data,write)=>{const control=controlFields(collection,write);const refused=Object.keys(data).filter((name)=>control.has(name));if(refused.length>0){throw new GatewayOperationError2("invalid_request",`Only Payload and the plugin write ${refused.map((name)=>`"${name}"`).join(", ")}: the publish, unpublish and delete operations change the Publication State and the trash`)}const converted=markdownToRichText({config:payload.config,data,fields:collection.flattenedFields});if(converted.errors.length>0){throw fieldErrors(converted.errors)}return converted.data};const create=async({context,idempotencyKey,input})=>{const collection=writable(input.collection);const locale=inLocale(input.locale);if(idempotencyKey===undefined){throw new GatewayOperationError2("invalid_request","A create needs an idempotency key")}const data=writeData(collection,input.data,"create");const user=await integrationUser();return await saveOnSite(()=>createOnce(payload,collection.slug,idempotencyKey,()=>payload.create({...locale,collection:collection.slug,context:editorContext(context.actor),data:{...data,[createKeyField]:idempotencyKey},depth:0,draft:hasDraftsEnabled3(collection),overrideAccess:false,user})))};const remove=async({context,input})=>{const collection=writable(input.collection);const expected=collection.trash?"trash":"permanent";if(input.mode!==expected){throw new GatewayOperationError2("invalid_request",`The collection "${collection.slug}" ${collection.trash?"has":"has no"} trash: a delete needs the mode "${expected}"`)}const user=await integrationUser();const target={collection:collection.slug,context:editorContext(context.actor),depth:0,id:input.id,overrideAccess:false,overrideLock:false,user};const{id}=await saveOnSite(async()=>collection.trash?await payload.update({...target,data:{deletedAt:new Date().toISOString()}}):await payload.delete(target));return{id}};const setStatus=(status)=>async({context,input})=>{const collection=writable(input.collection);const locale=inLocale(input.locale);if(!hasDraftsEnabled3(collection)){throw new GatewayOperationError2("invalid_request",`The collection "${collection.slug}" has no drafts: its documents are always published`)}const user=await integrationUser();return await saveOnSite(()=>payload.update({...locale,collection:collection.slug,context:editorContext(context.actor),data:{_status:status},depth:0,id:input.id,overrideAccess:false,overrideLock:false,user}))};const read=async({input})=>{const{collection}=exposed(input.collection);const locale=inLocale(input.locale);const{id}=input;if(id===undefined){return{collections:listed,document:null}}const user=await integrationUser();const version=async(draft)=>{const doc=await payload.findByID({...locale,collection:collection.slug,depth:0,disableErrors:true,draft,fallbackLocale:false,id,overrideAccess:false,user});if(doc===null){return null}const{[editorField]:_editor,...fields}=documentOf(doc);return fields};const[row,latest]=await Promise.all([version(false),version(true)]);const drafts=hasDraftsEnabled3(collection);const published=drafts&&row?._status!=="published"?null:row;const draft=drafts&&latest?._status==="draft"?latest:null;const newest=draft??published;if(newest===null){throw new GatewayOperationError2("invalid_request",`The collection "${collection.slug}" has no document "${id}" that the Integration User can read`)}return{collections:listed,document:{draft,...savedOf(newest),published}}};const update=async({context,idempotencyKey,input})=>{const collection=writable(input.collection);const locale=inLocale(input.locale);const data=writeData(collection,input.data,"update");const user=await integrationUser();const target={collection:collection.slug,id:input.id};return await saveOnSite(()=>updateOnce(payload,target,idempotencyKey,()=>payload.update({...locale,...target,context:{...readRevisionContext(input),...editorContext(context.actor),...idempotencyKey!==undefined&&{[updateKeyContext]:idempotencyKey}},data,depth:0,draft:hasDraftsEnabled3(collection),overrideAccess:false,overrideLock:false,user})))};return{create,delete:remove,publish:setStatus("published"),read,unpublish:setStatus("draft"),update}};var operationsPart={config:(config,settings)=>({...config,collections:(config.collections??[]).map((collection)=>settings.collections[collection.slug]?.writable===true?{...collection,fields:[...collection.fields,{hidden:true,name:createKeyField,type:"text",unique:true},{hidden:true,hooks:{beforeChange:[ownUpdateKey]},name:updateKeyField,type:"text"}]}:collection)}),serve:(site)=>({operations:operations(site)})};import{GatewayOperationError as GatewayOperationError3}from"@collective-intelligence/external-apps-server-sdk/gateway";import{isResourceJsonValue as isResourceJsonValue3,resourceFailure as resourceFailure2,resourceSuccess as resourceSuccess2}from"@collective-intelligence/external-apps-server-sdk/resources";import{APIError as APIError2,Locked as Locked2,ValidationError as ValidationError2}from"payload";import{hasDraftsEnabled as hasDraftsEnabled4}from"payload/shared";var knowledgeWrite={organization:"required",principalKinds:["service_principal"],scopes:["resources:write"]};var refused2=(code,message)=>({code,message,retryable:false});class RefusalError extends Error{error;constructor(code,message){super(message);this.name="RefusalError";this.error=refused2(code,message)}}var noItem=()=>new RefusalError("not_found","The site has no item with this Item Identity");var identityOf=(id)=>{const identity=decodeItemIdentity(id);if(identity===undefined){throw noItem()}return identity};var newerDraft=(identity,newest)=>new RefusalError("conflict",`The document "${String(identity.id)}" has a newer draft, the draft item ${encodeItemIdentity({...identity,state:"draft"})} saved at ${newest.updatedAt}: publish or discard it in Payload, then write the item again`);var relatedTypes=new Set(["join","relationship","ui","upload"]);var recordValue=(value)=>{const data=isResourceJsonValue3(value)?objectOf(value):undefined;if(data===undefined){throw new RefusalError("invalid_request","The record value is not an object")}return data};var writableData=(collection,data,write)=>{const control=controlFields(collection,write);const writable=new Set(collection.flattenedFields.filter((field)=>!control.has(field.name)&&!relatedTypes.has(field.type)).map(({name})=>name));const readOnly=Object.keys(data).filter((name)=>!writable.has(name));if(readOnly.length>0){throw new RefusalError("invalid_request",`The site keeps ${readOnly.map((name)=>`"${name}"`).join(", ")} read-only: a Knowledge write sends only fields mapped one to one from a Payload field`)}return data};var siteRefusal2=(error)=>{if(error instanceof RefusalError){return error.error}if(error instanceof Locked2||error instanceof GatewayOperationError3&&error.code==="conflict"){return refused2("conflict",error.message)}if(error instanceof ValidationError2){return refused2("invalid_request",`Invalid fields: ${error.data.errors.map(({message,path})=>`${path}: ${message}`).join("; ")}`)}if(error instanceof APIError2&&error.status<500){return refused2(error.status===403?"forbidden":"invalid_request",error.message)}throw error};var knowledgeWrites=({payload,settings})=>{const read=payloadRecords({payload,settings});const integrationUser=async()=>await readIntegrationUser(payload,settings);const findRecord=async(slug,identity)=>{const id=encodeItemIdentity(identity);const records=await read(slug,{id:{equals:identity.id}});return records.find((candidate)=>candidate.id===id)};const recordOf=async(slug,identity)=>{const record=await findRecord(slug,identity);if(record===undefined){throw noItem()}return record};const newestOf=async(collection,identity,user)=>{const doc=await payload.findByID({collection:collection.slug,depth:0,disableErrors:true,draft:true,fallbackLocale:false,id:identity.id,...identity.language!==undefined&&{locale:identity.language},overrideAccess:false,trash:true,user});if(doc===null){throw noItem()}const{_status:status,deletedAt,updatedAt}=documentOf(doc);const revision=String(updatedAt);return{context:readRevisionContext({collection:collection.slug,id:identity.id,revision}),draft:status==="draft",trashed:deletedAt!==null&&deletedAt!==undefined,updatedAt:revision}};const{localization}=payload.config;const languageOf=(localized,language)=>{if(!localized||localization===false){if(language!==undefined){throw new RefusalError("invalid_request",'The collection has no localized fields: send no "ciLanguage"')}return}if(language===undefined){return localization.defaultLocale}const locale=localization.localeCodes.find((code)=>code===language);if(locale===undefined){throw new RefusalError("invalid_request",`"ciLanguage" names no locale of the site; its locales are ${localization.localeCodes.join(", ")}`)}return locale};const create=async(request,context,{collection,localized})=>{const{ciLanguage,...fields}=recordValue(request.value);const language=languageOf(localized,ciLanguage);const data=writableData(collection,fields,"create");const drafts=hasDraftsEnabled4(collection);const user=await integrationUser();const doc=await createOnce(payload,collection.slug,request.idempotencyKey,()=>payload.create({collection:collection.slug,context:editorContext(context.actor),data:{...data,[createKeyField]:request.idempotencyKey},depth:0,draft:drafts,...language!==undefined&&{locale:language},overrideAccess:false,user}));return await recordOf(collection.slug,{id:doc.id,language,state:drafts?"draft":"published"})};const update=async(request,context,{collection})=>{const identity=identityOf(request.id);const data=writableData(collection,recordValue(request.value),"update");const user=await integrationUser();const newest=await newestOf(collection,identity,user);if(newest.trashed){throw noItem()}const drafts=hasDraftsEnabled4(collection);const draft=drafts&&identity.state==="draft";if(!draft&&newest.draft){throw newerDraft(identity,newest)}if(request.expectedRevision!==""){const current=await findRecord(collection.slug,identity);if(current?.revision!==request.expectedRevision){throw new RefusalError("conflict",`The item ${request.id} changed on the site after CI read it: read it again`)}}await payload.update({collection:collection.slug,context:{...newest.context,...editorContext(context.actor)},data:{...data,...drafts&&!draft&&{_status:"published"}},depth:0,draft,id:identity.id,...identity.language!==undefined&&{locale:identity.language},overrideAccess:false,overrideLock:false,user});return await recordOf(collection.slug,identity)};const remove=async(request,context,{collection})=>{const identity=identityOf(request.id);if(collection.trash!==true){throw new RefusalError("invalid_request",`The collection "${collection.slug}" has no trash, so a Knowledge delete would delete the document for ever: delete it in Payload`)}if(identity.state==="draft"){throw new RefusalError("invalid_request","A Knowledge delete of a draft item is refused: discard the draft in Payload")}const user=await integrationUser();const newest=await newestOf(collection,identity,user);if(newest.draft){throw newerDraft(identity,newest)}if(!newest.trashed){await payload.update({collection:collection.slug,context:{...newest.context,...editorContext(context.actor)},data:{deletedAt:new Date().toISOString()},depth:0,id:identity.id,overrideAccess:false,overrideLock:false,user})}return null};const restore=async(request,context,{collection})=>{const identity=identityOf(request.id);const user=await integrationUser();const newest=await newestOf(collection,identity,user);if(newest.trashed){await payload.update({collection:collection.slug,context:{...newest.context,...editorContext(context.actor)},data:{deletedAt:null},depth:0,id:identity.id,overrideAccess:false,overrideLock:false,trash:true,user})}return await recordOf(collection.slug,identity)};return{create,remove,restore,update}};var answered=async(requestId,write)=>{try{return resourceSuccess2(requestId,await write())}catch(error){return resourceFailure2(requestId,siteRefusal2(error))}};var served2=(exposure,collection,writes)=>{const{resource}=exposure;const{authorization,definition}=resource;const target={collection,localized:definition.identity.fields.some(({name})=>name==="ciLanguage")};return{...exposure,access:"read_write",resource:{...resource,authorization:{...authorization,create:knowledgeWrite,hard_delete:knowledgeWrite,restore:knowledgeWrite,update:knowledgeWrite},definition:{...definition,capabilities:{...definition.capabilities,create:true,hardDelete:true,restore:true,update:true}},execute:async(request,context,options)=>{switch(request.operation){case"create":{return await answered(request.requestId,()=>writes.create(request,context,target))}case"hard_delete":{return await answered(request.requestId,()=>writes.remove(request,context,target))}case"restore":{return await answered(request.requestId,()=>writes.restore(request,context,target))}case"update":{return await answered(request.requestId,()=>writes.update(request,context,target))}default:{return await resource.execute(request,context,options)}}}}}};var writeBackPart={serve:(site)=>{const writes=knowledgeWrites(site);return{knowledge:(exposure)=>{const{id}=exposure.resource.definition;const collection=site.payload.collections[id]?.config;return collection!==undefined&&site.settings.collections[id]?.writable===true?served2(exposure,collection,writes):exposure}}}};var contract={domain:"documents",id:"payload",version:"1.0.0"};var projection=(document)=>({dialect:"https://json-schema.org/draft/2020-12/schema",document,fidelity:"exact"});var object2=(properties,optional=[])=>({additionalProperties:false,properties,required:Object.keys(properties).filter((key)=>!optional.includes(key)),type:"object"});var text=(description)=>({description,minLength:1,type:"string"});var flag=(description)=>({description,type:"boolean"});var documentVersion=(description)=>({description,type:["object","null"]});var collection=text("Slug of a Payload collection. The read operation lists the collections.");var id=text("Id of the Payload document.");var revision=text("Revision of the Payload document. An update sends the revision that the read operation returned.");var locale=text("Locale code of the site's Payload localization. Without it, the operation uses the default locale; a read gives no fallback text.");var data={description:"Field values of the document: rich text as Markdown, other fields and blocks as JSON.",type:"object"};var saved=projection(object2({id,revision}));var policy=(effects)=>({authorization:{delegatedSubject:"allowed",organization:"required",principalKinds:["service_principal"],scopes:[`documents:${effects}`]},effects,execution:{mode:"synchronous",timeoutMs:30000},limits:{maxRequestBytes:1048576,maxResponseBytes:4194304},retry:{maxAttempts:3,mode:"idempotent_only"},version:contract.version});var operations2=[{...policy("write"),description:"Creates a document in a writable collection. A collection with drafts saves it as a draft.",id:"create",idempotency:"requires_key",input:projection(object2({collection,data,locale},["locale"])),output:saved,title:"Create a Payload document"},{...policy("write"),description:"Deletes a document of a writable collection. The mode must match whether the collection has trash.",id:"delete",idempotency:"idempotent",input:projection(object2({collection,id,mode:{description:"`trash` moves the document to trash; `permanent` deletes it for ever.",enum:["trash","permanent"]}})),output:projection(object2({id})),title:"Delete a Payload document"},{...policy("write"),description:"Publishes the newest draft of a document.",id:"publish",idempotency:"idempotent",input:projection(object2({collection,id,locale},["locale"])),output:saved,title:"Publish a Payload document"},{...policy("read"),description:"Lists the collections of the site and, for an id, reads the newest draft and the published version of the document.",id:"read",idempotency:"safe",input:projection(object2({collection,id,locale},["id","locale"])),output:projection(object2({collections:{items:object2({drafts:flag("The collection has drafts."),slug:text("Slug of the collection."),trash:flag("The collection has trash."),writable:flag("The operations can write the collection.")}),type:"array"},document:{anyOf:[{type:"null"},object2({draft:documentVersion("The draft that is newer than the published version, or null."),id,published:documentVersion("The published version, or null."),revision})],description:"The document, or null when the input has no id."}})),title:"Read a Payload document"},{...policy("write"),description:"Unpublishes a document; its newest version stays as a draft.",id:"unpublish",idempotency:"idempotent",input:projection(object2({collection,id,locale},["locale"])),output:saved,title:"Unpublish a Payload document"},{...policy("write"),description:"Saves new field values of a document. In a collection with drafts, it saves a draft. The update fails with a conflict when the document changed after the read.",id:"update",idempotency:"idempotent",input:projection(object2({collection,data,id,locale,revision},["locale"])),output:saved,title:"Update a Payload document"}];var payloadOperationContract={capabilities:{resources:false},datasets:[],id:contract.id,knowledge:[],operationDomains:[{description:"The documents of a Payload CMS site.",id:contract.domain,operations:operations2.map((operation)=>({...operation,canonicalReference:`${contract.id}/${contract.domain}/${operation.id}@${operation.version}`})),title:"Payload documents"}],organizationBinding:{mode:"installed_organization"},protocolVersion:"2",version:contract.version};var knowledgeRead={organization:"required",principalKinds:["service_principal"],scopes:["resources:read"]};var noCaller=()=>Promise.reject(new GatewayCallerAuthError2("unauthenticated","The Payload Plugin has no Gateway Connection"));var notServed=(id)=>()=>Promise.reject(new GatewayOperationError4("capability_not_supported",`The Payload Plugin does not serve the ${id} operation`));var knowledgeExposure=({definition,...manifest})=>({...manifest,access:"read",resource:{authorization:{list:knowledgeRead},definition,execute:(request)=>Promise.resolve({correlationId:request.requestId,error:{code:"capability_not_supported",message:`The Payload Plugin does not serve ${request.operation} on ${definition.id}`,retryable:false},ok:false})}});var gatewayKernel=({parts,payload,settings})=>{const served=parts.map((part)=>part.serve?.({payload,settings})??{});const handlers={};const connection={};for(const serving of served){Object.assign(handlers,serving.operations);Object.assign(connection,serving.connection)}return createGatewayKernel({basePath:formatAdminURL({apiRoute:payload.config.routes.api,path:gatewayMountPath}),gateway:defineGateway({id:payloadOperationContract.id,knowledge:payloadKnowledgeResources(payload.config,Object.keys(settings.collections)).map((resource)=>{let exposure=knowledgeExposure(resource);for(const serving of served){exposure=serving.knowledge?.(exposure)??exposure}return exposure}),operationDomains:payloadOperationContract.operationDomains.map((domain)=>({...domain,operations:domain.operations.map(({canonicalReference:_canonicalReference,...operation})=>({...operation,handler:handlers[operation.id]??notServed(operation.id)}))})),version:payloadOperationContract.version}),verifyCaller:noCaller,...connection})};var payloadPlugin=(parts)=>(options)=>{const settings=options;const kernels=new WeakMap;const handler=async(request)=>{if(!(request instanceof Request)){throw new TypeError("The Gateway endpoint needs the Web Request")}const{payload}=request;let kernel=kernels.get(payload);if(kernel===undefined){kernel=gatewayKernel({parts,payload,settings});kernels.set(payload,kernel)}return await kernel.handle(request)};const endpoints=["delete","get","patch","post"].map((method)=>({handler,method,path:`${gatewayMountPath}/:path*`}));return(config)=>{let result={...config,endpoints:[...config.endpoints??[],...endpoints]};for(const part of parts){result=part.config?.(result,settings)??result}return result}};var ciPayloadPlugin=payloadPlugin([sourcePart,grantStorePart,pushJobPart,operationsPart,editorFieldPart,conflictPart,filePart,writeBackPart,generatePart]);export{ciPayloadPlugin};