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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +1075 -2
  2. package/dist/admin.d.ts +7556 -0
  3. package/dist/admin.js +6 -0
  4. package/dist/auth/better-auth.d.ts +71 -0
  5. package/dist/auth/better-auth.js +1 -0
  6. package/dist/auth/federated.d.ts +135 -0
  7. package/dist/auth/federated.js +8 -0
  8. package/dist/auth.d.ts +162 -0
  9. package/dist/auth.js +1 -0
  10. package/dist/express.d.ts +644 -0
  11. package/dist/express.js +1 -0
  12. package/dist/gateway/contracts.d.ts +663 -0
  13. package/dist/gateway/contracts.js +0 -0
  14. package/dist/gateway.d.ts +762 -0
  15. package/dist/gateway.js +8 -0
  16. package/dist/index.d.ts +597 -0
  17. package/dist/index.js +9 -0
  18. package/dist/knowledge-sources/payload.d.ts +420 -0
  19. package/dist/knowledge-sources/payload.js +1 -0
  20. package/dist/knowledge-sources/strapi.d.ts +389 -0
  21. package/dist/knowledge-sources/strapi.js +1 -0
  22. package/dist/persistence/drizzle-effect.d.ts +38 -0
  23. package/dist/persistence/drizzle-effect.js +1 -0
  24. package/dist/persistence/drizzle.d.ts +1514 -0
  25. package/dist/persistence/drizzle.js +18 -0
  26. package/dist/resources.d.ts +423 -0
  27. package/dist/resources.js +15 -0
  28. package/dist/runtime/effect.d.ts +954 -0
  29. package/dist/runtime/effect.js +15 -0
  30. package/dist/runtime/express.d.ts +644 -0
  31. package/dist/runtime/express.js +1 -0
  32. package/dist/runtime/nestjs.d.ts +802 -0
  33. package/dist/runtime/nestjs.js +8 -0
  34. package/dist/runtime/next.d.ts +874 -0
  35. package/dist/runtime/next.js +8 -0
  36. package/dist/runtime/web.d.ts +776 -0
  37. package/dist/runtime/web.js +8 -0
  38. package/dist/tools/ai-sdk.d.ts +170 -0
  39. package/dist/tools/ai-sdk.js +8 -0
  40. package/package.json +242 -4
