@collective-intelligence/external-apps-server-sdk 0.2.6 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin.d.ts +30 -22
- package/dist/admin.js +2 -2
- package/dist/auth/federated.d.ts +9 -13
- package/dist/auth/federated.js +2 -2
- package/dist/auth.d.ts +52 -45
- package/dist/auth.js +1 -1
- package/dist/chunks/{index-rejqkp84.js → index-nm2bnv88.js} +5 -5
- package/dist/effect.d.ts +5 -5
- package/dist/effect.js +1 -1
- package/dist/express.d.ts +3 -1
- package/dist/express.js +1 -1
- package/dist/gateway.d.ts +7 -3
- package/dist/gateway.js +2 -2
- package/dist/index.d.ts +92 -64
- package/dist/index.js +1 -1
- package/dist/knowledge-sources/payload.d.ts +3 -1
- package/dist/knowledge-sources/payload.js +1 -1
- package/dist/knowledge-sources/strapi.d.ts +2 -1
- package/dist/knowledge-sources/strapi.js +1 -1
- package/dist/next.d.ts +75 -13
- package/dist/next.js +1 -1
- package/dist/runtime/express.d.ts +3 -1
- package/dist/runtime/express.js +1 -1
- package/dist/runtime/nestjs.d.ts +11 -5
- package/dist/runtime/nestjs.js +1 -1
- package/dist/runtime/web.d.ts +24 -4
- package/dist/runtime/web.js +1 -1
- package/dist/tools/ai-sdk.d.ts +1 -0
- package/dist/tools/ai-sdk.js +2 -2
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,60 @@ import * as Option$1 from 'effect/Option';
|
|
|
10
10
|
import * as Redacted from 'effect/Redacted';
|
|
11
11
|
import * as Schema from 'effect/Schema';
|
|
12
12
|
|
|
13
|
+
declare const ServerAccessError_base: Schema.Class<ServerAccessError, Schema.TaggedStruct<"ServerAccessError", {
|
|
14
|
+
readonly body: Schema.StructWithRest<Schema.Struct<{
|
|
15
|
+
readonly _tag: Schema.String;
|
|
16
|
+
}>, readonly [
|
|
17
|
+
Schema.$Record<Schema.String, Schema.Unknown>
|
|
18
|
+
]>;
|
|
19
|
+
readonly status: Schema.Int;
|
|
20
|
+
}>, import("effect/Cause").YieldableError>;
|
|
21
|
+
declare class ServerAccessError extends ServerAccessError_base {
|
|
22
|
+
get message(): string;
|
|
23
|
+
}
|
|
24
|
+
declare const oauthErrorCodes: readonly [
|
|
25
|
+
"invalid_client",
|
|
26
|
+
"invalid_grant",
|
|
27
|
+
"invalid_request",
|
|
28
|
+
"invalid_target",
|
|
29
|
+
"temporarily_unavailable",
|
|
30
|
+
"unauthorized_client",
|
|
31
|
+
"unsupported_grant_type"
|
|
32
|
+
];
|
|
33
|
+
/**
|
|
34
|
+
* `invalid_grant` means the member's CI session ended or the member cannot act
|
|
35
|
+
* in the Organization: sign the member in again. `invalid_response` means CI
|
|
36
|
+
* answered with neither a token nor an OAuth error. Other codes are CI's OAuth
|
|
37
|
+
* errors and point at the application's configuration or CI availability.
|
|
38
|
+
*/
|
|
39
|
+
export type MemberSessionExchangeErrorCode = (typeof oauthErrorCodes)[number] | "invalid_response";
|
|
40
|
+
declare const MemberSessionExchangeError_base: Schema.Class<MemberSessionExchangeError, Schema.TaggedStruct<"MemberSessionExchangeError", {
|
|
41
|
+
readonly cause: Schema.optional<Schema.Defect>;
|
|
42
|
+
readonly code: Schema.Literals<readonly [
|
|
43
|
+
"invalid_client",
|
|
44
|
+
"invalid_grant",
|
|
45
|
+
"invalid_request",
|
|
46
|
+
"invalid_target",
|
|
47
|
+
"temporarily_unavailable",
|
|
48
|
+
"unauthorized_client",
|
|
49
|
+
"unsupported_grant_type",
|
|
50
|
+
"invalid_response"
|
|
51
|
+
]>;
|
|
52
|
+
/** The HTTP status CI answered with; absent when CI was unreachable. */
|
|
53
|
+
readonly status: Schema.UndefinedOr<Schema.Int>;
|
|
54
|
+
}>, import("effect/Cause").YieldableError>;
|
|
55
|
+
/** CI refused the member session exchange, or did not answer it. */
|
|
56
|
+
export declare class MemberSessionExchangeError extends MemberSessionExchangeError_base {
|
|
57
|
+
/** The positional form of `.`: CI's code, its HTTP status and the cause. */
|
|
58
|
+
constructor(code: MemberSessionExchangeErrorCode, status: number | undefined, options?: ErrorOptions);
|
|
59
|
+
/** The Schema form; Schema decoding gives the fields and the options. */
|
|
60
|
+
constructor(fields: Readonly<{
|
|
61
|
+
cause?: unknown;
|
|
62
|
+
code: MemberSessionExchangeErrorCode;
|
|
63
|
+
status: number | undefined;
|
|
64
|
+
}>, options: Schema.MakeOptions | undefined);
|
|
65
|
+
get message(): string;
|
|
66
|
+
}
|
|
13
67
|
export type AccessExplanation = {
|
|
14
68
|
cut: {
|
|
15
69
|
credential: {
|
|
@@ -1745,59 +1799,6 @@ declare const createApplicationAccessApi: (client: Client$1) => {
|
|
|
1745
1799
|
snapshot: (options: EndpointOptions<Options$1<ApplicationAccessPrincipalsSnapshotData, false, unknown>>) => Promise<AccessSnapshot>;
|
|
1746
1800
|
};
|
|
1747
1801
|
export type ApplicationAccessApi = ReturnType<typeof createApplicationAccessApi>;
|
|
1748
|
-
declare const ServerAccessError_base: Schema.Class<ServerAccessError, Schema.TaggedStruct<"ServerAccessError", {
|
|
1749
|
-
readonly body: Schema.StructWithRest<Schema.Struct<{
|
|
1750
|
-
readonly _tag: Schema.String;
|
|
1751
|
-
}>, readonly [
|
|
1752
|
-
Schema.$Record<Schema.String, Schema.Unknown>
|
|
1753
|
-
]>;
|
|
1754
|
-
readonly status: Schema.Int;
|
|
1755
|
-
}>, import("effect/Cause").YieldableError>;
|
|
1756
|
-
declare class ServerAccessError extends ServerAccessError_base {
|
|
1757
|
-
get message(): string;
|
|
1758
|
-
}
|
|
1759
|
-
declare const oauthErrorCodes: readonly [
|
|
1760
|
-
"invalid_client",
|
|
1761
|
-
"invalid_grant",
|
|
1762
|
-
"invalid_request",
|
|
1763
|
-
"invalid_target",
|
|
1764
|
-
"temporarily_unavailable",
|
|
1765
|
-
"unauthorized_client",
|
|
1766
|
-
"unsupported_grant_type"
|
|
1767
|
-
];
|
|
1768
|
-
/**
|
|
1769
|
-
* `invalid_grant` means the member's CI session ended or the member cannot act
|
|
1770
|
-
* in the Organization: sign the member in again. `invalid_response` means CI
|
|
1771
|
-
* answered with neither a token nor an OAuth error. Other codes are CI's OAuth
|
|
1772
|
-
* errors and point at the application's configuration or CI availability.
|
|
1773
|
-
*/
|
|
1774
|
-
export type MemberSessionExchangeErrorCode = (typeof oauthErrorCodes)[number] | "invalid_response";
|
|
1775
|
-
declare const MemberSessionExchangeError_base: Schema.Class<MemberSessionExchangeError, Schema.TaggedStruct<"MemberSessionExchangeError", {
|
|
1776
|
-
readonly cause: Schema.optional<Schema.Defect>;
|
|
1777
|
-
readonly code: Schema.Literals<readonly [
|
|
1778
|
-
"invalid_client",
|
|
1779
|
-
"invalid_grant",
|
|
1780
|
-
"invalid_request",
|
|
1781
|
-
"invalid_target",
|
|
1782
|
-
"temporarily_unavailable",
|
|
1783
|
-
"unauthorized_client",
|
|
1784
|
-
"unsupported_grant_type",
|
|
1785
|
-
"invalid_response"
|
|
1786
|
-
]>;
|
|
1787
|
-
/** The HTTP status CI answered with; absent when CI was unreachable. */
|
|
1788
|
-
readonly status: Schema.UndefinedOr<Schema.Int>;
|
|
1789
|
-
}>, import("effect/Cause").YieldableError>;
|
|
1790
|
-
declare class MemberSessionExchangeError extends MemberSessionExchangeError_base {
|
|
1791
|
-
/** The positional form of `.`: CI's code, its HTTP status and the cause. */
|
|
1792
|
-
constructor(code: MemberSessionExchangeErrorCode, status: number | undefined, options?: ErrorOptions);
|
|
1793
|
-
/** The Schema form; Schema decoding gives the fields and the options. */
|
|
1794
|
-
constructor(fields: Readonly<{
|
|
1795
|
-
cause?: unknown;
|
|
1796
|
-
code: MemberSessionExchangeErrorCode;
|
|
1797
|
-
status: number | undefined;
|
|
1798
|
-
}>, options: Schema.MakeOptions | undefined);
|
|
1799
|
-
get message(): string;
|
|
1800
|
-
}
|
|
1801
1802
|
/** The Organization a `ci.access` call acts in. */
|
|
1802
1803
|
export type ServerAccessContext = Readonly<{
|
|
1803
1804
|
organizationId: string;
|
|
@@ -2113,6 +2114,7 @@ export type ServerRecordSearchResult = Readonly<{
|
|
|
2113
2114
|
result: ServerRecordPage;
|
|
2114
2115
|
}>;
|
|
2115
2116
|
}>;
|
|
2117
|
+
export declare const serverSdkRuntime: "node";
|
|
2116
2118
|
export type ServerOperationMethod<Id extends ExternalApplicationServerOperationId> = (request: ServerOperationRequest<Id>) => Promise<ExternalApplicationOperationResult<Id>>;
|
|
2117
2119
|
export type ServerMessageSendMethod = (request: ServerMessageSendRequest) => Promise<MessageSendResult>;
|
|
2118
2120
|
export type ServerResourceUploadMethod = (request: ServerResourceUploadRequest) => Promise<ServerResourceUploadResult>;
|
|
@@ -2301,12 +2303,31 @@ export interface ServerClient<Mode extends ServerAuthenticationMode = ServerAuth
|
|
|
2301
2303
|
list: ServerOperationMethod<"workflows_list">;
|
|
2302
2304
|
}>;
|
|
2303
2305
|
}
|
|
2304
|
-
|
|
2306
|
+
/**
|
|
2307
|
+
* Creates an isolated confidential client for one CI tenant. A bad
|
|
2308
|
+
* `tenantUrl` throws `TypeError`. A CI error envelope resolves as a value; a
|
|
2309
|
+
* request that does not reach CI, or an answer that is not readable, rejects
|
|
2310
|
+
* with `CiTransportError`; an abort rejects with `signal.reason`.
|
|
2311
|
+
* `close` disposes the runtime of the client; a call that still runs is
|
|
2312
|
+
* interrupted. A config whose `authentication` type is the service mode
|
|
2313
|
+
* gives `ServerClient<"service">`, the client that reads with the app's own
|
|
2314
|
+
* credential (INV-004, Q91).
|
|
2315
|
+
*/
|
|
2316
|
+
export declare function createServerClient(config: ServerClientConfig & ServerClientInvalidation & Readonly<{
|
|
2305
2317
|
authentication: ServiceServerAuthentication;
|
|
2306
2318
|
}>): ServerClient<"service"> & Readonly<{
|
|
2307
2319
|
close: () => Promise<void>;
|
|
2308
2320
|
}>;
|
|
2309
|
-
|
|
2321
|
+
/**
|
|
2322
|
+
* Creates an isolated confidential client for one CI tenant. A bad
|
|
2323
|
+
* `tenantUrl` throws `TypeError`. A CI error envelope resolves as a value; a
|
|
2324
|
+
* request that does not reach CI, or an answer that is not readable, rejects
|
|
2325
|
+
* with `CiTransportError`; an abort rejects with `signal.reason`.
|
|
2326
|
+
* `close` disposes the runtime of the client; a call that still runs is
|
|
2327
|
+
* interrupted. The type does not know the mode of this client, so
|
|
2328
|
+
* `cacheCiRead` does not take it.
|
|
2329
|
+
*/
|
|
2330
|
+
export declare function createServerClient(config: ServerClientConfig & ServerClientInvalidation): ServerClient & Readonly<{
|
|
2310
2331
|
close: () => Promise<void>;
|
|
2311
2332
|
}>;
|
|
2312
2333
|
export interface MemberSessionExchangeRequest {
|
|
@@ -2327,6 +2348,13 @@ export interface MemberAccessToken {
|
|
|
2327
2348
|
/** When to exchange again: before CI's expiry, which is counted from signing. */
|
|
2328
2349
|
readonly expiresAt: Date;
|
|
2329
2350
|
}
|
|
2351
|
+
/**
|
|
2352
|
+
* Exchanges a member's CI session for a short-lived access token that calls CI
|
|
2353
|
+
* as that member through this confidential application. In the given
|
|
2354
|
+
* Organization its calls are cut to the app's Max Privileges; it ends with the
|
|
2355
|
+
* CI session and is never refreshed: exchange again when it expires.
|
|
2356
|
+
*/
|
|
2357
|
+
export declare const exchangeMemberSession: (request: MemberSessionExchangeRequest) => Promise<MemberAccessToken>;
|
|
2330
2358
|
/** `Secret` is a string at `.`; the `./effect` layers also take a `Redacted` one. */
|
|
2331
2359
|
export type RunAsApplicationConfig<Secret extends ClientSecret = string> = Readonly<{
|
|
2332
2360
|
auditSubject: ExternalApplicationExternalAuditSubject;
|
|
@@ -2338,6 +2366,15 @@ export type RunAsApplicationConfig<Secret extends ClientSecret = string> = Reado
|
|
|
2338
2366
|
sleep?: (milliseconds: number) => Promise<void>;
|
|
2339
2367
|
tenantUrl: string;
|
|
2340
2368
|
}>;
|
|
2369
|
+
/**
|
|
2370
|
+
* Confidential Application identity. Requires an Audit subject and client
|
|
2371
|
+
* secret at construction. `invalidate` is that of `createServerClient`.
|
|
2372
|
+
*/
|
|
2373
|
+
export declare const runAsApplication: (config: RunAsApplicationConfig & ServerClientInvalidation) => ServerClient & Readonly<{
|
|
2374
|
+
close: () => Promise<void>;
|
|
2375
|
+
}>;
|
|
2376
|
+
/** Generates an RFC 9562 UUIDv7 with a millisecond Unix timestamp. */
|
|
2377
|
+
export declare const uuidV7: () => string;
|
|
2341
2378
|
declare const CiError$1: typeof CiError;
|
|
2342
2379
|
type CiError$1 = CiError;
|
|
2343
2380
|
declare const ServerAccessError$1: typeof ServerAccessError;
|
|
@@ -2346,13 +2383,6 @@ declare const CiTransportError$1: typeof CiTransportError;
|
|
|
2346
2383
|
type CiTransportError$1 = CiTransportError;
|
|
2347
2384
|
declare const FederatedAuthError$1: typeof FederatedAuthError;
|
|
2348
2385
|
type FederatedAuthError$1 = FederatedAuthError;
|
|
2349
|
-
declare const createServerClient$1: typeof createServerClient;
|
|
2350
|
-
export declare const serverSdkRuntime: "node";
|
|
2351
|
-
export declare const runAsApplication: (config: RunAsApplicationConfig & ServerClientInvalidation) => ServerClient & Readonly<{
|
|
2352
|
-
close: () => Promise<void>;
|
|
2353
|
-
}>;
|
|
2354
|
-
export declare const exchangeMemberSession: (request: MemberSessionExchangeRequest) => Promise<MemberAccessToken>, MemberSessionExchangeError$1: typeof MemberSessionExchangeError;
|
|
2355
|
-
export declare const uuidV7: () => string;
|
|
2356
2386
|
|
|
2357
2387
|
export {
|
|
2358
2388
|
CiError$1 as CiError,
|
|
@@ -2361,7 +2391,6 @@ export {
|
|
|
2361
2391
|
EntityUploadInput,
|
|
2362
2392
|
EntityUploadSlot,
|
|
2363
2393
|
FederatedAuthError$1 as FederatedAuthError,
|
|
2364
|
-
MemberSessionExchangeError$1 as MemberSessionExchangeError,
|
|
2365
2394
|
MessageContent as ServerMessageContent,
|
|
2366
2395
|
MessageReceipt as ServerMessageReceipt,
|
|
2367
2396
|
MessageSendErrorCode as ServerMessageSendErrorCode,
|
|
@@ -2371,7 +2400,6 @@ export {
|
|
|
2371
2400
|
ResourceJsonValue,
|
|
2372
2401
|
ServerAccessError$1 as ServerAccessError,
|
|
2373
2402
|
StorageFileId as ServerStorageFileId,
|
|
2374
|
-
createServerClient$1 as createServerClient,
|
|
2375
2403
|
};
|
|
2376
2404
|
|
|
2377
2405
|
export {};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ServerAccessError2,CiError2,CiTransportError2,FederatedAuthError2,
|
|
1
|
+
import{ServerAccessError2,MemberSessionExchangeError2,CiError2,CiTransportError2,FederatedAuthError2,serverSdkRuntime2,createServerClient2,exchangeMemberSession2,runAsApplication2,uuidV72}from"./chunks/index-nm2bnv88.js";var CiError=CiError2;var ServerAccessError=ServerAccessError2;var CiTransportError=CiTransportError2;var FederatedAuthError=FederatedAuthError2;export{CiError,CiTransportError,FederatedAuthError,MemberSessionExchangeError2 as MemberSessionExchangeError,ServerAccessError,createServerClient2 as createServerClient,exchangeMemberSession2 as exchangeMemberSession,runAsApplication2 as runAsApplication,serverSdkRuntime2 as serverSdkRuntime,uuidV72 as uuidV7};
|
|
@@ -258,7 +258,9 @@ export type PayloadGlobalSourceOptions<Entity = NativeRecord> = DataSourceBaseOp
|
|
|
258
258
|
nativeRequest?: (context: Parameters<DataSourceAdapter["execute"]>[1]) => PayloadOpaqueValue;
|
|
259
259
|
user: (context: Parameters<DataSourceAdapter["execute"]>[1]) => PayloadOpaqueValue;
|
|
260
260
|
}>;
|
|
261
|
-
export declare const
|
|
261
|
+
export declare const definePayloadSource: <Entity = NativeRecord>(options: PayloadSourceOptions<Entity>) => DataSourceAdapter<Entity>;
|
|
262
|
+
export declare const definePayloadGlobalSource: <Entity = NativeRecord>(options: PayloadGlobalSourceOptions<Entity>) => DataSourceAdapter<Entity>;
|
|
263
|
+
export declare const definePayloadGatewayPlugin: (hooks: PayloadGatewayHooks) => PayloadGatewayHooks;
|
|
262
264
|
|
|
263
265
|
export {
|
|
264
266
|
IdempotencyKey,
|
|
@@ -1 +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,{definePayloadGatewayPlugin:()=>definePayloadGatewayPlugin,definePayloadGlobalSource:()=>definePayloadGlobalSource,definePayloadSource:()=>definePayloadSource});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 row=await options.local.update({...callContext,collection:options.collection,data:parseJsonValue(request.value),draft,id,...optionalProperty("locale",locale)});return success(request.requestId,record(kind,options,row))}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 row=await options.plugin?.restore?.({collection:options.collection,id,...optionalProperty("locale",locale),organizationId:context.organizationId,...optionalProperty("signal",requestOptions?.signal),user});if(row===undefined){throw new TypeError("Restore is not supported")}return success(request.requestId,record(kind,options,row))}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{definePayloadGatewayPlugin2 as definePayloadGatewayPlugin,definePayloadGlobalSource2 as definePayloadGlobalSource,definePayloadSource2 as definePayloadSource};
|
|
1
|
+
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 row=await options.local.update({...callContext,collection:options.collection,data:parseJsonValue(request.value),draft,id,...optionalProperty("locale",locale)});return success(request.requestId,record(kind,options,row))}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 row=await options.plugin?.restore?.({collection:options.collection,id,...optionalProperty("locale",locale),organizationId:context.organizationId,...optionalProperty("signal",requestOptions?.signal),user});if(row===undefined){throw new TypeError("Restore is not supported")}return success(request.requestId,record(kind,options,row))}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);export{definePayloadGatewayPlugin,definePayloadGlobalSource,definePayloadSource};
|
|
@@ -227,7 +227,8 @@ export type StrapiDataSource<Entity = NativeRecord> = DataSourceAdapter<Entity>
|
|
|
227
227
|
}>) => Promise<Entity>;
|
|
228
228
|
}>;
|
|
229
229
|
}>;
|
|
230
|
-
export declare const
|
|
230
|
+
export declare const defineStrapiSource: <Entity = NativeRecord>(options: StrapiSourceOptions<Entity>) => StrapiDataSource<Entity>;
|
|
231
|
+
export declare const defineStrapiGatewayPlugin: (hooks: StrapiGatewayHooks) => StrapiGatewayHooks;
|
|
231
232
|
|
|
232
233
|
export {
|
|
233
234
|
IdempotencyKey,
|
|
@@ -1 +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_strapi={};__export(exports_strapi,{defineStrapiGatewayPlugin:()=>defineStrapiGatewayPlugin,defineStrapiSource:()=>defineStrapiSource});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 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 nativeFilter=(filter)=>{if("filters"in filter){return{...filter,filters:filter.filters.map(nativeFilter)}}if("filter"in filter){return{...filter,filter:nativeFilter(filter.filter)}}return{...filter,operator:nativeFilterOperator(filter.operator)}};var kind="strapi";var optionalProperty=(key,value)=>value===undefined?{}:{[key]:value};var documentId=(identity)=>{const value=identity.documentId;const documentIdentifier=optionalNativeString(value);if(documentIdentifier===undefined||documentIdentifier.length===0){throw new TypeError("Strapi identity must contain documentId")}return documentIdentifier};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 validateStrapi=(options)=>{if(options.identity.fields[0]!=="documentId"){throw new TypeError("Strapi identity must prefer documentId")}if(!options.capabilities.nativePolicy){throw new TypeError("Strapi must declare nativePolicy support")}if(options.capabilities.transactions||options.capabilities.softDelete!==(options.softDelete!==undefined)){throw new TypeError("Strapi transaction and soft-delete capabilities require explicit policy")}if(options.capabilities.softDelete!==(options.plugin?.softDelete!==undefined)||options.capabilities.restore!==(options.plugin?.restore!==undefined)||options.capabilities.incrementalChanges!==(options.plugin?.changes!==undefined)){throw new TypeError("Strapi capabilities must match installed plugin hooks")}};var defineStrapiSource=(options)=>{assertConfiguration(options);validateStrapi(options);const maximum=options.maxPageSize??100;const documents=options.documents.documents(options.uid);const published=options.includeDrafts===true?"draft":"published";const sanitizedRecord=async(action,context,row)=>record(kind,options,await options.sanitize({action,context,value:row}));const paginationStart=(pagination)=>{if(pagination.mode==="cursor"){return pagination.cursor===undefined?0:decodeCursor(kind,pagination.cursor)}return(pagination.page-1)*pagination.pageSize};const executeList=async(request,context,publishedStatus)=>{await options.authorize({action:"find",context});const{pagination}=request.query;const limit=boundedLimit(pagination.mode==="cursor"?pagination.limit:pagination.pageSize,maximum);const start=paginationStart(pagination);const parameters={...optionalProperty("filters",request.query.filter===undefined?undefined:nativeFilter(request.query.filter)),limit,...optionalProperty("locale",options.locale),start,status:publishedStatus,...optionalProperty("sort",request.query.sort?.map(({direction,field})=>`${field}:${direction}`))};let rows;if(options.contentType==="single"){const single=await documents.findFirst(parameters);rows=single===null?[]:[single]}else{rows=await documents.findMany(parameters)}const items=await Promise.all(rows.map(async(row)=>await sanitizedRecord("find",context,row)));if(pagination.mode==="page"){const totalItems=options.contentType==="single"?items.length:await documents.count(parameters);return success(request.requestId,{items,page:pagination.page,pageSize:pagination.pageSize,pagination:"page",totalItems,totalPages:Math.ceil(totalItems/pagination.pageSize)})}return success(request.requestId,{items,...optionalProperty("nextCursor",items.length<limit?undefined:cursor(kind,start+items.length)),pagination:"cursor"})};const lifecycleMethod=(operation)=>operation==="restore"?options.plugin?.restore:options.plugin?.softDelete;const execute=async(request,context,requestOptions)=>{const unsupported=unsupportedOperation(request.requestId,options.definition.capabilities,request.operation);if(unsupported!==undefined){return unsupported}try{if(request.operation==="list"){return await executeList(request,context,published)}if(request.operation==="create"){await options.authorize({action:"create",context});const row=await documents.create({data:parseJsonValue(request.value),...optionalProperty("locale",options.locale),status:published});return success(request.requestId,await sanitizedRecord("create",context,row))}const identity=decodeIdentity(kind,options.identity.fields,request.id);const id=documentId(identity);const locale=localeFor(options,identity);await options.authorize({action:"find",context});const current=await documents.findOne({documentId:id,...optionalProperty("locale",locale),status:published});if(current===null){return{correlationId:request.requestId,error:{code:"not_found",message:"The Strapi document was not found",retryable:false},ok:false}}if(request.operation==="get"){return success(request.requestId,await sanitizedRecord("find",context,current))}if(!expectedRevisionMatches(kind,options,current,request.expectedRevision)){return conflict(request.requestId)}if(request.operation==="update"){await options.authorize({action:"update",context});const row=await documents.update({data:parseJsonValue(request.value),documentId:id,...optionalProperty("locale",locale),status:published});return success(request.requestId,await sanitizedRecord("update",context,row))}if(request.operation==="hard_delete"){await options.authorize({action:"delete",context});await documents.delete({documentId:id,...optionalProperty("locale",locale)});return success(request.requestId,null)}const action=request.operation==="restore"?"restore":"delete";await options.authorize({action,context});const method=lifecycleMethod(request.operation==="restore"?"restore":"soft_delete");const row=await method?.({documentId:id,...optionalProperty("locale",locale),organizationId:context.organizationId,...optionalProperty("signal",requestOptions?.signal),uid:options.uid});if(row===undefined){throw new TypeError(`${request.operation} is not supported`)}return success(request.requestId,await sanitizedRecord(action,context,row))}catch(error){return error instanceof TypeError?invalid(request.requestId,error):nativeFailure(request.requestId,error)}};const publication=(action)=>{const method=documents[action];return method===undefined?undefined:async(input)=>{await options.authorize({action:"publish",context:input.context});const row=await method({documentId:input.documentId,...optionalProperty("locale",input.locale)});const sanitized=await sanitizedRecord("publish",input.context,row);return sanitized.value}};const changes=options.plugin?.changes===undefined?undefined:async(request,context,requestOptions)=>{try{await options.authorize({action:"find",context});const after=request.cursor===undefined?undefined:decodeCursor(`${kind}:changes`,request.cursor);const page=await options.plugin?.changes?.({...optionalProperty("after",after),limit:boundedLimit(request.limit,maximum),...optionalProperty("locale",options.locale),organizationId:context.organizationId,overlapMs:options.incrementalChanges?.overlapMs??5000,...optionalProperty("signal",requestOptions?.signal),uid:options.uid});if(page===undefined){throw new TypeError("Changes are unavailable")}const projectedChanges=await Promise.all(page.changes.map(async(change)=>change.kind==="upsert"?{kind:"upsert",record:await sanitizedRecord("find",context,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 publish=publication("publish");const unpublish=publication("unpublish");const source={authorization:options.authorization,...optionalProperty("changes",changes),dataSource:{capabilities:options.capabilities,kind},definition:options.definition,execute,publication:{...optionalProperty("publish",publish),...optionalProperty("unpublish",unpublish)}};return Object.freeze(source)};var defineStrapiGatewayPlugin=(hooks)=>Object.freeze(hooks);var{defineStrapiGatewayPlugin:defineStrapiGatewayPlugin2,defineStrapiSource:defineStrapiSource2}=exports_strapi;export{defineStrapiGatewayPlugin2 as defineStrapiGatewayPlugin,defineStrapiSource2 as defineStrapiSource};
|
|
1
|
+
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 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 nativeFilter=(filter)=>{if("filters"in filter){return{...filter,filters:filter.filters.map(nativeFilter)}}if("filter"in filter){return{...filter,filter:nativeFilter(filter.filter)}}return{...filter,operator:nativeFilterOperator(filter.operator)}};var kind="strapi";var optionalProperty=(key,value)=>value===undefined?{}:{[key]:value};var documentId=(identity)=>{const value=identity.documentId;const documentIdentifier=optionalNativeString(value);if(documentIdentifier===undefined||documentIdentifier.length===0){throw new TypeError("Strapi identity must contain documentId")}return documentIdentifier};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 validateStrapi=(options)=>{if(options.identity.fields[0]!=="documentId"){throw new TypeError("Strapi identity must prefer documentId")}if(!options.capabilities.nativePolicy){throw new TypeError("Strapi must declare nativePolicy support")}if(options.capabilities.transactions||options.capabilities.softDelete!==(options.softDelete!==undefined)){throw new TypeError("Strapi transaction and soft-delete capabilities require explicit policy")}if(options.capabilities.softDelete!==(options.plugin?.softDelete!==undefined)||options.capabilities.restore!==(options.plugin?.restore!==undefined)||options.capabilities.incrementalChanges!==(options.plugin?.changes!==undefined)){throw new TypeError("Strapi capabilities must match installed plugin hooks")}};var defineStrapiSource=(options)=>{assertConfiguration(options);validateStrapi(options);const maximum=options.maxPageSize??100;const documents=options.documents.documents(options.uid);const published=options.includeDrafts===true?"draft":"published";const sanitizedRecord=async(action,context,row)=>record(kind,options,await options.sanitize({action,context,value:row}));const paginationStart=(pagination)=>{if(pagination.mode==="cursor"){return pagination.cursor===undefined?0:decodeCursor(kind,pagination.cursor)}return(pagination.page-1)*pagination.pageSize};const executeList=async(request,context,publishedStatus)=>{await options.authorize({action:"find",context});const{pagination}=request.query;const limit=boundedLimit(pagination.mode==="cursor"?pagination.limit:pagination.pageSize,maximum);const start=paginationStart(pagination);const parameters={...optionalProperty("filters",request.query.filter===undefined?undefined:nativeFilter(request.query.filter)),limit,...optionalProperty("locale",options.locale),start,status:publishedStatus,...optionalProperty("sort",request.query.sort?.map(({direction,field})=>`${field}:${direction}`))};let rows;if(options.contentType==="single"){const single=await documents.findFirst(parameters);rows=single===null?[]:[single]}else{rows=await documents.findMany(parameters)}const items=await Promise.all(rows.map(async(row)=>await sanitizedRecord("find",context,row)));if(pagination.mode==="page"){const totalItems=options.contentType==="single"?items.length:await documents.count(parameters);return success(request.requestId,{items,page:pagination.page,pageSize:pagination.pageSize,pagination:"page",totalItems,totalPages:Math.ceil(totalItems/pagination.pageSize)})}return success(request.requestId,{items,...optionalProperty("nextCursor",items.length<limit?undefined:cursor(kind,start+items.length)),pagination:"cursor"})};const lifecycleMethod=(operation)=>operation==="restore"?options.plugin?.restore:options.plugin?.softDelete;const execute=async(request,context,requestOptions)=>{const unsupported=unsupportedOperation(request.requestId,options.definition.capabilities,request.operation);if(unsupported!==undefined){return unsupported}try{if(request.operation==="list"){return await executeList(request,context,published)}if(request.operation==="create"){await options.authorize({action:"create",context});const row=await documents.create({data:parseJsonValue(request.value),...optionalProperty("locale",options.locale),status:published});return success(request.requestId,await sanitizedRecord("create",context,row))}const identity=decodeIdentity(kind,options.identity.fields,request.id);const id=documentId(identity);const locale=localeFor(options,identity);await options.authorize({action:"find",context});const current=await documents.findOne({documentId:id,...optionalProperty("locale",locale),status:published});if(current===null){return{correlationId:request.requestId,error:{code:"not_found",message:"The Strapi document was not found",retryable:false},ok:false}}if(request.operation==="get"){return success(request.requestId,await sanitizedRecord("find",context,current))}if(!expectedRevisionMatches(kind,options,current,request.expectedRevision)){return conflict(request.requestId)}if(request.operation==="update"){await options.authorize({action:"update",context});const row=await documents.update({data:parseJsonValue(request.value),documentId:id,...optionalProperty("locale",locale),status:published});return success(request.requestId,await sanitizedRecord("update",context,row))}if(request.operation==="hard_delete"){await options.authorize({action:"delete",context});await documents.delete({documentId:id,...optionalProperty("locale",locale)});return success(request.requestId,null)}const action=request.operation==="restore"?"restore":"delete";await options.authorize({action,context});const method=lifecycleMethod(request.operation==="restore"?"restore":"soft_delete");const row=await method?.({documentId:id,...optionalProperty("locale",locale),organizationId:context.organizationId,...optionalProperty("signal",requestOptions?.signal),uid:options.uid});if(row===undefined){throw new TypeError(`${request.operation} is not supported`)}return success(request.requestId,await sanitizedRecord(action,context,row))}catch(error){return error instanceof TypeError?invalid(request.requestId,error):nativeFailure(request.requestId,error)}};const publication=(action)=>{const method=documents[action];return method===undefined?undefined:async(input)=>{await options.authorize({action:"publish",context:input.context});const row=await method({documentId:input.documentId,...optionalProperty("locale",input.locale)});const sanitized=await sanitizedRecord("publish",input.context,row);return sanitized.value}};const changes=options.plugin?.changes===undefined?undefined:async(request,context,requestOptions)=>{try{await options.authorize({action:"find",context});const after=request.cursor===undefined?undefined:decodeCursor(`${kind}:changes`,request.cursor);const page=await options.plugin?.changes?.({...optionalProperty("after",after),limit:boundedLimit(request.limit,maximum),...optionalProperty("locale",options.locale),organizationId:context.organizationId,overlapMs:options.incrementalChanges?.overlapMs??5000,...optionalProperty("signal",requestOptions?.signal),uid:options.uid});if(page===undefined){throw new TypeError("Changes are unavailable")}const projectedChanges=await Promise.all(page.changes.map(async(change)=>change.kind==="upsert"?{kind:"upsert",record:await sanitizedRecord("find",context,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 publish=publication("publish");const unpublish=publication("unpublish");const source={authorization:options.authorization,...optionalProperty("changes",changes),dataSource:{capabilities:options.capabilities,kind},definition:options.definition,execute,publication:{...optionalProperty("publish",publish),...optionalProperty("unpublish",unpublish)}};return Object.freeze(source)};var defineStrapiGatewayPlugin=(hooks)=>Object.freeze(hooks);export{defineStrapiGatewayPlugin,defineStrapiSource};
|
package/dist/next.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Generated by dts-bundle-generator v9.5.1
|
|
2
2
|
|
|
3
3
|
import { AccessHeldCapability, AccessRequirement, DatasetDefinition, DatasetProviderCapabilities, DatasetProviderResult, DatasetResultPage, OperationDomainDeclaration, PackageSchemaProjection, PortableOperationDeclaration, QueryInput } from '@collective-intelligence/extensions-sdk';
|
|
4
|
-
import { RealtimeTopicFilter } from '@collective-intelligence/external-apps-client-sdk';
|
|
4
|
+
import { RealtimeTopic, RealtimeTopicFilter } from '@collective-intelligence/external-apps-client-sdk';
|
|
5
5
|
import { EntityOperation, EntityOperationResult, EntityRequest, ResourceDefinition, ResourceResult, ResourceTransportRequest } from '@collective-intelligence/external-apps-client-sdk/resources';
|
|
6
6
|
import * as Brand from 'effect/Brand';
|
|
7
7
|
import * as Context from 'effect/Context';
|
|
@@ -78,6 +78,26 @@ export interface ExternalApplicationExternalAuditSubject {
|
|
|
78
78
|
}
|
|
79
79
|
/** One tag of the SDK cache tag vocabulary. */
|
|
80
80
|
export type CiTag = string & Brand.Brand<"CiTag">;
|
|
81
|
+
export declare const ciTag: {
|
|
82
|
+
/** The tag of every read that `cacheCiRead` tags. */
|
|
83
|
+
all: CiTag;
|
|
84
|
+
/** The tag of one record of the schema `fqn`. */
|
|
85
|
+
entity: (fqn: string, id: string) => CiTag;
|
|
86
|
+
/**
|
|
87
|
+
* The tag of every list of the schema `fqn`, filtered or not. A write
|
|
88
|
+
* changes which records a list holds, so it expires this tag; a get of
|
|
89
|
+
* another record keeps its entry.
|
|
90
|
+
*/
|
|
91
|
+
list: (fqn: string) => CiTag;
|
|
92
|
+
/**
|
|
93
|
+
* The tag of every read of the schema `fqn`: gets and lists. A Realtime
|
|
94
|
+
* reset of a topic without a filter expires it, because the missed changes
|
|
95
|
+
* have no ids.
|
|
96
|
+
*/
|
|
97
|
+
schema: (fqn: string) => CiTag;
|
|
98
|
+
/** The tag of a filtered topic; a topic without a filter has the List Tag. */
|
|
99
|
+
topic: (topic: RealtimeTopic) => CiTag;
|
|
100
|
+
};
|
|
81
101
|
/**
|
|
82
102
|
* The `invalidate` option of a Vanilla Facade: it gets the Entity Tag and the
|
|
83
103
|
* List Tag of each record write that CI confirmed. In Next.js, pass
|
|
@@ -154,11 +174,22 @@ export type CiResourcesOptions = Readonly<{
|
|
|
154
174
|
policy?: UserAuthAccessPolicy;
|
|
155
175
|
tenantUrl: string;
|
|
156
176
|
}>;
|
|
177
|
+
/** One Resource proxy mount per CI entity contract, authorized from the current user session. */
|
|
178
|
+
export declare const createCiResourceMounts: ({ auth, bindings, policy, ...ci }: CiResourcesOptions) => {
|
|
179
|
+
basePath: string;
|
|
180
|
+
handler: (request: Request) => Promise<Response>;
|
|
181
|
+
}[];
|
|
157
182
|
export type RealtimeRevalidateOptions = Readonly<{
|
|
158
183
|
auth: Pick<ApplicationUserAuth, "getSession">;
|
|
159
184
|
/** The `secrets` of the ticket route, the current one first. */
|
|
160
185
|
secrets: readonly string[];
|
|
161
186
|
}>;
|
|
187
|
+
/**
|
|
188
|
+
* The Revalidate Route, `POST {basePath}/realtime/revalidate`: mount it next
|
|
189
|
+
* to the ticket route, with the same `secrets`. The BFF mounts it with
|
|
190
|
+
* `realtime.revalidate`.
|
|
191
|
+
*/
|
|
192
|
+
export declare const createRealtimeRevalidateHandler: (options: RealtimeRevalidateOptions) => ((request: Request) => Promise<Response>);
|
|
162
193
|
export type RealtimeTicketOptions = Readonly<{
|
|
163
194
|
/** `getSession` is needed only with `secrets`. */
|
|
164
195
|
auth: Pick<ApplicationUserAuth, "getAccessToken"> & Partial<Pick<ApplicationUserAuth, "getSession">>;
|
|
@@ -188,6 +219,13 @@ export type RealtimeTicketResponse = Readonly<{
|
|
|
188
219
|
*/
|
|
189
220
|
grantToken?: string;
|
|
190
221
|
}>;
|
|
222
|
+
/**
|
|
223
|
+
* `POST` route that mints a CI realtime ticket for the signed-in user with the
|
|
224
|
+
* server-held delegated token. The browser receives the ticket and the stream
|
|
225
|
+
* URL, never the token. With `secrets` it also receives the sealed Topic Grant
|
|
226
|
+
* of the ticket.
|
|
227
|
+
*/
|
|
228
|
+
export declare const createRealtimeTicketHandler: (options: RealtimeTicketOptions) => ((request: Request) => Promise<Response>);
|
|
191
229
|
export type BffResourceMount = Readonly<{
|
|
192
230
|
basePath: string;
|
|
193
231
|
handler: (request: Request) => Promise<Response>;
|
|
@@ -225,6 +263,8 @@ export type ExternalApplicationBffOptions = Readonly<{
|
|
|
225
263
|
resources?: readonly BffResourceMount[];
|
|
226
264
|
}>;
|
|
227
265
|
export type ExternalApplicationBff = (request: Request) => Promise<Response>;
|
|
266
|
+
/** One BFF mount for federated auth, Resource proxy, and dedicated Capability forwarding. */
|
|
267
|
+
export declare const createExternalApplicationBff: (options: ExternalApplicationBffOptions) => ExternalApplicationBff;
|
|
228
268
|
export type PrincipalKind = "detached_user" | "service_principal";
|
|
229
269
|
export type DelegatedSubjectPolicy = "allowed" | "forbidden" | "required";
|
|
230
270
|
export type AuthorizationRequirement = Readonly<{
|
|
@@ -397,6 +437,10 @@ export interface GatewayKernel {
|
|
|
397
437
|
readonly handle: (request: Request) => Promise<Response>;
|
|
398
438
|
readonly manifest: DefinedGateway["manifest"];
|
|
399
439
|
}
|
|
440
|
+
export declare const publicOriginFromHeaders: (headerList: Headers, fallbackOrigin: string) => string;
|
|
441
|
+
declare const cookiesFromRequest: (request: Request) => string | null;
|
|
442
|
+
declare const headersFromRequest: (request: Request) => Headers;
|
|
443
|
+
export declare const requestWithPublicOrigin: (request: Request, publicOrigin: string) => Request;
|
|
400
444
|
export type WorkflowTarget = Readonly<{
|
|
401
445
|
workflowId: string;
|
|
402
446
|
workflowFqn?: never;
|
|
@@ -417,6 +461,8 @@ export type FixedWorkflowRouteOptions<Input, Params = Record<string, never>> = R
|
|
|
417
461
|
authorize?: (request: Request) => Promise<EntityInvocationContext | Response>;
|
|
418
462
|
getAccessToken?: (request: Request) => Promise<string | null>;
|
|
419
463
|
}> & WorkflowTarget;
|
|
464
|
+
/** Server-owned Fixed workflow route. The browser cannot choose the workflow. */
|
|
465
|
+
export declare const createFixedWorkflowRoute: <Input, Params = Record<string, never>>(options: FixedWorkflowRouteOptions<Input, Params>) => ((request: Request, params: Params) => Promise<Response>);
|
|
420
466
|
export type GatewayWebHandler = (request: Request) => Promise<Response>;
|
|
421
467
|
export type GatewayRuntimeKernel = Pick<GatewayKernel, "handle">;
|
|
422
468
|
export type GatewayNextRouteHandlers = Readonly<{
|
|
@@ -426,12 +472,18 @@ export type GatewayNextRouteHandlers = Readonly<{
|
|
|
426
472
|
POST: GatewayWebHandler;
|
|
427
473
|
PUT: GatewayWebHandler;
|
|
428
474
|
}>;
|
|
475
|
+
/** Creates App Router-compatible route handlers without assuming a long-lived server. */
|
|
476
|
+
export declare const createGatewayNextRouteHandlers: (kernel: GatewayRuntimeKernel) => GatewayNextRouteHandlers;
|
|
429
477
|
export type ResourceNextRouteHandlers = Readonly<{
|
|
430
478
|
DELETE: GatewayWebHandler;
|
|
431
479
|
GET: GatewayWebHandler;
|
|
432
480
|
PATCH: GatewayWebHandler;
|
|
433
481
|
POST: GatewayWebHandler;
|
|
434
482
|
}>;
|
|
483
|
+
/** App Router CRUD routes over the host-authorized shared resource. */
|
|
484
|
+
export declare const createResourceNextRouteHandlers: <Value, Create = Value, Patch = Partial<Value>>(options: ResourceHttpHandlerOptions<Value, Create, Patch>) => ResourceNextRouteHandlers;
|
|
485
|
+
/** One Next App Router mount for federated auth, resources, and dedicated capabilities. */
|
|
486
|
+
export declare const createExternalApplicationBffNextHandlers: (options: ExternalApplicationBffOptions) => GatewayNextRouteHandlers;
|
|
435
487
|
/** The lifetime of a cache entry, in seconds. */
|
|
436
488
|
export type CacheLife = Readonly<{
|
|
437
489
|
expire?: number;
|
|
@@ -449,19 +501,29 @@ export type CacheCiReadOptions = Readonly<{
|
|
|
449
501
|
filter?: RealtimeTopicFilter;
|
|
450
502
|
id?: never;
|
|
451
503
|
})>;
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
504
|
+
/**
|
|
505
|
+
* Gives one CI read, inside an app function with the `use cache` directive,
|
|
506
|
+
* its cache tags and its lifetime: `cacheTag` for `ci:all`, the Schema Tag,
|
|
507
|
+
* and the Entity Tag of a get or the List Tag of a list, with the Topic Tag
|
|
508
|
+
* of a filtered list. A write expires its Entity Tag and the List Tag, so a
|
|
509
|
+
* write never expires the get of another record. `cacheLife`
|
|
510
|
+
* for `life`, by default 60 seconds stale, 60 seconds revalidate and one day
|
|
511
|
+
* expire. `schema` is the FQN. `client` is the service-mode server client,
|
|
512
|
+
* which reads with the app's own credential: a user-session client, or a
|
|
513
|
+
* client of a mode that the type does not know, does not type-check
|
|
514
|
+
* (INV-004, Q91). The parameter type is the mode part of the client only, so
|
|
515
|
+
* that a client of `.` fits it in the declarations of `./next`.
|
|
516
|
+
*/
|
|
456
517
|
export declare const cacheCiRead: (client: ServerClientMode<"service">, options: CacheCiReadOptions) => void;
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
schema: (fqn: string) => CiTag;
|
|
462
|
-
topic: (topic: import("@collective-intelligence/external-apps-client-sdk").RealtimeTopic) => CiTag;
|
|
463
|
-
};
|
|
518
|
+
/**
|
|
519
|
+
* The `invalidate` option of `createServerClient` in Next.js. Next allows
|
|
520
|
+
* `revalidateTag` in a Route Handler and a Server Function, so write there.
|
|
521
|
+
*/
|
|
464
522
|
export declare const nextInvalidate: (tags: readonly CiTag[]) => void;
|
|
465
|
-
|
|
523
|
+
|
|
524
|
+
export {
|
|
525
|
+
cookiesFromRequest as cookies,
|
|
526
|
+
headersFromRequest as headers,
|
|
527
|
+
};
|
|
466
528
|
|
|
467
529
|
export {};
|