@collective-intelligence/external-apps-server-sdk 0.2.0 → 0.2.2

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.
@@ -1 +1 @@
1
- import{layerNodePostgres2}from"../chunks/index-pzge02c9.js";import"../chunks/index-8yk07eg5.js";export{layerNodePostgres2 as layerNodePostgres};
1
+ import{makeDatabase,DrizzlePostgres2,DrizzlePostgresInitializationError2}from"../chunks/index-4z962jdh.js";import{drizzle}from"drizzle-orm/node-postgres";import*as Effect from"effect/Effect";import*as Layer from"effect/Layer";import{Pool}from"pg";var layerNodePostgres=(options)=>Layer.effect(DrizzlePostgres2,Effect.acquireRelease(Effect.try({catch:(cause)=>new DrizzlePostgresInitializationError2({cause}),try:()=>{const pool=new Pool(options.connection);return{database:makeDatabase(drizzle,pool),pool}}}),({pool})=>Effect.promise(async()=>{await pool.end()})).pipe(Effect.flatMap(({database,pool})=>{const value=DrizzlePostgres2.of({database,pool});const{migrate}=options;return migrate===undefined?Effect.succeed(value):Effect.tryPromise({catch:(cause)=>new DrizzlePostgresInitializationError2({cause}),try:migrate.bind(undefined,value)}).pipe(Effect.as(value))})));var layerNodePostgres2=layerNodePostgres;export{layerNodePostgres2 as layerNodePostgres};
package/dist/effect.d.ts CHANGED
@@ -956,7 +956,7 @@ declare const GatewayEffectRuntimeError_base: Schema.Class<GatewayEffectRuntimeE
956
956
  readonly cause: Schema.Defect;
957
957
  }>, import("effect/Cause").YieldableError>;