@@ -0,0 +1,420 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ export type ResourceJsonValue = null | boolean | number | string | readonly ResourceJsonValue[] | Readonly<{
4
+ [key: string]: ResourceJsonValue;
5
+ }>;
6
+ /** Opaque wire identity. Callers must not infer or concatenate its internals. */
7
+ export type ResourceId = string;
8
+ export type ResourceRecordId = ResourceId;
9
+ /** Opaque concurrency token independent from source timestamps. */
10
+ export type ResourceRevision = string;
11
+ /** Opaque pagination position issued and consumed only by a resource adapter. */
12
+ export type ResourceCursor = string;
13
+ export type IdempotencyKey = string;
14
+ export type ResourceIdentityField = Readonly<{
15
+ name: string;
16
+ type: "number" | "string";
17
+ }>;
18
+ export type ResourceCapabilities = Readonly<{
19
+ create?: boolean;
20
+ /** Common entity deletion is always soft deletion. */
21
+ delete?: boolean;
22
+ get?: boolean;
23
+ hardDelete?: boolean;
24
+ includeDeleted?: boolean;
25
+ restore?: boolean;
26
+ search: true;
27
+ softDelete?: boolean;
28
+ update?: boolean;
29
+ }>;
30
+ export type ResourcePaginationMode = "cursor" | "page";
31
+ export type PortableResourceSchema = Readonly<Record<string, ResourceJsonValue>>;
32
+ export type ResourceDefinition<Entity, Create = Entity, Update = Partial<Entity>> = Readonly<{
33
+ capabilities: ResourceCapabilities;
34
+ concurrency: "revision";
35
+ id: string;
36
+ identity: Readonly<{
37
+ fields: readonly [
38
+ ResourceIdentityField,
39
+ ...ResourceIdentityField[]
40
+ ];
41
+ }>;
42
+ query: Readonly<{
43
+ filterableFields: readonly string[];
44
+ pagination: Readonly<{
45
+ modes: readonly ResourcePaginationMode[];
46
+ }>;
47
+ sortableFields: readonly string[];
48
+ textSearchFields?: readonly string[];
49
+ }>;
50
+ schemas: Readonly<{
51
+ create?: PortableResourceSchema;
52
+ entity: PortableResourceSchema;
53
+ update?: PortableResourceSchema;
54
+ }>;
55
+ version: string;
56
+ /** Portable UI metadata; required/enum/nullability remain in schemas. */
57
+ metadata?: Readonly<Record<string, ResourceJsonValue>>;
58
+ /** Type-only slots keep definition values portable and serializable. */
59
+ readonly __types?: Readonly<{
60
+ create: Create;
61
+ entity: Entity;
62
+ update: Update;
63
+ }>;
64
+ }>;
65
+ export type FilterValue = ResourceJsonValue | readonly ResourceJsonValue[];
66
+ export type ResourceFilter = Readonly<{
67
+ field: string;
68
+ operator: "contains" | "ends_with" | "eq" | "gt" | "gte" | "in" | "lt" | "lte" | "ne" | "not_in" | "starts_with";
69
+ value: FilterValue;
70
+ }> | Readonly<{
71
+ field: string;
72
+ operator: "is_not_null" | "is_null";
73
+ }> | Readonly<{
74
+ filters: readonly ResourceFilter[];
75
+ operator: "and" | "or";
76
+ }> | Readonly<{
77
+ filter: ResourceFilter;
78
+ operator: "not";
79
+ }>;
80
+ export type ResourceSort = Readonly<{
81
+ direction: "asc" | "desc";
82
+ field: string;
83
+ }>;
84
+ export type ResourcePagination = Readonly<{
85
+ mode: "cursor";
86
+ cursor?: ResourceCursor;
87
+ limit: number;
88
+ }> | Readonly<{
89
+ mode: "page";
90
+ page: number;
91
+ pageSize: number;
92
+ }>;
93
+ export type ResourceListQuery = Readonly<{
94
+ filter?: ResourceFilter;
95
+ includeDeleted?: boolean;
96
+ pagination: ResourcePagination;
97
+ sort?: readonly ResourceSort[];
98
+ textSearch?: string;
99
+ }>;
100
+ export type ResourceRecord<Entity> = Readonly<{
101
+ deletedAt?: string;
102
+ id: ResourceRecordId;
103
+ revision: ResourceRevision;
104
+ value: Entity;
105
+ }>;
106
+ export type ResourceErrorCode = "capability_not_supported" | "conflict" | "forbidden" | "internal" | "invalid_request" | "not_found" | "rate_limited" | "transport_error" | "unauthenticated" | "unavailable";
107
+ export type ResourceError = Readonly<{
108
+ code: ResourceErrorCode;
109
+ /** Client-observed dispatch outcome; uncertainty never proves rollback. */
110
+ outcome?: "not_dispatched" | "rejected" | "uncertain";
111
+ details?: Readonly<Record<string, ResourceJsonValue>>;
112
+ message: string;
113
+ retryable: boolean;
114
+ }>;
115
+ export type ResourceResult<Value> = Readonly<{
116
+ correlationId: string;
117
+ ok: true;
118
+ value: Value;
119
+ }> | Readonly<{
120
+ correlationId: string;
121
+ error: ResourceError;
122
+ ok: false;
123
+ }>;
124
+ export type ResourceListRequest = Readonly<{
125
+ operation: "list";
126
+ query: ResourceListQuery;
127
+ requestId: string;
128
+ resourceId: string;
129
+ }>;
130
+ export type ResourceGetRequest = Readonly<{
131
+ id: ResourceRecordId;
132
+ includeDeleted?: boolean;
133
+ operation: "get";
134
+ requestId: string;
135
+ resourceId: string;
136
+ }>;
137
+ export type ResourceCreateRequest<Create> = Readonly<{
138
+ idempotencyKey: IdempotencyKey;
139
+ operation: "create";
140
+ requestId: string;
141
+ resourceId: string;
142
+ value: Create;
143
+ }>;
144
+ export type ResourceUpdateRequest<Update> = Readonly<{
145
+ expectedRevision: ResourceRevision;
146
+ id: ResourceRecordId;
147
+ idempotencyKey?: IdempotencyKey;
148
+ operation: "update";
149
+ requestId: string;
150
+ resourceId: string;
151
+ value: Update;
152
+ }>;
153
+ export type ResourceLifecycleRequest = Readonly<{
154
+ expectedRevision: ResourceRevision;
155
+ id: ResourceRecordId;
156
+ idempotencyKey?: IdempotencyKey;
157
+ operation: "hard_delete" | "restore" | "soft_delete";
158
+ requestId: string;
159
+ resourceId: string;
160
+ }>;
161
+ export type ResourceTransportRequest = ResourceCreateRequest<unknown> | ResourceGetRequest | ResourceLifecycleRequest | ResourceListRequest | ResourceUpdateRequest<unknown>;
162
+ export type PrincipalKind = "detached_user" | "service_principal";
163
+ export type DelegatedSubjectPolicy = "allowed" | "forbidden" | "required";
164
+ export type AuthorizationRequirement = Readonly<{
165
+ delegatedSubject?: DelegatedSubjectPolicy;
166
+ organization: "required";
167
+ principalKinds: readonly PrincipalKind[];
168
+ scopes: readonly string[];
169
+ }>;
170
+ export type ExternalAuditSubject = Readonly<{
171
+ issuer: string;
172
+ mappedCiUserId?: string;
173
+ subject: string;
174
+ }>;
175
+ export type GatewayCallerIdentity = Readonly<{
176
+ audience: readonly string[];
177
+ binding: string;
178
+ expiresAt: number;
179
+ installationId: string;
180
+ issuer: string;
181
+ organizationId: string;
182
+ principalKind: PrincipalKind;
183
+ requestId: string;
184
+ scopes: readonly string[];
185
+ subject: string;
186
+ }>;
187
+ export type GatewayInvocationContext = Readonly<{
188
+ caller: GatewayCallerIdentity;
189
+ correlationId: string;
190
+ externalAuditSubject?: ExternalAuditSubject;
191
+ organizationId: string;
192
+ }>;
193
+ /** Full inventory only: no filters, text search or caller-selected ordering.
194
+ * Continue consecutive pages with the first watermark. A conflict requires restart.
195
+ */
196
+ export type ResourceInventoryRequest = Readonly<{
197
+ page: number;
198
+ pageSize: number;
199
+ watermark?: string;
200
+ }>;
201
+ export type GatewayResourceOperation = ResourceTransportRequest["operation"];
202
+ export type GatewayResourceAuthorization = Readonly<Partial<Record<GatewayResourceOperation, AuthorizationRequirement>>>;
203
+ export type GatewayResourceDefinition<Entity = unknown, Create = Entity, Update = Partial<Entity>> = Readonly<{
204
+ authorization: GatewayResourceAuthorization;
205
+ definition: ResourceDefinition<Entity, Create, Update>;
206
+ execute: (request: ResourceTransportRequest, context: GatewayInvocationContext, options?: Readonly<{
207
+ signal?: AbortSignal;
208
+ }>) => Promise<ResourceResult<unknown>>;
209
+ scan?: (request: ResourceInventoryRequest & Readonly<{
210
+ requestId: string;
211
+ resourceId: string;
212
+ }>, context: GatewayInvocationContext, options?: Readonly<{
213
+ signal?: AbortSignal;
214
+ }>) => Promise<ResourceResult<unknown>>;
215
+ changes?: (request: Readonly<{
216
+ cursor?: string;
217
+ limit: number;
218
+ requestId: string;
219
+ resourceId: string;
220
+ }>, context: GatewayInvocationContext, options?: Readonly<{
221
+ signal?: AbortSignal;
222
+ }>) => Promise<ResourceResult<unknown>>;
223
+ }>;
224
+ export type NativeRecord = Readonly<Record<string, ResourceJsonValue>>;
225
+ export type DataSourceKind = "drizzle_postgresql" | "payload" | "strapi";
226
+ export type DataSourceCapabilities = Readonly<{
227
+ create: boolean;
228
+ hardDelete: boolean;
229
+ incrementalChanges: boolean;
230
+ nativePolicy: boolean;
231
+ pagination: readonly ("cursor" | "page")[];
232
+ read: true;
233
+ relations: boolean;
234
+ restore: boolean;
235
+ softDelete: boolean;
236
+ transactions: boolean;
237
+ update: boolean;
238
+ }>;
239
+ export type DataSourceRelation = Readonly<{
240
+ cardinality: "many" | "one";
241
+ field: string;
242
+ targetIdentityFields: readonly [
243
+ string,
244
+ ...string[]
245
+ ];
246
+ targetResourceId: string;
247
+ }>;
248
+ export type DataSourceProjection = Readonly<{
249
+ fields: readonly string[];
250
+ redact?: readonly string[];
251
+ relations?: readonly DataSourceRelation[];
252
+ }>;
253
+ export type DataSourceChange<Entity> = Readonly<{
254
+ kind: "tombstone";
255
+ deletedAt: string;
256
+ id: string;
257
+ revision: string;
258
+ }> | Readonly<{
259
+ kind: "upsert";
260
+ record: ResourceRecord<Entity>;
261
+ }>;
262
+ export type DataSourceChangePage<Entity> = Readonly<{
263
+ changes: readonly DataSourceChange<Entity>[];
264
+ nextCursor?: string;
265
+ }>;
266
+ export type NativeChange = Readonly<{
267
+ deletedAt: string;
268
+ identity: NativeRecord;
269
+ kind: "tombstone";
270
+ revision: string;
271
+ updatedAt: string;
272
+ }> | Readonly<{
273
+ kind: "upsert";
274
+ row: NativeRecord;
275
+ }>;
276
+ export type NativeChangePage = Readonly<{
277
+ changes: readonly NativeChange[];
278
+ }>;
279
+ export type DataSourceAdapter<Entity = NativeRecord> = GatewayResourceDefinition<Entity> & Readonly<{
280
+ dataSource: Readonly<{
281
+ capabilities: DataSourceCapabilities;
282
+ kind: DataSourceKind;
283
+ }>;
284
+ }>;
285
+ export type DataSourceBaseOptions<Entity = NativeRecord> = Readonly<{
286
+ authorization: GatewayResourceAuthorization;
287
+ capabilities: DataSourceCapabilities;
288
+ definition: ResourceDefinition<Entity>;
289
+ identity: Readonly<{
290
+ fields: readonly [
291
+ string,
292
+ ...string[]
293
+ ];
294
+ }>;
295
+ maxPageSize?: number;
296
+ projection: DataSourceProjection;
297
+ revision: (record: NativeRecord) => string;
298
+ softDelete?: Readonly<{
299
+ deletedAt: (record: NativeRecord) => string | undefined;
300
+ }>;
301
+ updatedAt: (record: NativeRecord) => string;
302
+ }>;
303
+ export type DataSourceMappingErrorCode = "capability_mismatch" | "duplicate_field" | "invalid_identity" | "invalid_pagination" | "unsupported_mapping";
304
+ export declare class DataSourceMappingError extends TypeError {
305
+ readonly code: DataSourceMappingErrorCode;
306
+ constructor(code: DataSourceMappingErrorCode, message: string);
307
+ }
308
+ export type PayloadOpaqueValue = object | null;
309
+ export type PayloadWhere = Readonly<Record<string, ResourceJsonValue>>;
310
+ export type PayloadCallContext = Readonly<{
311
+ overrideAccess: false;
312
+ req?: PayloadOpaqueValue;
313
+ user: PayloadOpaqueValue;
314
+ }>;
315
+ export interface PayloadLocalApi {
316
+ readonly create: (input: PayloadCallContext & Readonly<{
317
+ collection: string;
318
+ data: ResourceJsonValue;
319
+ draft: boolean;
320
+ locale?: string;
321
+ }>) => Promise<NativeRecord>;
322
+ readonly delete: (input: PayloadCallContext & Readonly<{
323
+ collection: string;
324
+ id: number | string;
325
+ locale?: string;
326
+ }>) => Promise<NativeRecord>;
327
+ readonly find: (input: PayloadCallContext & Readonly<{
328
+ collection: string;
329
+ draft: boolean;
330
+ limit: number;
331
+ locale?: string;
332
+ page: number;
333
+ sort?: readonly string[];
334
+ where?: PayloadWhere;
335
+ }>) => Promise<Readonly<{
336
+ docs: readonly NativeRecord[];
337
+ page?: number;
338
+ totalDocs: number;
339
+ totalPages: number;
340
+ }>>;
341
+ readonly findByID: (input: PayloadCallContext & Readonly<{
342
+ collection: string;
343
+ draft: boolean;
344
+ id: number | string;
345
+ locale?: string;
346
+ }>) => Promise<NativeRecord | null>;
347
+ readonly findGlobal?: (input: PayloadCallContext & Readonly<{
348
+ draft: boolean;
349
+ locale?: string;
350
+ slug: string;
351
+ }>) => Promise<NativeRecord>;
352
+ readonly update: (input: PayloadCallContext & Readonly<{
353
+ collection: string;
354
+ data: ResourceJsonValue;
355
+ draft: boolean;
356
+ id: number | string;
357
+ locale?: string;
358
+ }>) => Promise<NativeRecord>;
359
+ readonly updateGlobal?: (input: PayloadCallContext & Readonly<{
360
+ data: ResourceJsonValue;
361
+ draft: boolean;
362
+ locale?: string;
363
+ slug: string;
364
+ }>) => Promise<NativeRecord>;
365
+ }
366
+ export type PayloadGatewayHooks = Readonly<{
367
+ changes?: (input: {
368
+ after?: Readonly<{
369
+ externalId: string;
370
+ updatedAt: string;
371
+ }>;
372
+ collection: string;
373
+ limit: number;
374
+ locale?: string;
375
+ organizationId: string;
376
+ overlapMs: number;
377
+ signal?: AbortSignal;
378
+ user: PayloadOpaqueValue;
379
+ }) => Promise<NativeChangePage>;
380
+ hardDelete?: (input: {
381
+ collection: string;
382
+ id: number | string;
383
+ locale?: string;
384
+ organizationId: string;
385
+ signal?: AbortSignal;
386
+ user: PayloadOpaqueValue;
387
+ }) => Promise<void>;
388
+ restore?: (input: {
389
+ collection: string;
390
+ id: number | string;
391
+ locale?: string;
392
+ organizationId: string;
393
+ signal?: AbortSignal;
394
+ user: PayloadOpaqueValue;
395
+ }) => Promise<NativeRecord>;
396
+ }>;
397
+ export type PayloadSourceOptions<Entity = NativeRecord> = DataSourceBaseOptions<Entity> & Readonly<{
398
+ collection: string;
399
+ includeDrafts?: boolean;
400
+ incrementalChanges?: Readonly<{
401
+ overlapMs?: number;
402
+ }>;
403
+ local: PayloadLocalApi;
404
+ locale?: string;
405
+ localeField?: string;
406
+ nativeRequest?: (context: Parameters<DataSourceAdapter["execute"]>[1]) => PayloadOpaqueValue;
407
+ plugin?: PayloadGatewayHooks;
408
+ user: (context: Parameters<DataSourceAdapter["execute"]>[1]) => PayloadOpaqueValue;
409
+ }>;
410
+ export type PayloadGlobalSourceOptions<Entity = NativeRecord> = DataSourceBaseOptions<Entity> & Readonly<{
411
+ global: string;
412
+ includeDrafts?: boolean;
413
+ local: PayloadLocalApi & Required<Pick<PayloadLocalApi, "findGlobal" | "updateGlobal">>;
414
+ locale?: string;
415
+ nativeRequest?: (context: Parameters<DataSourceAdapter["execute"]>[1]) => PayloadOpaqueValue;
416
+ user: (context: Parameters<DataSourceAdapter["execute"]>[1]) => PayloadOpaqueValue;
417
+ }>;
418
+ export declare const definePayloadGatewayPlugin: (hooks: PayloadGatewayHooks) => PayloadGatewayHooks, definePayloadGlobalSource: <Entity = Readonly<Record<string, ResourceJsonValue>>>(options: PayloadGlobalSourceOptions<Entity>) => DataSourceAdapter<Entity>, definePayloadSource: <Entity = Readonly<Record<string, ResourceJsonValue>>>(options: PayloadSourceOptions<Entity>) => DataSourceAdapter<Entity>;
419
+
420
+ export {};
@@ -0,0 +1 @@
1
+ var __defProp=Object.defineProperty;var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var exports_payload={};__export(exports_payload,{definePayloadSource:()=>definePayloadSource,definePayloadGlobalSource:()=>definePayloadGlobalSource,definePayloadGatewayPlugin:()=>definePayloadGatewayPlugin});var resourceCapabilityByOperation={create:"create",get:"get",hard_delete:"hardDelete",list:"search",restore:"restore",soft_delete:"softDelete",update:"update"};class DataSourceMappingError extends TypeError{code;constructor(code,message){super(message);this.name="DataSourceMappingError";this.code=code}}var isJsonValue=(value)=>{if(value===null||typeof value==="boolean"||typeof value==="number"||typeof value==="string"){return true}if(Array.isArray(value)){return value.every(isJsonValue)}if(typeof value!=="object"||value===null){return false}const prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null){return false}return Object.values(value).every(isJsonValue)};var parseJsonValue=(value)=>{if(!isJsonValue(value)){throw new DataSourceMappingError("unsupported_mapping","Value must be JSON-compatible")}return value};var encode=(prefix,value)=>`${prefix}.${Buffer.from(JSON.stringify(value)).toString("base64url")}`;var decode=(prefix,value)=>{if(!value.startsWith(`${prefix}.`)){throw new DataSourceMappingError("invalid_identity",`Expected an opaque ${prefix} identifier`)}try{const parsed=JSON.parse(Buffer.from(value.slice(prefix.length+1),"base64url").toString("utf-8"));if(!isJsonValue(parsed)){throw new DataSourceMappingError("invalid_identity",`Invalid opaque ${prefix} identifier`)}return parsed}catch{throw new DataSourceMappingError("invalid_identity",`Invalid opaque ${prefix} identifier`)}};var opaqueIdentity=(kind,fields,record)=>{const values=fields.map((field)=>{const value=record[field];if(typeof value!=="string"&&typeof value!=="number"){throw new DataSourceMappingError("invalid_identity",`Identity field ${field} must be a string or number`)}return value});return encode(`${kind}:id`,values)};var decodeIdentity=(kind,fields,id)=>{const values=decode(`${kind}:id`,id);if(!Array.isArray(values)||values.length!==fields.length){throw new DataSourceMappingError("invalid_identity","Opaque identifier does not match the configured identity")}return Object.fromEntries(fields.map((field,index)=>[field,values[index]]))};var opaqueRevision=(kind,revision)=>encode(`${kind}:rev`,revision);var nativeIdentifier=(value)=>{if(typeof value!=="string"&&typeof value!=="number"){throw new DataSourceMappingError("invalid_identity","Identity value must be a string or number")}return value};var optionalNativeString=(value)=>typeof value==="string"?value:undefined;var cursor=(kind,value)=>encode(`${kind}:cursor`,value);var decodeCursor=(kind,value)=>decode(`${kind}:cursor`,value);var projectedRelation=(kind,relation,value)=>{const normalize=(record)=>{if(typeof record!=="object"||record===null){throw new DataSourceMappingError("unsupported_mapping",`Relation ${relation.field} requires an object identity`)}const nativeRecord=Object.fromEntries(Object.entries(record));return opaqueIdentity(`${kind}:${relation.targetResourceId}`,relation.targetIdentityFields,nativeRecord)};if(relation.cardinality==="many"){if(!Array.isArray(value)){throw new DataSourceMappingError("unsupported_mapping",`Relation ${relation.field} requires an array`)}return value.map(normalize)}return value===null||value===undefined?null:normalize(value)};var project=(kind,projection,row)=>{const redacted=new Set(projection.redact);const relations=new Map((projection.relations??[]).map((relation)=>[relation.field,relation]));const entries=[];for(const field of projection.fields){if(redacted.has(field)){continue}const value=row[field];const relation=relations.get(field);if(relation!==undefined){entries.push([field,projectedRelation(kind,relation,value)]);continue}if(value===undefined){continue}if(!isJsonValue(value)){throw new DataSourceMappingError("unsupported_mapping",`Field ${field} is not JSON-compatible`)}entries.push([field,value])}return Object.fromEntries(entries)};var record=(kind,options,row)=>{const deletedAt=options.softDelete?.deletedAt(row);const result={id:opaqueIdentity(kind,options.identity.fields,row),revision:opaqueRevision(kind,options.revision(row)),value:project(kind,options.projection,row)};if(deletedAt!==undefined){result.deletedAt=deletedAt}return result};var success=(correlationId,value)=>({correlationId,ok:true,value});var failure=(correlationId,error)=>({correlationId,error,ok:false});var nativeFilterOperator=(operator)=>operator.replaceAll(/_(?<letter>[a-z])/gu,(_match,letter)=>letter.toUpperCase());var unsupportedOperation=(correlationId,capabilities,operation)=>{const capability=resourceCapabilityByOperation[operation];if(capabilities[capability]===true){return}return failure(correlationId,{code:"capability_not_supported",details:{capability},message:`The data source does not support ${capability}`,retryable:false})};var conflict=(correlationId)=>failure(correlationId,{code:"conflict",message:"The expected revision does not match the current record",retryable:false});var invalid=(correlationId,cause)=>failure(correlationId,{code:"invalid_request",details:{cause:cause instanceof Error?cause.message:String(cause)},message:"The data-source request is invalid",retryable:false});var nativeFailure=(correlationId,cause)=>failure(correlationId,{code:"internal",details:{cause:cause instanceof Error?cause.message:String(cause)},message:"The native data source failed",retryable:false});var assertConfiguration=(options)=>{const fields=[...options.projection.fields,...options.projection.redact??[]];if(new Set(fields).size!==fields.length){throw new DataSourceMappingError("duplicate_field","Exposed and redacted fields must be disjoint and unique")}const maxPageSize=options.maxPageSize??100;if(!Number.isSafeInteger(maxPageSize)||maxPageSize<1){throw new DataSourceMappingError("invalid_pagination","maxPageSize must be a positive safe integer")}if(options.capabilities.pagination.length===0){throw new DataSourceMappingError("invalid_pagination","At least one pagination mode must be declared")}const declaredPagination=new Set(options.definition.query.pagination.modes);if(declaredPagination.size!==options.capabilities.pagination.length||options.capabilities.pagination.some((mode)=>!declaredPagination.has(mode))){throw new DataSourceMappingError("capability_mismatch","Data-source pagination must match the resource definition")}if(options.capabilities.relations!==(options.projection.relations?.length??0)>0){throw new DataSourceMappingError("capability_mismatch","Relation capability must match the explicit relation projection")}for(const capability of["create","hardDelete","restore","softDelete","update"]){if(options.capabilities[capability]!==(options.definition.capabilities[capability]===true)){throw new DataSourceMappingError("capability_mismatch",`${capability} capability must match the resource definition`)}}};var boundedLimit=(requested,maximum=100)=>{if(!Number.isSafeInteger(requested)||requested<1){throw new DataSourceMappingError("invalid_pagination","Page size must be a positive safe integer")}return Math.min(requested,maximum)};var expectedRevisionMatches=(kind,options,row,expectedRevision)=>opaqueRevision(kind,options.revision(row))===expectedRevision;var kind="payload";var optionalProperty=(key,value)=>value===undefined?{}:{[key]:value};var payloadWhere=(filter)=>{if(filter===undefined){return}if("filters"in filter){const filters=filter.filters.map(payloadWhere).filter((where)=>where!==undefined);return{[filter.operator]:filters}}if("filter"in filter){const nested=payloadWhere(filter.filter);return nested===undefined?undefined:{not:nested}}if(filter.operator==="is_null"){return{[filter.field]:{exists:false}}}if(filter.operator==="is_not_null"){return{[filter.field]:{exists:true}}}if(!("value"in filter)){return}const{operator:filterOperator,value:filterValue}=filter;const operator=nativeFilterOperator(filterOperator);let patternValue;if(filterOperator==="starts_with"||filterOperator==="ends_with"){try{patternValue=String(nativeIdentifier(filterValue))}catch{throw new TypeError(`${filterOperator} requires a string or number`)}}if((filterOperator==="starts_with"||filterOperator==="ends_with")&&patternValue===undefined){throw new TypeError(`${filterOperator} requires a string or number`)}let value;if(filterOperator==="starts_with"){value=`${patternValue}%`}else if(filterOperator==="ends_with"){value=`%${patternValue}`}else{value=filterValue}return{[filter.field]:{[operator]:value}}};var nativeId=(options,identity)=>{const[firstField]=options.identity.fields;return nativeIdentifier(identity[firstField])};var localeFor=(options,identity)=>{if(options.localeField!==undefined&&identity!==undefined){const value=identity[options.localeField];const localeValue=optionalNativeString(value);if(localeValue!==undefined){return localeValue}}return options.locale};var validatePayload=(options)=>{if(!options.capabilities.nativePolicy){throw new TypeError("Payload must declare nativePolicy support")}if(options.capabilities.transactions||options.capabilities.softDelete!==(options.softDelete!==undefined)){throw new TypeError("Payload transaction and soft-delete capabilities require explicit policy")}if(options.capabilities.hardDelete!==(options.plugin?.hardDelete!==undefined)||options.capabilities.restore!==(options.plugin?.restore!==undefined)||options.capabilities.incrementalChanges!==(options.plugin?.changes!==undefined)){throw new TypeError("Payload capabilities must match installed plugin hooks")}if(options.capabilities.softDelete!==(options.definition.capabilities.softDelete===true)){throw new TypeError("Payload soft-delete capability must match its resource definition")}};var definePayloadSource=(options)=>{assertConfiguration(options);validatePayload(options);const maximum=options.maxPageSize??100;const executeList=async(request,callContext,draft)=>{const{pagination}=request.query;let page=1;if(pagination.mode==="page"){const{page:requestedPage}=pagination;page=requestedPage}else if(pagination.cursor!==undefined){page=decodeCursor(kind,pagination.cursor)}const pageSize=boundedLimit(pagination.mode==="page"?pagination.pageSize:pagination.limit,maximum);const result=await options.local.find({...callContext,collection:options.collection,draft,limit:pageSize,...optionalProperty("locale",options.locale),page,...optionalProperty("sort",request.query.sort?.map((sort)=>sort.direction==="desc"?`-${sort.field}`:sort.field)),...optionalProperty("where",payloadWhere(request.query.filter))});const items=result.docs.map((row)=>record(kind,options,row));if(pagination.mode==="page"){return success(request.requestId,{items,page,pageSize,pagination:"page",totalItems:result.totalDocs,totalPages:result.totalPages})}return success(request.requestId,{items,...optionalProperty("nextCursor",page>=result.totalPages?undefined:cursor(kind,page+1)),pagination:"cursor"})};const executeCreate=async(request,callContext,draft)=>{const row=await options.local.create({...callContext,collection:options.collection,data:parseJsonValue(request.value),draft,...optionalProperty("locale",options.locale)});return success(request.requestId,record(kind,options,row))};const execute=async(request,context,requestOptions)=>{const unsupported=unsupportedOperation(request.requestId,options.definition.capabilities,request.operation);if(unsupported!==undefined){return unsupported}const user=options.user(context);const callContext={overrideAccess:false,...optionalProperty("req",options.nativeRequest?.(context)),user};const draft=options.includeDrafts===true;try{if(request.operation==="list"){return await executeList(request,callContext,draft)}if(request.operation==="create"){return await executeCreate(request,callContext,draft)}const identity=decodeIdentity(kind,options.identity.fields,request.id);const id=nativeId(options,identity);const locale=localeFor(options,identity);const current=await options.local.findByID({...callContext,collection:options.collection,draft,id,...optionalProperty("locale",locale)});if(current===null){return{correlationId:request.requestId,error:{code:"not_found",message:"The Payload document was not found",retryable:false},ok:false}}if(request.operation==="get"){return success(request.requestId,record(kind,options,current))}if(!expectedRevisionMatches(kind,options,current,request.expectedRevision)){return conflict(request.requestId)}if(request.operation==="update"){const row2=await options.local.update({...callContext,collection:options.collection,data:parseJsonValue(request.value),draft,id,...optionalProperty("locale",locale)});return success(request.requestId,record(kind,options,row2))}if(request.operation==="hard_delete"){await options.plugin?.hardDelete?.({collection:options.collection,id,...optionalProperty("locale",locale),organizationId:context.organizationId,...optionalProperty("signal",requestOptions?.signal),user});return success(request.requestId,null)}if(request.operation==="restore"){const row2=await options.plugin?.restore?.({collection:options.collection,id,...optionalProperty("locale",locale),organizationId:context.organizationId,...optionalProperty("signal",requestOptions?.signal),user});if(row2===undefined){throw new TypeError("Restore is not supported")}return success(request.requestId,record(kind,options,row2))}const row=await options.local.delete({...callContext,collection:options.collection,id,...optionalProperty("locale",locale)});return success(request.requestId,record(kind,options,row))}catch(error){return error instanceof TypeError?invalid(request.requestId,error):nativeFailure(request.requestId,error)}};const changes=options.plugin?.changes===undefined?undefined:async(request,context,requestOptions)=>{try{const after=request.cursor===undefined?undefined:decodeCursor(`${kind}:changes`,request.cursor);const user=options.user(context);const page=await options.plugin?.changes?.({...optionalProperty("after",after),collection:options.collection,limit:boundedLimit(request.limit,maximum),...optionalProperty("locale",options.locale),organizationId:context.organizationId,overlapMs:options.incrementalChanges?.overlapMs??5000,...optionalProperty("signal",requestOptions?.signal),user});if(page===undefined){throw new TypeError("Changes are unavailable")}const projectedChanges=page.changes.map((change)=>change.kind==="upsert"?{kind:"upsert",record:record(kind,options,change.row)}:{deletedAt:change.deletedAt,id:opaqueIdentity(kind,options.identity.fields,change.identity),kind:"tombstone",revision:opaqueRevision(kind,change.revision)});const final=page.changes.at(-1);const nextCursor=final===undefined?undefined:cursor(`${kind}:changes`,{externalId:final.kind==="upsert"?opaqueIdentity(kind,options.identity.fields,final.row):opaqueIdentity(kind,options.identity.fields,final.identity),updatedAt:final.kind==="upsert"?options.updatedAt(final.row):final.updatedAt});return success(request.requestId,{changes:projectedChanges,...optionalProperty("nextCursor",nextCursor)})}catch(error){return invalid(request.requestId,error)}};const source={authorization:options.authorization,...optionalProperty("changes",changes),dataSource:{capabilities:options.capabilities,kind},definition:options.definition,execute};return Object.freeze(source)};var definePayloadGlobalSource=(options)=>{assertConfiguration(options);if(!options.capabilities.nativePolicy){throw new TypeError("Payload must declare nativePolicy support")}if(options.capabilities.create||options.capabilities.hardDelete||options.capabilities.incrementalChanges||options.capabilities.restore||options.capabilities.softDelete||options.capabilities.transactions){throw new TypeError("Payload globals only support read and update")}const load=async(context)=>await options.local.findGlobal({draft:options.includeDrafts===true,...optionalProperty("locale",options.locale),overrideAccess:false,...optionalProperty("req",options.nativeRequest?.(context)),slug:options.global,user:options.user(context)});const execute=async(request,context)=>{const unsupported=unsupportedOperation(request.requestId,options.definition.capabilities,request.operation);if(unsupported!==undefined){return unsupported}try{const current=await load(context);if(request.operation==="list"){return success(request.requestId,{items:[record(kind,options,current)],...request.query.pagination.mode==="page"?{page:request.query.pagination.page,pageSize:request.query.pagination.pageSize,pagination:"page",totalItems:1,totalPages:1}:{pagination:"cursor"}})}const currentRecord=record(kind,options,current);if(request.operation==="get"){if(request.id!==currentRecord.id){return{correlationId:request.requestId,error:{code:"not_found",message:"The Payload global was not found",retryable:false},ok:false}}return success(request.requestId,currentRecord)}if(request.operation!=="update"){return invalid(request.requestId,new TypeError("Unsupported Payload global operation"))}if(!expectedRevisionMatches(kind,options,current,request.expectedRevision)){return conflict(request.requestId)}const updated=await options.local.updateGlobal({data:parseJsonValue(request.value),draft:options.includeDrafts===true,...optionalProperty("locale",options.locale),overrideAccess:false,...optionalProperty("req",options.nativeRequest?.(context)),slug:options.global,user:options.user(context)});return success(request.requestId,record(kind,options,updated))}catch(error){return error instanceof TypeError?invalid(request.requestId,error):nativeFailure(request.requestId,error)}};return Object.freeze({authorization:options.authorization,dataSource:{capabilities:options.capabilities,kind},definition:options.definition,execute})};var definePayloadGatewayPlugin=(hooks)=>Object.freeze(hooks);var{definePayloadGatewayPlugin:definePayloadGatewayPlugin2,definePayloadGlobalSource:definePayloadGlobalSource2,definePayloadSource:definePayloadSource2}=exports_payload;export{definePayloadSource2 as definePayloadSource,definePayloadGlobalSource2 as definePayloadGlobalSource,definePayloadGatewayPlugin2 as definePayloadGatewayPlugin};