958
958
  declare class GatewayEffectRuntimeError extends GatewayEffectRuntimeError_base {
959
- /** The positional form of `./runtime/effect`: one argument is the cause. */
959
+ /** The positional form of 0.1.x: one argument is the cause. */
960
960
  constructor(cause: unknown);
961
961
  /** The Schema form; Schema decoding gives the fields and the options. */
962
962
  constructor(fields: Readonly<{
package/dist/effect.js CHANGED
@@ -1 +1 @@
1
- import{EntityFileValue2,EntityFileWrite2,EntityFileFieldWrite2,CiError2,CiErrorCode2,CiTransportError2,FederatedAuthError2,FederatedAuthErrorCode2,GatewayEffectRuntimeError2,MemberSessionExchangeError2,ServerClient2,layerServerClient2,layerServerClientConfig2,layerApplicationServerClient2,layerApplicationServerClientConfig2,exchangeMemberSession2,CacheInvalidation2,CiEntities2,layerCiEntities2,layerCiEntitiesConfig2,DateTimeString2,jsonSchema2,projectResourceSchema2,UuidV72,uuidV72,createGatewayEffectHandler2,createResourceEffectHandler2,makeEffectCrudResource2,DrizzlePostgres2,DrizzlePostgresInitializationError2,layerFromDatabase2}from"./chunks/index-ees2k4z3.js";import"./chunks/index-mp74xvyn.js";import"./chunks/index-8yk07eg5.js";export{CacheInvalidation2 as CacheInvalidation,CiEntities2 as CiEntities,CiError2 as CiError,CiErrorCode2 as CiErrorCode,CiTransportError2 as CiTransportError,DateTimeString2 as DateTimeString,DrizzlePostgres2 as DrizzlePostgres,DrizzlePostgresInitializationError2 as DrizzlePostgresInitializationError,EntityFileFieldWrite2 as EntityFileFieldWrite,EntityFileValue2 as EntityFileValue,EntityFileWrite2 as EntityFileWrite,FederatedAuthError2 as FederatedAuthError,FederatedAuthErrorCode2 as FederatedAuthErrorCode,GatewayEffectRuntimeError2 as GatewayEffectRuntimeError,MemberSessionExchangeError2 as MemberSessionExchangeError,ServerClient2 as ServerClient,UuidV72 as UuidV7,createGatewayEffectHandler2 as createGatewayEffectHandler,createResourceEffectHandler2 as createResourceEffectHandler,exchangeMemberSession2 as exchangeMemberSession,jsonSchema2 as jsonSchema,layerApplicationServerClient2 as layerApplicationServerClient,layerApplicationServerClientConfig2 as layerApplicationServerClientConfig,layerCiEntities2 as layerCiEntities,layerCiEntitiesConfig2 as layerCiEntitiesConfig,layerFromDatabase2 as layerFromDatabase,layerServerClient2 as layerServerClient,layerServerClientConfig2 as layerServerClientConfig,makeEffectCrudResource2 as makeEffectCrudResource,projectResourceSchema2 as projectResourceSchema,uuidV72 as uuidV7};
1
+ import{DrizzlePostgres2,layerFromDatabase2,DrizzlePostgresInitializationError2}from"./chunks/index-4z962jdh.js";import{__toESM,__commonJS,__export,CacheInvalidation2,invalidateRecord,require_codegen,require_util,require_names,require_validate,require_validation_error,require_ref_error,require_compile,require_core,require_ref,require_core2,require_validation,require_dependencies,require_applicator,require_format,require_metadata,require_discriminator,require_ajv,GatewayEffectRuntimeError2,MemberSessionExchangeError2,CiError2,CiErrorCode2,CiTransportError2,FederatedAuthError2,FederatedAuthErrorCode2,ServerClient2,layer,layerConfig,exchange,layerApplication,layerApplicationConfig,uuidV72}from"./chunks/index-qe1587f9.js";var require_formats=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});exports.formatNames=exports.fastFormats=exports.fullFormats=undefined;function fmtDef(validate,compare){return{validate,compare}}exports.fullFormats={date:fmtDef(date,compareDate),time:fmtDef(getTime(true),compareTime),"date-time":fmtDef(getDateTime(true),compareDateTime),"iso-time":fmtDef(getTime(),compareIsoTime),"iso-date-time":fmtDef(getDateTime(),compareIsoDateTime),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:true,binary:true};exports.fastFormats={...exports.fullFormats,date:fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,compareDate),time:fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareTime),"date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareDateTime),"iso-time":fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoTime),"iso-date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoDateTime),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};exports.formatNames=Object.keys(exports.fullFormats);function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;var DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date(str){const matches=DATE.exec(str);if(!matches)return false;const year=+matches[1];const month=+matches[2];const day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}function compareDate(d1,d2){if(!(d1&&d2))return;if(d1>d2)return 1;if(d1<d2)return-1;return 0}var TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function time(str){const matches=TIME.exec(str);if(!matches)return false;const hr=+matches[1];const min=+matches[2];const sec=+matches[3];const tz=matches[4];const tzSign=matches[5]==="-"?-1:1;const tzH=+(matches[6]||0);const tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return false;if(hr<=23&&min<=59&&sec<60)return true;const utcMin=min-tzM*tzSign;const utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}function compareTime(s1,s2){if(!(s1&&s2))return;const t1=new Date("2020-01-01T"+s1).valueOf();const t2=new Date("2020-01-01T"+s2).valueOf();if(!(t1&&t2))return;return t1-t2}function compareIsoTime(t1,t2){if(!(t1&&t2))return;const a1=TIME.exec(t1);const a2=TIME.exec(t2);if(!(a1&&a2))return;t1=a1[1]+a1[2]+a1[3];t2=a2[1]+a2[2]+a2[3];if(t1>t2)return 1;if(t1<t2)return-1;return 0}var DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){const time=getTime(strictTimeZone);return function date_time(str){const dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date(dateTime[0])&&time(dateTime[1])}}function compareDateTime(dt1,dt2){if(!(dt1&&dt2))return;const d1=new Date(dt1).valueOf();const d2=new Date(dt2).valueOf();if(!(d1&&d2))return;return d1-d2}function compareIsoDateTime(dt1,dt2){if(!(dt1&&dt2))return;const[d1,t1]=dt1.split(DATE_TIME_SEPARATOR);const[d2,t2]=dt2.split(DATE_TIME_SEPARATOR);const res=compareDate(d1,d2);if(res===undefined)return;return res||compareTime(t1,t2)}var NOT_URI_FRAGMENT=/\/|:/;var URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}var BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str){BYTE.lastIndex=0;return BYTE.test(str)}var MIN_INT32=-(2**31);var MAX_INT32=2**31-1;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return true}var Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return false;try{new RegExp(str);return true}catch(e){return false}}});var require_limit=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});exports.formatLimitDefinition=undefined;var ajv_1=require_ajv();var codegen_1=require_codegen();var ops=codegen_1.operators;var KWDs={formatMaximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},formatMinimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},formatExclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},formatExclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}};var error={message:({keyword,schemaCode})=>(0,codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`};exports.formatLimitDefinition={keyword:Object.keys(KWDs),type:"string",schemaType:"string",$data:true,error,code(cxt){const{gen,data,schemaCode,keyword,it}=cxt;const{opts,self}=it;if(!opts.validateFormats)return;const fCxt=new ajv_1.KeywordCxt(it,self.RULES.all.format.definition,"format");if(fCxt.$data)validate$DataFormat();else validateFormat();function validate$DataFormat(){const fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats});const fmt=gen.const("fmt",(0,codegen_1._)`${fmts}[${fCxt.schemaCode}]`);cxt.fail$data((0,codegen_1.or)((0,codegen_1._)`typeof ${fmt} != "object"`,(0,codegen_1._)`${fmt} instanceof RegExp`,(0,codegen_1._)`typeof ${fmt}.compare != "function"`,compareCode(fmt)))}function validateFormat(){const format=fCxt.schema;const fmtDef=self.formats[format];if(!fmtDef||fmtDef===true)return;if(typeof fmtDef!="object"||fmtDef instanceof RegExp||typeof fmtDef.compare!="function"){throw new Error(`"${keyword}": format "${format}" does not define "compare" function`)}const fmt=gen.scopeValue("formats",{key:format,ref:fmtDef,code:opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(format)}`:undefined});cxt.fail$data(compareCode(fmt))}function compareCode(fmt){return(0,codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`}},dependencies:["format"]};var formatLimitPlugin=(ajv)=>{ajv.addKeyword(exports.formatLimitDefinition);return ajv};exports.default=formatLimitPlugin});var require_dist=__commonJS(function(exports,module){Object.defineProperty(exports,"__esModule",{value:true});var formats_1=require_formats();var limit_1=require_limit();var codegen_1=require_codegen();var fullName=new codegen_1.Name("fullFormats");var fastName=new codegen_1.Name("fastFormats");var formatsPlugin=(ajv,opts={keywords:true})=>{if(Array.isArray(opts)){addFormats(ajv,opts,formats_1.fullFormats,fullName);return ajv}const[formats,exportName]=opts.mode==="fast"?[formats_1.fastFormats,fastName]:[formats_1.fullFormats,fullName];const list=opts.formats||formats_1.formatNames;addFormats(ajv,list,formats,exportName);if(opts.keywords)(0,limit_1.default)(ajv);return ajv};formatsPlugin.get=(name,mode="full")=>{const formats=mode==="fast"?formats_1.fastFormats:formats_1.fullFormats;const f=formats[name];if(!f)throw new Error(`Unknown format "${name}"`);return f};function addFormats(ajv,list,fs,exportName){var _a;var _b;(_a=(_b=ajv.opts.code).formats)!==null&&_a!==undefined||(_b.formats=(0,codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);for(const f of list)ajv.addFormat(f,fs[f])}module.exports=exports=formatsPlugin;Object.defineProperty(exports,"__esModule",{value:true});exports.default=formatsPlugin});var require_dynamicAnchor=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});exports.dynamicAnchor=undefined;var codegen_1=require_codegen();var names_1=require_names();var compile_1=require_compile();var ref_1=require_ref();var def={keyword:"$dynamicAnchor",schemaType:"string",code:(cxt)=>dynamicAnchor(cxt,cxt.schema)};function dynamicAnchor(cxt,anchor){const{gen,it}=cxt;it.schemaEnv.root.dynamicAnchors[anchor]=true;const v=(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`;const validate=it.errSchemaPath==="#"?it.validateName:_getValidate(cxt);gen.if((0,codegen_1._)`!${v}`,()=>gen.assign(v,validate))}exports.dynamicAnchor=dynamicAnchor;function _getValidate(cxt){const{schemaEnv,schema,self}=cxt.it;const{root,baseId,localRefs,meta}=schemaEnv.root;const{schemaId}=self.opts;const sch=new compile_1.SchemaEnv({schema,schemaId,root,baseId,localRefs,meta});compile_1.compileSchema.call(self,sch);return(0,ref_1.getValidate)(cxt,sch)}exports.default=def});var require_dynamicRef=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});exports.dynamicRef=undefined;var codegen_1=require_codegen();var names_1=require_names();var ref_1=require_ref();var def={keyword:"$dynamicRef",schemaType:"string",code:(cxt)=>dynamicRef(cxt,cxt.schema)};function dynamicRef(cxt,ref){const{gen,keyword,it}=cxt;if(ref[0]!=="#")throw new Error(`"${keyword}" only supports hash fragment reference`);const anchor=ref.slice(1);if(it.allErrors){_dynamicRef()}else{const valid=gen.let("valid",false);_dynamicRef(valid);cxt.ok(valid)}function _dynamicRef(valid){if(it.schemaEnv.root.dynamicAnchors[anchor]){const v=gen.let("_v",(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor)}`);gen.if(v,_callRef(v,valid),_callRef(it.validateName,valid))}else{_callRef(it.validateName,valid)()}}function _callRef(validate,valid){return valid?()=>gen.block(()=>{(0,ref_1.callRef)(cxt,validate);gen.let(valid,true)}):()=>(0,ref_1.callRef)(cxt,validate)}}exports.dynamicRef=dynamicRef;exports.default=def});var require_recursiveAnchor=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var dynamicAnchor_1=require_dynamicAnchor();var util_1=require_util();var def={keyword:"$recursiveAnchor",schemaType:"boolean",code(cxt){if(cxt.schema)(0,dynamicAnchor_1.dynamicAnchor)(cxt,"");else(0,util_1.checkStrictMode)(cxt.it,"$recursiveAnchor: false is ignored")}};exports.default=def});var require_recursiveRef=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var dynamicRef_1=require_dynamicRef();var def={keyword:"$recursiveRef",schemaType:"string",code:(cxt)=>(0,dynamicRef_1.dynamicRef)(cxt,cxt.schema)};exports.default=def});var require_dynamic=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var dynamicAnchor_1=require_dynamicAnchor();var dynamicRef_1=require_dynamicRef();var recursiveAnchor_1=require_recursiveAnchor();var recursiveRef_1=require_recursiveRef();var dynamic=[dynamicAnchor_1.default,dynamicRef_1.default,recursiveAnchor_1.default,recursiveRef_1.default];exports.default=dynamic});var require_dependentRequired=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var dependencies_1=require_dependencies();var def={keyword:"dependentRequired",type:"object",schemaType:"object",error:dependencies_1.error,code:(cxt)=>(0,dependencies_1.validatePropertyDeps)(cxt)};exports.default=def});var require_dependentSchemas=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var dependencies_1=require_dependencies();var def={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(cxt)=>(0,dependencies_1.validateSchemaDeps)(cxt)};exports.default=def});var require_limitContains=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var util_1=require_util();var def={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword,parentSchema,it}){if(parentSchema.contains===undefined){(0,util_1.checkStrictMode)(it,`"${keyword}" without "contains" is ignored`)}}};exports.default=def});var require_next=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var dependentRequired_1=require_dependentRequired();var dependentSchemas_1=require_dependentSchemas();var limitContains_1=require_limitContains();var next=[dependentRequired_1.default,dependentSchemas_1.default,limitContains_1.default];exports.default=next});var require_unevaluatedProperties=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var names_1=require_names();var error={message:"must NOT have unevaluated properties",params:({params})=>(0,codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}`};var def={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:true,error,code(cxt){const{gen,schema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");const{allErrors,props}=it;if(props instanceof codegen_1.Name){gen.if((0,codegen_1._)`${props} !== true`,()=>gen.forIn("key",data,(key)=>gen.if(unevaluatedDynamic(props,key),()=>unevaluatedPropCode(key))))}else if(props!==true){gen.forIn("key",data,(key)=>props===undefined?unevaluatedPropCode(key):gen.if(unevaluatedStatic(props,key),()=>unevaluatedPropCode(key)))}it.props=true;cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function unevaluatedPropCode(key){if(schema===false){cxt.setParams({unevaluatedProperty:key});cxt.error();if(!allErrors)gen.break();return}if(!(0,util_1.alwaysValidSchema)(it,schema)){const valid=gen.name("valid");cxt.subschema({keyword:"unevaluatedProperties",dataProp:key,dataPropType:util_1.Type.Str},valid);if(!allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())}}function unevaluatedDynamic(evaluatedProps,key){return(0,codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`}function unevaluatedStatic(evaluatedProps,key){const ps=[];for(const p in evaluatedProps){if(evaluatedProps[p]===true)ps.push((0,codegen_1._)`${key} !== ${p}`)}return(0,codegen_1.and)(...ps)}}};exports.default=def});var require_unevaluatedItems=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var codegen_1=require_codegen();var util_1=require_util();var error={message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`};var def={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error,code(cxt){const{gen,schema,data,it}=cxt;const items=it.items||0;if(items===true)return;const len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema===false){cxt.setParams({len:items});cxt.fail((0,codegen_1._)`${len} > ${items}`)}else if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){const valid=gen.var("valid",(0,codegen_1._)`${len} <= ${items}`);gen.if((0,codegen_1.not)(valid),()=>validateItems(valid,items));cxt.ok(valid)}it.items=true;function validateItems(valid,from){gen.forRange("i",from,len,(i)=>{cxt.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:util_1.Type.Num},valid);if(!it.allErrors)gen.if((0,codegen_1.not)(valid),()=>gen.break())})}}};exports.default=def});var require_unevaluated=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var unevaluatedProperties_1=require_unevaluatedProperties();var unevaluatedItems_1=require_unevaluatedItems();var unevaluated=[unevaluatedProperties_1.default,unevaluatedItems_1.default];exports.default=unevaluated});var require_draft2020=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var core_1=require_core2();var validation_1=require_validation();var applicator_1=require_applicator();var dynamic_1=require_dynamic();var next_1=require_next();var unevaluated_1=require_unevaluated();var format_1=require_format();var metadata_1=require_metadata();var draft2020Vocabularies=[dynamic_1.default,core_1.default,validation_1.default,(0,applicator_1.default)(true),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary,next_1.default,unevaluated_1.default];exports.default=draft2020Vocabularies});var require_schema=__commonJS(function(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:true,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:true,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:true},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:true}}}});var require_applicator2=__commonJS(function(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":true},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var require_unevaluated2=__commonJS(function(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var require_content=__commonJS(function(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var require_core3=__commonJS(function(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var require_format_annotation=__commonJS(function(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var require_meta_data=__commonJS(function(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:true,deprecated:{type:"boolean",default:false},readOnly:{type:"boolean",default:false},writeOnly:{type:"boolean",default:false},examples:{type:"array",items:true}}}});var require_validation2=__commonJS(function(exports,module){module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":true},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:true}]},const:true,enum:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}}}});var require_json_schema_2020_12=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:true});var metaSchema=require_schema();var applicator=require_applicator2();var unevaluated=require_unevaluated2();var content=require_content();var core=require_core3();var format=require_format_annotation();var metadata=require_meta_data();var validation=require_validation2();var META_SUPPORT_DATA=["/properties"];function addMetaSchema2020($data){[metaSchema,applicator,unevaluated,content,core,with$data(this,format),metadata,with$data(this,validation)].forEach((sch)=>this.addMetaSchema(sch,undefined,false));return this;function with$data(ajv,sch){return $data?ajv.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports.default=addMetaSchema2020});var require__2020=__commonJS(function(exports,module){Object.defineProperty(exports,"__esModule",{value:true});exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv2020=undefined;var core_1=require_core();var draft2020_1=require_draft2020();var discriminator_1=require_discriminator();var json_schema_2020_12_1=require_json_schema_2020_12();var META_SCHEMA_ID="https://json-schema.org/draft/2020-12/schema";class Ajv2020 extends core_1.default{constructor(opts={}){super({...opts,dynamicRef:true,next:true,unevaluated:true})}_addVocabularies(){super._addVocabularies();draft2020_1.default.forEach((v)=>this.addVocabulary(v));if(this.opts.discriminator)this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();const{$data,meta}=this.opts;if(!meta)return;json_schema_2020_12_1.default.call(this,$data);this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:undefined)}}exports.Ajv2020=Ajv2020;module.exports=exports=Ajv2020;module.exports.Ajv2020=Ajv2020;Object.defineProperty(exports,"__esModule",{value:true});exports.default=Ajv2020;var validate_1=require_validate();Object.defineProperty(exports,"KeywordCxt",{enumerable:true,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports,"_",{enumerable:true,get:function(){return codegen_1._}});Object.defineProperty(exports,"str",{enumerable:true,get:function(){return codegen_1.str}});Object.defineProperty(exports,"stringify",{enumerable:true,get:function(){return codegen_1.stringify}});Object.defineProperty(exports,"nil",{enumerable:true,get:function(){return codegen_1.nil}});Object.defineProperty(exports,"Name",{enumerable:true,get:function(){return codegen_1.Name}});Object.defineProperty(exports,"CodeGen",{enumerable:true,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports,"ValidationError",{enumerable:true,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports,"MissingRefError",{enumerable:true,get:function(){return ref_error_1.default}})});var exports_crud={};__export(exports_crud,{makeEffectCrudResource:()=>makeEffectCrudResource});import*as Effect2 from"effect/Effect";import*as ExitModule from"effect/Exit";import{createEntityProtocol}from"@collective-intelligence/external-apps-client-sdk/resources";var unavailableBrand=Symbol.for("@collective-intelligence/external-apps-server-sdk/ApplicationUserAuthUnavailableError");class ApplicationUserAuthUnavailableError extends Error{[unavailableBrand]=true;code="user_auth_unavailable";static[Symbol.hasInstance](value){return value instanceof Error&&unavailableBrand in value&&value[unavailableBrand]===true&&"code"in value&&value.code==="user_auth_unavailable"}constructor(cause){super("Application user authentication is unavailable",{cause});this.name="ApplicationUserAuthUnavailableError"}}var credential=Symbol.for("@collective-intelligence/external-apps-server-sdk/ci-entity-invocation");var ciEntityAccessToken=(context)=>{if(!Object.hasOwn(context,credential)){return}const bound=context;return bound[credential]?.(context)};var matchesEntityContext=(context,resourceId)=>context?.resourceId===resourceId&&context.applicationId.length>0&&context.user?.kind==="ci_user"&&context.user.id.length>0&&context.user.issuer===context.issuer&&context.user.organizationId===context.organizationId;var record=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value)?Object.fromEntries(Object.entries(value)):null;var json=(body,status,correlationId)=>Response.json(body,{headers:{"cache-control":"no-store","x-correlation-id":correlationId},status});var resourceResult=(result)=>{if(result.ok){return json(result,200,result.correlationId)}let status;switch(result.error.code){case"unauthenticated":{status=401;break}case"forbidden":{status=403;break}case"not_found":{status=404;break}case"conflict":{status=409;break}case"rate_limited":{status=429;break}case"unavailable":case"transport_error":{status=503;break}case"internal":{status=500;break}case"capability_not_supported":case"invalid_request":case"upload_not_supported":{status=400;break}default:{status=500}}return json(result,status,result.correlationId)};var resourceRequest=(request,body,resourceId,externalId,action,correlationId)=>{if(request.method==="POST"&&externalId===undefined&&(action==="scan"||action==="search")){const pagination=record(body.pagination);if(pagination===null||pagination.mode!=="cursor"&&pagination.mode!=="page"){return null}const query=body;return{operation:"list",query,requestId:correlationId,resourceId}}if(request.method==="GET"&&externalId!==undefined&&action===undefined){return{id:externalId,operation:"get",requestId:correlationId,resourceId}}if(request.method==="POST"&&externalId===undefined&&action==="records"){if(typeof body.idempotencyKey!=="string"||!("value"in body)){return null}return{idempotencyKey:body.idempotencyKey,operation:"create",requestId:correlationId,resourceId,value:body.value}}if(externalId===undefined||typeof body.expectedRevision!=="string"){return null}const idempotencyKey=typeof body.idempotencyKey==="string"?{idempotencyKey:body.idempotencyKey}:{};if(request.method==="PATCH"&&action===undefined&&"value"in body){return{expectedRevision:body.expectedRevision,id:externalId,...idempotencyKey,operation:"update",requestId:correlationId,resourceId,value:body.value}}const operation=request.method==="DELETE"&&action===undefined?"hard_delete":request.method==="POST"&&action==="soft-delete"?"soft_delete":request.method==="POST"&&action==="restore"?"restore":null;return operation===null?null:{expectedRevision:body.expectedRevision,id:externalId,...idempotencyKey,operation,requestId:correlationId,resourceId}};var readResourceBody=async(request,maximum)=>{if(Number(request.headers.get("content-length"))>maximum){await request.body?.cancel();return null}const reader=request.body?.getReader();if(reader===undefined){return null}const decoder=new TextDecoder("utf-8",{fatal:true});let size=0;let text="";try{for(;;){const{done,value}=await reader.read();if(done){break}size+=value.byteLength;if(size>maximum){await reader.cancel();return null}text+=decoder.decode(value,{stream:true})}text+=decoder.decode();const parsed=JSON.parse(text);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return null}return Object.fromEntries(Object.entries(parsed))}catch{return null}finally{reader.releaseLock()}};var fixedRoutes=new Map([["search",{kind:"search"}],["records",{kind:"collection"}],["records/batch",{kind:"batch"}],["uploads",{kind:"uploads"}]]);var trimTrailingSlash=(value)=>value.endsWith("/")?value.slice(0,-1):value;var matchEntityHttpRoute=(pathname,basePath)=>{const prefix=trimTrailingSlash(basePath);if(!pathname.startsWith(`${prefix}/`)){return null}let parts;try{parts=pathname.slice(prefix.length+1).split("/").map(decodeURIComponent)}catch{return null}const fixed=fixedRoutes.get(parts.join("/"));if(fixed!==undefined){return fixed}const[head,id,action]=parts;if(head!=="records"||id===undefined||id.length===0){return null}if(parts.length===2){return{id,kind:"record"}}if(parts.length===3&&action==="soft-delete"){return{id,kind:"soft_delete"}}if(parts.length===3&&action==="restore"){return{id,kind:"restore"}}if(parts.length===4&&action==="relation-members"&&parts[3]==="search"){return{id,kind:"relation_members"}}return null};var decodeEntityRoute=(protocol,input,body)=>{if(input.operation==="list_members"){const{field,...query}=body;return protocol.decodeRequest({...input,field,query})}if(input.operation==="upload"||input.operation==="batch"){return protocol.decodeRequest({...body,...input})}if(input.operation!=="list"&&input.operation!=="get"){const allowed=["idempotencyKey"];if(input.operation!=="create"){allowed.push("expectedRevision")}if(input.operation==="create"||input.operation==="update"){allowed.push("value")}if(Object.keys(body).some((key)=>!allowed.includes(key))){return{correlationId:input.requestId,error:{code:"invalid_request",details:{issues:[{field:"",keyword:"additionalProperties"}]},message:"Request contains unsupported entity fields",retryable:false},ok:false}}}return protocol.decodeRequest({...input,operation:input.operation==="soft_delete"?"delete":input.operation})};var routeTarget=(route)=>{switch(route.kind){case"search":{return{action:"search",externalId:undefined}}case"collection":{return{action:"records",externalId:undefined}}case"record":{return{action:undefined,externalId:route.id}}case"batch":{return{action:undefined,externalId:"batch"}}case"soft_delete":{return{action:"soft-delete",externalId:route.id}}case"restore":{return{action:"restore",externalId:route.id}}default:{return{action:undefined,externalId:undefined}}}};var readResourceRoute=async(request,basePath,resourceId,requestId,maximum)=>{const invalid=(message)=>resourceResult({correlationId:requestId,error:{code:"invalid_request",message,retryable:false},ok:false});const path=new URL(request.url).pathname;const route=matchEntityHttpRoute(path,basePath);if(route===null){return new Response(null,{status:404})}const body=request.method==="GET"?{}:await readResourceBody(request,maximum);if(body===null){return invalid("Request body is invalid or exceeds its limit")}if(route.kind==="relation_members"){const member={operation:"list_members",parentId:route.id,requestId,resourceId};return request.method==="POST"?{body,input:member}:invalid("Invalid resource route or request")}if(route.kind==="uploads"){const upload={operation:"upload",requestId,resourceId};return request.method==="POST"?{body,input:upload}:invalid("Invalid resource route or request")}if(route.kind==="batch"&&request.method==="POST"){const batch={operation:"batch",requestId,resourceId};return{body,input:batch}}const{action,externalId}=routeTarget(route);const input=resourceRequest(request,body,resourceId,externalId,action,requestId);return input===null?invalid("Invalid resource route or request"):{body,input}};var entityOnlyOperations=new Set(["batch","list_members","upload"]);var isCrudRequest=(input)=>!entityOnlyOperations.has(input.operation);var operationsOf=(input,decoded)=>{if(decoded===null||!decoded.ok){return[input.operation]}const{value}=decoded;return value.operation==="batch"?[value.operation,...new Set(value.ops.map(({op})=>op))]:[value.operation]};var authorizeAll=async(authorize,request,resourceId,operations)=>{let context;for(const operation of operations){const authorized=await authorize(request,operation);if(authorized instanceof Response){return authorized}if(!matchesEntityContext(authorized,resourceId)){return}context??=authorized}return context};var createResourceHttpHandler=(options)=>{const protocol="executeCrud"in options.resource?null:createEntityProtocol(options.resource.definition);return async(request)=>{const requestId=request.headers.get("x-correlation-id")?.match(/^[\w.-]{1,128}$/u)?.[0]??crypto.randomUUID();const{resource}=options;const route=await readResourceRoute(request,options.basePath,resource.definition.id,requestId,options.maxBodyBytes??1048576);if(route instanceof Response){return route}const{body,input}=route;const decoded=protocol===null?null:decodeEntityRoute(protocol,input,body);if(decoded!==null&&!decoded.ok){return resourceResult(decoded)}try{const authorized=await authorizeAll(options.authorize,request,resource.definition.id,operationsOf(input,decoded));if(authorized instanceof Response){return authorized}if(authorized===undefined){return resourceResult({correlationId:requestId,error:{code:"forbidden",message:"The current identity is not authorized for this resource",retryable:false},ok:false})}if("executeCrud"in resource){return isCrudRequest(input)?resourceResult(await resource.executeCrud(input,authorized)):new Response(null,{status:404})}if(decoded?.ok){return resourceResult(await resource.execute(decoded.value,authorized,{signal:request.signal}))}throw new TypeError("Entity request was not decoded")}catch(error){return resourceResult({correlationId:requestId,error:{code:error instanceof ApplicationUserAuthUnavailableError?"unavailable":"internal",message:"Resource authorization or execution is unavailable",retryable:false},ok:false})}}};import*as Effect from"effect/Effect";var resourceCapabilityByOperation={create:"create",get:"get",hard_delete:"hardDelete",list:"search",restore:"restore",soft_delete:"softDelete",update:"update"};var repositoryErrorBrand=Symbol.for("@collective-intelligence/external-apps-server-sdk/ResourceRepositoryError");var resourceErrorCodes={capability_not_supported:true,conflict:true,forbidden:true,internal:true,invalid_request:true,not_found:true,rate_limited:true,transport_error:true,unauthenticated:true,unavailable:true,upload_not_supported:true};var isResourceRepositoryError=(value)=>value instanceof Error&&(repositoryErrorBrand in value)&&value[repositoryErrorBrand]===true&&typeof value.message==="string"&&("code"in value)&&typeof value.code==="string"&&Object.hasOwn(resourceErrorCodes,value.code)&&("retryable"in value)&&typeof value.retryable==="boolean";class ResourceRepositoryError extends Error{[repositoryErrorBrand]=true;code;retryable;details;constructor(code,message,retryable=false,details){super(message);this.code=code;this.retryable=retryable;this.details=details;this.name="ResourceRepositoryError"}}var import_ajv_formats=__toESM(require_dist(),1);var import__2020=__toESM(require__2020(),1);var maxDepth=(filter,depth=0)=>{if(depth>16){throw new TypeError("Filter nesting exceeds 16 levels")}if(filter.operator==="and"||filter.operator==="or"){for(const child of filter.filters){maxDepth(child,depth+1)}}else if(filter.operator==="not"){maxDepth(filter.filter,depth+1)}};var referenceCardinality=(property)=>{if(property===null||typeof property!=="object"||Array.isArray(property)){return}if("format"in property&&property.format==="uuid"){return"one"}const items="items"in property?property.items:undefined;return items!==null&&typeof items==="object"&&!Array.isArray(items)&&"format"in items&&items.format==="uuid"?"many":undefined};var escapePattern=(value)=>value.replaceAll(/[$()*+.?[\\\]^{|}]/gu,"\\$&");var createResourceValidator=(definition,maxPageSize=100)=>{const entityProperties=definition.schemas.entity.properties;if(entityProperties!==undefined&&(typeof entityProperties!=="object"||entityProperties===null||Array.isArray(entityProperties))){throw new TypeError("Entity properties must be an object")}const properties=entityProperties;const leaves=definition.query.filterableFields.flatMap((field)=>{const value=properties?.[field];if(value===undefined){throw new TypeError(`Filter field ${field} requires a declared property schema`)}const predicate=(operators,valueSchema)=>({additionalProperties:false,properties:{field:{const:field},operator:{enum:operators},value:valueSchema??false},required:valueSchema===undefined?["field","operator"]:["field","operator","value"],type:"object"});const cardinality=referenceCardinality(value);const comparisonValue=cardinality==="many"?{format:"uuid",type:"string"}:value;return[predicate(cardinality===undefined?["is_null","is_not_null"]:["is_null","is_not_null","is_empty","is_not_empty"]),...cardinality==="many"&&typeof value==="object"&&value!==null&&"items"in value?[predicate(["contains_any","contains_all","contains_none"],{items:value.items,maxItems:1000,minItems:1,type:"array"})]:[],predicate(["eq","ne"],comparisonValue),predicate(["lt","lte","gt","gte"],{allOf:[value,{type:["number","string"]}]}),predicate(["contains","starts_with","ends_with"],{allOf:[value,{type:"string"}]}),predicate(["in","not_in"],{items:comparisonValue,maxItems:1000,minItems:1,type:"array"})]});const relationPaths=definition.query.filterableFields.flatMap((field)=>referenceCardinality(properties?.[field])===undefined?[]:[{additionalProperties:false,properties:{field:{pattern:`^${escapePattern(field)}(\\.[^.]+){1,3}$`},operator:{enum:["eq","ne","lt","lte","gt","gte","contains","starts_with","ends_with","in","not_in","is_null","is_not_null","contains_any","contains_all","contains_none","is_empty","is_not_empty"]},value:true},required:["field","operator"],type:"object"}]);const filter={oneOf:[...leaves,...relationPaths,{additionalProperties:false,properties:{filters:{items:{$ref:"#/$defs/filter"},maxItems:100,minItems:1,type:"array"},operator:{enum:["and","or"]}},required:["operator","filters"],type:"object"},{additionalProperties:false,properties:{filter:{$ref:"#/$defs/filter"},operator:{const:"not"}},required:["operator","filter"],type:"object"}]};const page={additionalProperties:false,properties:{mode:{const:"page"},page:{maximum:1e6,minimum:1,type:"integer"},pageSize:{maximum:maxPageSize,minimum:1,type:"integer"}},required:["mode","page","pageSize"],type:"object"};const cursor={additionalProperties:false,properties:{cursor:{maxLength:4096,minLength:1,type:"string"},limit:{maximum:maxPageSize,minimum:1,type:"integer"},mode:{const:"cursor"}},required:["mode","limit"],type:"object"};const includeDeleted=definition.capabilities.includeDeleted===true?{type:"boolean"}:{const:false};const query={properties:{filter:{$ref:"#/$defs/filter"},include:{items:{pattern:"^[^.]+(\\.[^.]+){0,2}$",type:"string"},maxItems:20,type:"array"},includeDeleted,pagination:{oneOf:definition.query.pagination.modes.map((mode)=>mode==="page"?page:cursor)},sort:{items:{additionalProperties:false,properties:{direction:{enum:["asc","desc"]},field:definition.query.sortableFields.length?{enum:definition.query.sortableFields}:false},required:["field","direction"],type:"object"},maxItems:20,type:"array"},textSearch:(definition.query.textSearchFields?.length??0)>0?{maxLength:1000,type:"string"}:false},required:["pagination"],type:"object"};const id={maxLength:4096,minLength:1,type:"string"};const request=(operation,required,requestProperties)=>({properties:{operation:{enum:operation},requestId:{minLength:1,type:"string"},resourceId:{const:definition.id},...requestProperties},required:["operation","resourceId","requestId",...required],type:"object"});const ajv=new import__2020.default({allErrors:false,strict:false});import_ajv_formats.default(ajv,["uuid"]);const validate=ajv.compile({$defs:{filter},oneOf:[request(["list"],["query"],{query}),request(["get"],["id"],{id,includeDeleted:query.properties.includeDeleted}),request(["create"],["idempotencyKey","value"],{idempotencyKey:{pattern:"^[\\w.-]{1,256}$",type:"string"},value:definition.schemas.create??false}),request(["update"],["id","expectedRevision","value"],{expectedRevision:id,id,value:definition.schemas.update??false}),request(["hard_delete","soft_delete","restore"],["id","expectedRevision"],{expectedRevision:id,id})]});return(input)=>{if(!validate(input)){throw new TypeError("Request does not match the declared resource schema, fields, operators or pagination")}if(input.operation==="list"&&input.query.filter!==undefined){maxDepth(input.query.filter)}}};var result=async(requestId,run)=>{try{return{correlationId:requestId,ok:true,value:await run()}}catch(error){if(isResourceRepositoryError(error)){return{correlationId:requestId,error:{code:error.code,message:error.message,retryable:error.retryable},ok:false}}if(error instanceof TypeError){return{correlationId:requestId,error:{code:"invalid_request",message:error.message,retryable:false},ok:false}}return{correlationId:requestId,error:{code:"internal",message:"Resource persistence failed",retryable:false},ok:false}}};var defineCrudResource=(input)=>{const{definition,repository}=input;for(const operation of["get","create","update","hardDelete","softDelete","restore"]){if(definition.capabilities[operation]===true&&repository[operation]===undefined){throw new TypeError(`Repository does not implement ${operation}`)}}const validate=createResourceValidator(definition);const execute=async(request,context)=>await result(request.requestId,async()=>{const capability=resourceCapabilityByOperation[request.operation];if(definition.capabilities[capability]!==true){throw new ResourceRepositoryError("capability_not_supported","Resource operation is unsupported")}validate(request);switch(request.operation){case"list":{return await repository.list(request.query,context)}case"get":{return await repository.get?.(request.id,request.includeDeleted,context)}case"create":{return await repository.create?.(request.value,request.idempotencyKey,context)}case"update":{return await repository.update?.({...request,value:request.value},context)}case"hard_delete":{await repository.hardDelete?.(request,context);return null}case"soft_delete":{return await repository.softDelete?.(request,context)}case"restore":{return await repository.restore?.(request,context)}default:{throw new TypeError("Unknown resource operation")}}});const{changes,scan}=repository;const resource={authorization:input.authorization,definition,execute:async(request)=>await execute(request),executeCrud:async(request,context)=>{if(!matchesEntityContext(context,definition.id)){return{correlationId:request.requestId,error:{code:"forbidden",message:"The current identity is not authorized for this resource",retryable:false},ok:false}}return await execute(request,context)}};if(changes!==undefined){Object.assign(resource,{changes:async(request)=>await result(request.requestId,async()=>await changes(request))})}if(scan!==undefined){Object.assign(resource,{scan:async(request)=>await result(request.requestId,async()=>await scan(request))})}return Object.freeze(resource)};var makeEffectCrudResource=(options)=>options.repository.pipe(Effect.map((repository)=>defineCrudResource({authorization:options.authorization,definition:options.definition,repository})));import{canonicalJson,Draft202012Dialect,normalizeJsonSchemaProjection,parseJsonObject,validateConsumerProfile}from"@collective-intelligence/extensions-sdk";import*as Schema from"effect/Schema";var isoDateTime=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;var uuidV7=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-7[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/u;var DateTimeString=Schema.String.check(Schema.makeFilter((value)=>isoDateTime.test(value)&&!Number.isNaN(Date.parse(value))?undefined:"Expected an ISO date-time",{toJsonSchema:()=>({pattern:isoDateTime.source})}));var UuidV7=Schema.String.check(Schema.isPattern(uuidV7));var jsonSchema=(schema)=>{const document=Schema.toJsonSchemaDocument(schema,{onExcessProperty:"error"});const projection=Object.keys(document.definitions).length===0?document.schema:{...document.schema,$defs:document.definitions};return parseJsonObject(canonicalJson(projection))};var escapePointer=(value)=>value.replaceAll("~","~0").replaceAll("/","~1");var lengthFilters=["effect/schema/isMinLength","effect/schema/isMaxLength","effect/schema/isLengthBetween","effect/schema/isBetweenLength"];var portableFilters=new Set([...lengthFilters,"effect/schema/isPattern","effect/schema/isInt","effect/schema/isFinite","effect/schema/isGreaterThan","effect/schema/isGreaterThanOrEqualTo","effect/schema/isLessThan","effect/schema/isLessThanOrEqualTo","effect/schema/isBetween","effect/schema/isMultipleOf","effect/schema/isMinSize","effect/schema/isMaxSize"]);var portableNodes=new Set(["Null","String","Number","Boolean","Literal","Objects","Arrays","Union","Suspend"]);var isPortableCheck=(check,ast)=>{if(check._tag==="FilterGroup"){return check.checks.every((child)=>isPortableCheck(child,ast))}const representation=check.annotations?.representation;if(representation===undefined||!portableFilters.has(representation.id)){return false}if(representation.id==="effect/schema/isPattern"){const payload=parseJsonObject(canonicalJson(representation.payload));return payload.flags==="u"}if(lengthFilters.includes(representation.id)){return ast._tag==="Arrays"}return true};var fidelityDiagnostics=(root)=>{const diagnostics=[];const ancestors=new Set;const visit=(ast,location)=>{if(ancestors.has(ast)){diagnostics.push({code:"unsupported_schema",location,reason:"Recursive schemas are not supported by portable resource forms."});return}ancestors.add(ast);if(ast.annotations?.toJsonSchema!==undefined||!portableNodes.has(ast._tag)){diagnostics.push({code:"unsupported_schema",location,reason:"Native schema or projection override cannot establish exact portable validation."})}if(ast.encoding!==undefined){diagnostics.push({code:"unsupported_transform",location,reason:"Native transform cannot be represented as exact portable validation."})}if(ast.checks?.some((check)=>!isPortableCheck(check,ast))===true){diagnostics.push({code:"unsupported_refinement",location,reason:"Native refinement cannot be represented as exact portable validation."})}if(ast._tag==="Objects"){for(const property of ast.propertySignatures){visit(property.type,`${location}/properties/${escapePointer(String(property.name))}`)}for(const signature of ast.indexSignatures){visit(signature.type,`${location}/additionalProperties`)}}else if(ast._tag==="Arrays"){for(const[index,element]of ast.elements.entries()){visit(element,`${location}/prefixItems/${index}`)}for(const element of ast.rest){visit(element,`${location}/items`)}}else if(ast._tag==="Union"){for(const[index,member]of ast.types.entries()){visit(member,`${location}/anyOf/${index}`)}}else if(ast._tag==="Suspend"){visit(ast.thunk(),location)}ancestors.delete(ast)};visit(root,"#");return diagnostics};var projectResourceSchema=(schema,metadata)=>{const diagnostics=fidelityDiagnostics(schema.ast);if(diagnostics.length>0){return{diagnostics,success:false}}const document=normalizeJsonSchemaProjection(jsonSchema(schema),"exact");const profileDiagnostics=validateConsumerProfile({dialect:Draft202012Dialect,document,fidelity:"exact"},"interactive_form","");if(profileDiagnostics.length>0){return{diagnostics:profileDiagnostics,success:false}}if(metadata!==undefined){canonicalJson(metadata);return{fidelity:"exact",metadata:structuredClone(metadata),schema:document,success:true}}return{fidelity:"exact",schema:document,success:true}};var createGatewayEffectHandler=(kernel)=>Effect2.fn("GatewayEffectHandler")(function*handleRequest(request){if(request.signal.aborted){return yield*Effect2.interrupt}const aborted=Effect2.callback((resume)=>{const interrupt2=()=>{resume(Effect2.interrupt)};request.signal.addEventListener("abort",interrupt2,{once:true});if(request.signal.aborted){interrupt2()}return Effect2.sync(()=>{request.signal.removeEventListener("abort",interrupt2)})});const handled=Effect2.tryPromise({catch:(cause)=>new GatewayEffectRuntimeError2(cause),try:async(signal)=>await kernel.handle(new Request(request,{signal:AbortSignal.any([request.signal,signal])}))});return yield*Effect2.raceFirst(handled,aborted)});var{makeEffectCrudResource:makeEffectCrudResource2}=exports_crud;var createResourceEffectHandler=(options)=>Effect2.fn("ResourceEffectHandler")(function*handleResourceRequest(request){const context2=yield*Effect2.context();let authorizationCause;let authorizationExit;const handle=createResourceHttpHandler({...options,authorize:async(input,operation)=>{authorizationExit=Promise.resolve().then(async()=>await Effect2.runPromiseExitWith(context2)(options.authorize(input,operation),{signal:input.signal}));const exit=await authorizationExit;if(ExitModule.isSuccess(exit)){return exit.value}authorizationCause=exit.cause;throw new GatewayEffectRuntimeError2(exit.cause)}});return yield*createGatewayEffectHandler({handle})(request).pipe(Effect2.flatMap((response)=>authorizationCause?Effect2.failCause(authorizationCause):Effect2.succeed(response)),Effect2.catch((error)=>authorizationCause?Effect2.failCause(authorizationCause):Effect2.fail(error)),Effect2.ensuring(Effect2.suspend(()=>{const pending=authorizationExit;return pending?Effect2.promise(async()=>await pending):Effect2.void})))});import{makeEntityHttpExecute}from"@collective-intelligence/external-apps-client-sdk/effect";import*as Config from"effect/Config";import*as Context from"effect/Context";import*as Effect3 from"effect/Effect";import*as Layer from"effect/Layer";import*as Schema2 from"effect/Schema";class CiEntities extends Context.Service()("@collective-intelligence/external-apps-server-sdk/CiEntities"){}var capability={batch:"batch",create:"create",delete:"delete",get:"get",list:"search",list_members:"search",restore:"restore",update:"update",upload:"upload"};var tenantOrigin=(tenantUrl)=>{const tenant=new URL(tenantUrl);if(tenant.protocol!=="https:"||tenant.username!==""||tenant.password!==""||tenant.pathname!=="/"||tenant.search!==""||tenant.hash!==""){throw new TypeError("CI entity bindings require an HTTPS tenant origin")}return tenant.origin};var entityExecute=(options,schemaFqn,accessToken)=>makeEntityHttpExecute({authentication:{auth:{getAccessToken:()=>accessToken},mode:"federated"},destination:{kind:"ci",organizationId:options.organizationId,schemaFqn,tenantUrl:tenantOrigin(options.tenantUrl)},fetch:options.fetch??globalThis.fetch});var isCiErrorCode=Schema2.is(CiErrorCode2);var isRecordWrite=(operation)=>operation==="create"||operation==="delete"||operation==="restore"||operation==="update";var outcomeOf=(operation)=>operation==="get"||operation==="list"||operation==="list_members"?"rejected":"uncertain";var failure=(error)=>error.code==="transport_error"?new CiTransportError2({cause:error}):new CiError2({code:isCiErrorCode(error.code)?error.code:"invalid_request",details:error.outcome===undefined?{...error.details,resourceCode:error.code}:{...error.details,outcome:error.outcome,resourceCode:error.code},message:error.message,retryable:error.retryable});var make=(options)=>{const origin=tenantOrigin(options.tenantUrl);const executeResult=Effect3.fn("CiEntities.executeResult")(function*executeResult(binding,request,context,callOptions){const{definition,protocol}=binding;const accessToken=ciEntityAccessToken(context);if(!matchesEntityContext(context,definition.id)||context.issuer!==origin||context.organizationId!==options.organizationId||accessToken===undefined){return{correlationId:request.requestId,error:{code:"forbidden",message:"The current CI identity is not authorized for this binding",outcome:"not_dispatched",retryable:false},ok:false}}const decoded=protocol.decodeRequest(request);if(!decoded.ok){return{...decoded,error:{...decoded.error,outcome:"not_dispatched"}}}const{operation}=decoded.value;const required=decoded.value.operation==="batch"?[capability.batch,...decoded.value.ops.map(({op})=>capability[op])]:[capability[operation]];if(required.some((name)=>definition.capabilities[name]!==true)){return{correlationId:request.requestId,error:{code:"capability_not_supported",message:"Resource operation is unsupported",outcome:"not_dispatched",retryable:false},ok:false}}const result=yield*entityExecute(options,binding.schemaFqn,accessToken)(decoded.value,callOptions??{}).pipe(Effect3.catchTag("CiTransportError",()=>Effect3.succeed({correlationId:request.requestId,error:{code:"transport_error",message:"The entity response could not be received",outcome:outcomeOf(operation),retryable:false},ok:false})));const decodeResult=(resultOperation)=>{const response=protocol.decodeResult(resultOperation,result,request.requestId);return!response.ok&&response.error.details?.phase==="response_contract"?{...response,error:{...response.error,outcome:outcomeOf(resultOperation)}}:response};if(operation==="batch"){const batched=decodeResult(operation);if(batched.ok){yield*Effect3.forEach(batched.value,(record)=>invalidateRecord({fqn:Effect3.succeedSome(binding.schemaFqn),id:record.id}),{discard:true})}return batched}if(!isRecordWrite(operation)){return decodeResult(operation)}const written=decodeResult(operation);if(written.ok){yield*invalidateRecord({fqn:Effect3.succeedSome(binding.schemaFqn),id:written.value.id})}return written});return CiEntities.of({execute:Effect3.fn("CiEntities.execute")(function*execute(binding,request,context){const result=yield*executeResult(binding,request,context);if(result.ok){return result.value}return yield*failure(result.error)}),executeResult})};var layer2=(options)=>Layer.sync(CiEntities,()=>make(options));var layerConfig2=(config)=>Layer.unwrap(Effect3.map(Config.unwrap(config),layer2));import*as Schema3 from"effect/Schema";var EntityFileValue=Schema3.Struct({filename:Schema3.String,id:Schema3.String,mimeType:Schema3.NullOr(Schema3.String),size:Schema3.NullOr(Schema3.Int),source:Schema3.Literals(["managed","external_url"]),url:Schema3.String});var EntityFileWrite=Schema3.Union([Schema3.Struct({id:Schema3.optionalKey(Schema3.Never),upload:Schema3.String}),Schema3.Struct({id:Schema3.String,upload:Schema3.optionalKey(Schema3.Never)})]);var EntityFileFieldWrite=Schema3.NullOr(Schema3.Union([EntityFileWrite,Schema3.Array(EntityFileWrite)]));var CiError=CiError2;var CiErrorCode=CiErrorCode2;var CiTransportError=CiTransportError2;var FederatedAuthError=FederatedAuthError2;var FederatedAuthErrorCode=FederatedAuthErrorCode2;var GatewayEffectRuntimeError=GatewayEffectRuntimeError2;var MemberSessionExchangeError=MemberSessionExchangeError2;var ServerClient=ServerClient2;var layerServerClient=layer;var layerServerClientConfig=layerConfig;var layerApplicationServerClient=layerApplication;var layerApplicationServerClientConfig=layerApplicationConfig;var exchangeMemberSession=exchange;var CacheInvalidation=CacheInvalidation2;var CiEntities2=CiEntities;var layerCiEntities=layer2;var layerCiEntitiesConfig=layerConfig2;var DateTimeString2=DateTimeString;var jsonSchema2=jsonSchema;var projectResourceSchema2=projectResourceSchema;var UuidV72=UuidV7;var uuidV73=uuidV72;var createGatewayEffectHandler2=createGatewayEffectHandler;var createResourceEffectHandler2=createResourceEffectHandler;var makeEffectCrudResource3=makeEffectCrudResource2;var DrizzlePostgres=DrizzlePostgres2;var DrizzlePostgresInitializationError=DrizzlePostgresInitializationError2;var layerFromDatabase=layerFromDatabase2;export{CacheInvalidation,CiEntities2 as CiEntities,CiError,CiErrorCode,CiTransportError,DateTimeString2 as DateTimeString,DrizzlePostgres,DrizzlePostgresInitializationError,EntityFileFieldWrite,EntityFileValue,EntityFileWrite,FederatedAuthError,FederatedAuthErrorCode,GatewayEffectRuntimeError,MemberSessionExchangeError,ServerClient,UuidV72 as UuidV7,createGatewayEffectHandler2 as createGatewayEffectHandler,createResourceEffectHandler2 as createResourceEffectHandler,exchangeMemberSession,jsonSchema2 as jsonSchema,layerApplicationServerClient,layerApplicationServerClientConfig,layerCiEntities,layerCiEntitiesConfig,layerFromDatabase,layerServerClient,layerServerClientConfig,makeEffectCrudResource3 as makeEffectCrudResource,projectResourceSchema2 as projectResourceSchema,uuidV73 as uuidV7};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{CiError3,CiTransportError3,FederatedAuthError3,exports_client,exports_member_session,exports_run_as_application,exports_uuid_v7}from"./chunks/index-mp74xvyn.js";var CiError=CiError3;var CiTransportError=CiTransportError3;var FederatedAuthError=FederatedAuthError3;var{createServerClient}=exports_client;var{serverSdkRuntime}=exports_client;var{runAsApplication}=exports_run_as_application;var{exchangeMemberSession,MemberSessionExchangeError}=exports_member_session;var{uuidV7}=exports_uuid_v7;export{CiError,CiTransportError,FederatedAuthError,MemberSessionExchangeError,createServerClient,exchangeMemberSession,runAsApplication,serverSdkRuntime,uuidV7};
1
+ import{CiError2,CiTransportError2,FederatedAuthError2,exports_client,exports_member_session,exports_run_as_application,exports_uuid_v7}from"./chunks/index-qe1587f9.js";var CiError=CiError2;var CiTransportError=CiTransportError2;var FederatedAuthError=FederatedAuthError2;var{createServerClient}=exports_client;var{serverSdkRuntime}=exports_client;var{runAsApplication}=exports_run_as_application;var{exchangeMemberSession,MemberSessionExchangeError}=exports_member_session;var{uuidV7}=exports_uuid_v7;export{CiError,CiTransportError,FederatedAuthError,MemberSessionExchangeError,createServerClient,exchangeMemberSession,runAsApplication,serverSdkRuntime,uuidV7};
package/docs/effect.md ADDED
@@ -0,0 +1,76 @@
1
+ # Effect
2
+
3
+ `/effect` is the Effect API of the server SDK. The package root is a Vanilla
4
+ Facade over the same Effect Core: both load `effect`, and a class that both
5
+ export has one identity in the app.
6
+
7
+ ## Convention
8
+
9
+ - Import Effect APIs only from `/effect`. `/effect` loads no `next`, no `pg`
10
+ and no `drizzle-orm`.
11
+ - `/effect/next` holds `CacheInvalidation.layerNext` and loads `next`.
12
+ - `/effect/node-postgres` holds `layerNodePostgres` and loads `pg` and
13
+ `drizzle-orm`.
14
+ - `effect` `^4.1.0` is a required peer: keep one version in the app.
15
+ - The `ci-solution/effect-subpath` rule of `@collective-intelligence/lint`
16
+ reports an Effect API that comes from outside `/effect`, and the subpaths
17
+ that the release after 0.2.0 removes. To move code, run
18
+ [the move skill](../skills/server-sdk-move-to-effect/SKILL.md).
19
+
20
+ ## Services and layers
21
+
22
+ Each client is one `Context.Service` with a `layer` and a `layerConfig` that
23
+ reads Effect `Config`.
24
+
25
+ | Service | Layers |
26
+ | -------------- | -------------------------------------------------------------------------------------------------------------------- |
27
+ | `ServerClient` | `layerServerClient`, `layerServerClientConfig`, `layerApplicationServerClient`, `layerApplicationServerClientConfig` |
28
+ | `CiEntities` | `layerCiEntities`, `layerCiEntitiesConfig` |
29
+
30
+ - `execute` fails with `CiError` or `CiTransportError`; `executeResult` keeps
31
+ the CI error envelope as a value. `records.create`, `update` and `delete`
32
+ fail with `CiError`; `recordsResult` keeps the refusal as a value.
33
+ - A `layer...Config` reads the client secret with `Config.Redacted`.
34
+ - Without a `sleep` option, the retry backoff is `Effect.sleep` on the
35
+ `Clock`, so `TestClock` drives it.
36
+ - `exchangeMemberSession(request)` fails with `MemberSessionExchangeError`.
37
+ - `CacheInvalidation` is a `Context.Reference` whose default does nothing.
38
+ The writes read it from their fiber: merge `CacheInvalidation.layerNext`
39
+ into the runtime next to the client layers, not with `Layer.provide` into
40
+ them. See [next-cache.md](next-cache.md#write-invalidation).
41
+
42
+ ```ts
43
+ import * as Effect from "effect/Effect"
44
+ import {
45
+ layerServerClient,
46
+ ServerClient
47
+ } from "@collective-intelligence/external-apps-server-sdk/effect"
48
+
49
+ const program = ServerClient.use((client) =>
50
+ client.execute("context_get", { organizationId })
51
+ ).pipe(
52
+ Effect.catchTag("CiError", (error) => Effect.succeed(error.code)),
53
+ Effect.provide(layerServerClient({ authentication, tenantUrl }))
54
+ )
55
+ ```
56
+
57
+ ## Read Port
58
+
59
+ Shared cached reads of an Effect server go through an app-owned `ReadPort`
60
+ service. The Next app supplies its `"use cache"` adapter; a passthrough layer
61
+ serves tests and runs outside Next. See
62
+ [next-cache.md](next-cache.md#effect-server-the-read-port).
63
+
64
+ ## Resources and gateways
65
+
66
+ - `makeEffectCrudResource` acquires the repository Effect once and returns the
67
+ portable `CrudResource` of the HTTP and gateway bindings.
68
+ - `createResourceEffectHandler` and `createGatewayEffectHandler` lift the
69
+ resource and the gateway kernel into Effect handlers. A request abort
70
+ interrupts the fiber.
71
+ - `jsonSchema`, `DateTimeString` and `UuidV7` give wire Schemas for resource
72
+ and operation definitions.
73
+
74
+ ## Errors
75
+
76
+ See [errors.md](errors.md).
package/docs/errors.md ADDED
@@ -0,0 +1,30 @@
1
+ # Errors
2
+
3
+ The server SDK uses the tagged error classes of
4
+ `@collective-intelligence/external-apps-client-sdk`. The package root and
5
+ `/effect` export the same classes, so `instanceof` gives one answer in the
6
+ app.
7
+
8
+ | Class | When |
9
+ | ---------------------------- | --------------------------------------------------------------------- |
10
+ | `CiError` | CI refused an operation: `code`, `message`, `retryable`, `details?` |
11
+ | `CiTransportError` | The request did not reach CI, or its answer was not readable: `cause` |
12
+ | `FederatedAuthError` | The federated sign-in failed: `code`, `message` |
13
+ | `MemberSessionExchangeError` | `exchangeMemberSession` failed |
14
+ | `GatewayEffectRuntimeError` | The Effect gateway runtime failed |
15
+
16
+ ## Rules
17
+
18
+ - A CI error envelope stays a value: `{ ok: false, error: { correlationId, error } }`.
19
+ Read `error.code`; keep `correlationId` in logs.
20
+ - A transport failure rejects (Promise) or fails (Effect) with
21
+ `CiTransportError`. Its `message` is empty: show the user your own text.
22
+ - An abort through `signal` rejects with `signal.reason`; in Effect it is an
23
+ interruption.
24
+ - Bad input, such as a bad `tenantUrl`, throws `TypeError`. Fix the call.
25
+ - `defineCiEntityResource` keeps each failure as a value of its
26
+ `ResourceResult`, with `transport_error` and its `outcome`.
27
+ - A failed cache invalidation after a confirmed write only logs a warning; the
28
+ write keeps its result.
29
+ - In Effect, branch with `Effect.catchTag("CiError", ...)`; decode a wire code
30
+ with the `CiErrorCode` Schema of `/effect`.
@@ -0,0 +1,120 @@
1
+ # Next.js cache
2
+
3
+ The Cache Primitives of `/next` give a CI read its cache tags and its
4
+ lifetime in Next.js Cache Components (Next.js 16, `cacheComponents: true`).
5
+ The app owns the `"use cache"` directive and the cache store. `/next` loads
6
+ `next`.
7
+
8
+ ## Cache a shared read
9
+
10
+ 1. Make a server client with the app's own credential:
11
+ `createServerClient({ authentication: { credentials, mode: "service" }, invalidate: nextInvalidate, tenantUrl })`.
12
+ 2. Write `"use cache"` at the start of the app function (or file) that reads.
13
+ 3. In that scope, call `cacheCiRead(client, { schema, id })` for a get, or
14
+ `cacheCiRead(client, { schema, filter })` for a filtered list, then read.
15
+
16
+ ```ts
17
+ import { cacheCiRead } from "@collective-intelligence/external-apps-server-sdk/next"
18
+
19
+ import { ci } from "./ci" // the service-mode server client
20
+
21
+ export const getLead = async (organizationId: string, entityId: string) => {
22
+ "use cache"
23
+ cacheCiRead(ci, { id: entityId, schema: "acme.crm.lead" })
24
+ const answer = await ci.knowledge.query({
25
+ organizationId,
26
+ query: { entityId, op: "get" }
27
+ })
28
+ if (!answer.ok) {
29
+ // Throw: the cache must not keep a CI error envelope.
30
+ throw new Error(`CI read failed: ${answer.error.error.code}`)
31
+ }
32
+ return answer.value.result
33
+ }
34
+ ```
35
+
36
+ - `schema` is the FQN of the schema.
37
+ - Read a get with `knowledge.query` and `op: "get"`. Return only the answer of
38
+ an ok result, and throw on an error envelope: a thrown read is not cached.
39
+ - Tags: `ciTag.all`, the Schema Tag, and the Entity Tag of a get or the Topic
40
+ Tag of a filtered list. To name a tag yourself, use `ciTag.entity(fqn, id)`,
41
+ `ciTag.schema(fqn)` or `ciTag.topic({ schema, filter })`. A tag is a
42
+ `CiTag`, a branded string; the SDK computes it.
43
+ - Lifetime: `life`, by default `{ stale: 60, revalidate: 60, expire: 86400 }`
44
+ seconds. A `life` replaces the default as a whole.
45
+ - `cacheCiRead` calls `cacheTag` and `cacheLife` of `next/cache`, so it works
46
+ only inside a `"use cache"` scope.
47
+
48
+ ## Credential rule
49
+
50
+ A cache entry goes to every visitor. So a cached read uses the app's own
51
+ credential:
52
+
53
+ - `cacheCiRead` type-checks only with `ServerClient<"service">`: a client whose
54
+ config has `authentication: { credentials, mode: "service" }`.
55
+ - A user-session client (`getAccessToken`, a token from
56
+ `exchangeMemberSession`), a client typed `ServerClient`, and the client of
57
+ `runAsApplication` do not type-check. This is the gate; keep it, with no
58
+ cast.
59
+ - User-scoped reads stay in TanStack Query on the client (the entity hooks of
60
+ `external-apps-client-sdk-react`). They never go into the shared cache.
61
+
62
+ ## Effect server: the Read Port
63
+
64
+ When the app API is an Effect server, keep `next` out of it:
65
+
66
+ - The server owns a `ReadPort` `Context.Service` with the shared reads.
67
+ - The Next app gives the adapter layer: each function has `"use cache"`,
68
+ calls `cacheCiRead`, and returns plain JSON from an uncached read.
69
+ - A passthrough layer reads CI through the `/effect` `ServerClient`, for tests
70
+ and for runs outside Next.
71
+ - Put into the port only reads that every signed-in user may see.
72
+
73
+ ## Write invalidation
74
+
75
+ After CI confirms a write, the SDK expires the Entity Tag and the Schema Tag
76
+ of its record, so the next read computes the entry again. This covers
77
+ `resources.records` writes and each write through the CI entity proxy
78
+ (`ciResources` of the BFF, `createCiResourceMounts`, `defineCiEntityResource`,
79
+ `CiEntities`). A read, and a write that CI refuses or that fails, expires
80
+ nothing.
81
+
82
+ | Code | Give it |
83
+ | ------------------------------------------------------------------ | ----------------------------------------------- |
84
+ | `createServerClient`, `runAsApplication` | `invalidate: nextInvalidate` |
85
+ | `ciResources`, `createCiResourceMounts`, `defineCiEntityResource` | `invalidate: nextInvalidate` |
86
+ | Effect runtime with `layerServerClient...` or `layerCiEntities...` | `CacheInvalidation.layerNext` of `/effect/next` |
87
+
88
+ - Merge `CacheInvalidation.layerNext` into the runtime, or provide it to the
89
+ program: `Layer.mergeAll(layerServerClientConfig(config), CacheInvalidation.layerNext)`.
90
+ The writes read it from their fiber, so `Layer.provide` of it to the client
91
+ layer does not reach them.
92
+ - `revalidateTag` runs only in a Route Handler or a Server Function. Write
93
+ there, not while a page renders.
94
+ - A failed invalidation does not fail the write: the write logs a warning and
95
+ keeps the record that CI confirmed. The old entry stays until its lifetime
96
+ ends.
97
+ - A write named by schema id reads the schema snapshot once per process to
98
+ find the FQN.
99
+
100
+ ## More than one instance
101
+
102
+ With the built-in in-memory store, each instance has its own cache. An
103
+ invalidation reaches only the instance that receives it; the other instances
104
+ serve old data until the lifetime ends. When that gap matters, configure a
105
+ shared store:
106
+
107
+ 1. Write a cache handler over shared storage. It implements `refreshTags`, so
108
+ each instance reads the tags that other instances expired.
109
+ 2. Register it under a kind name in `next.config.ts`:
110
+ `cacheHandlers: { neon: require.resolve("./cache-handlers/neon.mjs") }`.
111
+ 3. Use that kind in the shared reads: `"use cache: neon"`. `cacheCiRead`
112
+ works the same in that scope.
113
+
114
+ Example: apito plans a Neon cache handler, a handler whose storage is its Neon
115
+ database, used as `'use cache: neon'` for the shared CI reads only.
116
+
117
+ ## Realtime
118
+
119
+ The Revalidate Route expires the tags of the records that change in CI while
120
+ a tab is open. See [realtime.md](realtime.md).
@@ -0,0 +1,75 @@
1
+ # Realtime routes
2
+
3
+ A browser opens the CI realtime stream with a single-use ticket from the BFF,
4
+ never with the user's token. The server SDK gives two routes:
5
+
6
+ | Route | Handler of `/next` | Job |
7
+ | ------------------------------------- | --------------------------------- | -------------------------------------------------------------- |
8
+ | `POST {basePath}/realtime/ticket` | `createRealtimeTicketHandler` | Gets a CI ticket with the user's server-held token |
9
+ | `POST {basePath}/realtime/revalidate` | `createRealtimeRevalidateHandler` | Expires the Next.js cache tags of the changes that a tab posts |
10
+
11
+ `basePath` is `/api` by default. The browser client is in
12
+ `external-apps-client-sdk` (`createRealtimeClient`) and
13
+ `external-apps-client-sdk-react` (`RealtimeProvider`).
14
+
15
+ ## Mount both routes
16
+
17
+ ```ts
18
+ import {
19
+ createExternalApplicationBffNextHandlers,
20
+ createRealtimeRevalidateHandler
21
+ } from "@collective-intelligence/external-apps-server-sdk/next"
22
+
23
+ createExternalApplicationBffNextHandlers({
24
+ auth,
25
+ publicOrigin: env.APP_ORIGIN,
26
+ realtime: {
27
+ organizationId: env.CI_ORGANIZATION_ID,
28
+ revalidate: createRealtimeRevalidateHandler,
29
+ // The session secrets, the current one first.
30
+ secrets: [env.SESSION_SECRET],
31
+ tenantUrl: env.CI_TENANT_URL
32
+ }
33
+ })
34
+ ```
35
+
36
+ Then give the browser realtime client
37
+ `revalidateUrl: "/api/realtime/revalidate"`.
38
+
39
+ ## Topic Grant
40
+
41
+ - With `secrets`, each ticket answer also holds `grantToken`, the Topic Grant:
42
+ the topics that CI accepted, the session of the request, and an expiry 10
43
+ minutes after mint, sealed with the secret.
44
+ - The grant token is the only authority of the Revalidate Route. The route
45
+ refuses a token that is not its own, that expired, or that another session
46
+ got (403 `invalid_grant`), and a request without a session (401).
47
+ - It ignores a change whose topic is not in the token, and it never expires
48
+ `ci:all`.
49
+ - The token binds to the `sessionId` of the session that `auth.getSession`
50
+ gives. A custom `ApplicationUserAuth` without `sessionId` binds the token to
51
+ the user. Give a `sessionId` that stays the same for one session.
52
+ - The browser client renews the token 8 minutes after each ticket while the
53
+ stream stays open.
54
+
55
+ ## What the Revalidate Route expires
56
+
57
+ - For each accepted change: the Topic Tag (the Schema Tag for a topic without
58
+ a filter) and the Entity Tag. These are the tags that `cacheCiRead` writes;
59
+ see [next-cache.md](next-cache.md).
60
+ - `reset: true`, after a `reset` or `access-changed` event: the tag of each
61
+ topic in the token.
62
+ - It calls `revalidateTag(tag, { expire: 0 })`. On one instance, the first post
63
+ of a tag expires it at once and opens a 1-second window; more posts in the
64
+ window expire it once more at the window end, through `after`.
65
+ - A body holds at most 100 changes and 1 MiB (else 400 `invalid_request`). The
66
+ client splits a larger delivery.
67
+ - Each instance expires tags only for the posts that it receives. With the
68
+ built-in store, the other instances keep old entries; see
69
+ [next-cache.md](next-cache.md#more-than-one-instance).
70
+
71
+ ## Mount the routes yourself
72
+
73
+ Call `createRealtimeTicketHandler` and `createRealtimeRevalidateHandler` from
74
+ `/next` with the same `auth` and `secrets`. `secrets` needs
75
+ `auth.getSession`.
package/package.json CHANGED
@@ -1,12 +1,15 @@
1
1
  {
2
2
  "name": "@collective-intelligence/external-apps-server-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Server-side client and proxy adapters for Collective Intelligence external applications.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "files": [
8
8
  "dist",
9
- "README.md"
9
+ "README.md",
10
+ "AGENTS.md",
11
+ "docs",
12
+ "skills"
10
13
  ],
11
14
  "main": "./dist/index.js",
12
15
  "types": "./dist/index.d.ts",
@@ -77,12 +80,6 @@
77
80
  "import": "./dist/persistence/drizzle.js",
78
81
  "default": "./dist/persistence/drizzle.js"
79
82
  },
80
- "./persistence/drizzle/effect": {
81
- "ci-source": "./src/entrypoints/persistence/drizzle-effect.ts",
82
- "types": "./dist/persistence/drizzle-effect.d.ts",
83
- "import": "./dist/persistence/drizzle-effect.js",
84
- "default": "./dist/persistence/drizzle-effect.js"
85
- },
86
83
  "./knowledge-sources/payload": {
87
84
  "ci-source": "./src/entrypoints/knowledge-sources/payload.ts",
88
85
  "types": "./dist/knowledge-sources/payload.d.ts",
@@ -113,18 +110,6 @@
113
110
  "import": "./dist/runtime/nestjs.js",
114
111
  "default": "./dist/runtime/nestjs.js"
115
112
  },
116
- "./runtime/next": {
117
- "ci-source": "./src/entrypoints/runtime/next.ts",
118
- "types": "./dist/runtime/next.d.ts",
119
- "import": "./dist/next.js",
120
- "default": "./dist/next.js"
121
- },
122
- "./runtime/effect": {
123
- "ci-source": "./src/entrypoints/runtime/effect.ts",
124
- "types": "./dist/runtime/effect.d.ts",
125
- "import": "./dist/effect.js",
126
- "default": "./dist/effect.js"
127
- },
128
113
  "./gateway/contracts": {
129
114
  "ci-source": "./src/entrypoints/gateway/contracts.ts",
130
115
  "types": "./dist/gateway/contracts.d.ts",
@@ -166,8 +151,8 @@
166
151
  "test:postgres": "bun tools/test-postgres.ts src/adapters/persistence/drizzle"
167
152
  },
168
153
  "dependencies": {
169
- "@collective-intelligence/extensions-sdk": "0.2.0",
170
- "@collective-intelligence/external-apps-client-sdk": "0.2.0",
154
+ "@collective-intelligence/extensions-sdk": "0.2.2",
155
+ "@collective-intelligence/external-apps-client-sdk": "0.2.2",
171
156
  "ajv": "8.20.0",
172
157
  "ajv-formats": "3.0.1",
173
158
  "jose": "6.2.9"
@@ -267,5 +252,5 @@
267
252
  "vitest": "5.0.2",
268
253
  "zod": "4.4.3"
269
254
  },
270
- "gitHead": "399369a97e85b54b43aeac887e7ba9c960cb7505"
255
+ "gitHead": "51fdea833e25fe215b3cf0d70adf1984b8e0f81c"
271
256
  }
@@ -0,0 +1,45 @@
1
+ ---
2
+ name: server-sdk-adopt-cache-primitives
3
+ description: Move the cached CI reads of a Next.js app to the Cache Primitives of `@collective-intelligence/external-apps-server-sdk/next`. Use when an app caches CI reads with its own tags or `unstable_cache`, calls `revalidateTag` after SDK writes, or turns on Cache Components.
4
+ ---
5
+
6
+ # Adopt the Cache Primitives
7
+
8
+ Reference: [next-cache.md](../../docs/next-cache.md),
9
+ [realtime.md](../../docs/realtime.md).
10
+
11
+ ## Steps
12
+
13
+ 1. **Inventory.** Search the app for `unstable_cache`, `cacheTag(`,
14
+ `cacheLife(`, `revalidateTag(`, `revalidatePath(` and `"use cache"` near
15
+ calls of the CI server client. Done when you have a list with each cached
16
+ CI read site and each manual revalidation after an SDK write.
17
+ 2. **Classify each read.** A read is _shared_ when it uses the app's own
18
+ credential and gives the same answer to every visitor; else it is
19
+ _user-scoped_. Done when each read of the list has one class.
20
+ 3. **Move the user-scoped reads out of the server cache.** Read them with
21
+ TanStack Query on the client (the entity hooks of
22
+ `external-apps-client-sdk-react`), or uncached on the server. Done when no
23
+ user-scoped read is in a `"use cache"` scope.
24
+ 4. **Tag the shared reads.** For each one: use the service-mode server client;
25
+ write `"use cache"` in the app function; call
26
+ `cacheCiRead(client, { schema, id })` or `{ schema, filter }` with the
27
+ schema FQN; remove the hand-written tags and `unstable_cache`. In an Effect
28
+ server, put the read behind the Read Port. Done when each shared read calls
29
+ `cacheCiRead` and type-checks with no cast on the client.
30
+ 5. **Wire write invalidation.** Pass `invalidate: nextInvalidate` to
31
+ `createServerClient`, `runAsApplication`, `ciResources`,
32
+ `createCiResourceMounts` and `defineCiEntityResource`; in an Effect runtime,
33
+ merge `CacheInvalidation.layerNext`. Remove each manual `revalidateTag` of
34
+ step 1 that follows an SDK write; keep the ones for other writes. Done when
35
+ each SDK write path has an invalidation and no manual call duplicates it.
36
+ 6. **Wire realtime, when the app has a realtime client.** Add `secrets` and
37
+ `revalidate: createRealtimeRevalidateHandler` to the BFF `realtime`
38
+ options, and `revalidateUrl` to the browser client. Done when the
39
+ Revalidate Route answers 204 to a post from a signed-in tab.
40
+ 7. **Check the instance count.** With more than one instance, configure a
41
+ shared cache handler and its `"use cache: <kind>"`. Done when the deploy has
42
+ one instance, or a shared handler with `refreshTags`.
43
+ 8. **Verify.** Run the app type-check and `next build`. Write a record through
44
+ the SDK, then read it through the cached function. Done when the build
45
+ passes and the read shows the new value.