promptgun 0.12.1 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,10 +3,6 @@
3
3
  The simplest, most advanced LLM prompting library.
4
4
 
5
5
  # How to use
6
- ### Text output – single
7
- ```typescript
8
- const fruit = await ai.chat('What company makes the iPhone?')
9
- ```
10
6
  ### Text output – streamed
11
7
  ```typescript
12
8
  const stream = ai.chat('How to make bread?')
@@ -15,53 +11,57 @@ for await (const chunk of stream) {
15
11
  recipe += chunk
16
12
  }
17
13
  ```
18
-
19
- ### Data output - single
14
+ ### Text output – single
20
15
  ```typescript
21
- const restaurants /* type: {name: string, address?: string}[] */ = await ai
22
- .chat('Give 5 top restaurants in London')
23
- .getArray(o => o
24
- .object(o => o
25
- .hasString('name')
26
- .canHaveString('description', 'A 50 character description')
27
- )
28
- )
16
+ const fruit = await ai.chat('What company makes the iPhone?')
29
17
  ```
30
- Promptgun will
31
- * tell the LLM what shape its output data should be,
32
- * parse that data to JS types,
33
- * correctly Typescript-type the output and
34
- * pass your optional hints!
35
18
 
36
- ### Data output - stream
37
- Stream data-aware. Put callbacks on elements of the result data, which get called as they come in:
19
+ ### Data output - streamed
20
+ Stream data-aware:
38
21
  ```typescript
39
- await ai
40
- .chat('Give 5 top restaurants in London')
22
+ const restaurantStream = ai
23
+ .chat('Give 5 top bars in London')
41
24
  .getArray(d => d
42
25
  .object(obj => obj
43
26
  .hasString('name')
44
- .hasString('address')
27
+ .hasString('address', /* optional hint */ 'Street and address only!')
45
28
  )
46
29
  )
47
- .onElement(async restaurantStream /* type safe */ => {
48
- console.log(await restaurantStream)
49
- })
30
+ for await (const restaurant /* type safe */ of restaurantStream) {
31
+ console.log(restaurant)
32
+ }
50
33
  ```
34
+ Note that you will see each restaurant logged as soon as the LLM outputs it.
35
+ Note that Promptgun
36
+ * told the LLM what shape its output data should be,
37
+ * parsed that data to JS types,
38
+ * reorganized the stream so that each "event" is a complete element of the requested output array,
39
+ * correctly Typescript-typed each of those output elements and
40
+ * passed your optional hints
51
41
 
52
- And iterating (not awaiting) any streamed json element simply gives the stream of accumulated partial data, "what has come in so far" as it comes in. The data is parsed for you, even as the underlying JSON that is received is incomplete.
42
+ If the output type is not an array, streaming it simply gives the stream of accumulated partial parsed JSON, "what has come in so far", as it comes in. The incomplete data is parsed for you as best as possible even as the underlying JSON that is received is incomplete.
53
43
  ```typescript
54
44
  const parsedPartialJsonStream = ai
55
- .chat('What are the top 5 restaurants in New York City?')
45
+ .chat('What is the best bar in Paris?')
46
+ .getObject(o => o
47
+ .hasString('name')
48
+ .hasString('address')
49
+ )
50
+ for await (const parsedPartialJson of parsedPartialJsonStream) {
51
+ // do stuff with parsed partial json
52
+ }
53
+ ```
54
+
55
+ ### Data output - single
56
+ ```typescript
57
+ const restaurants /* type: {name: string, address?: string}[] */ = await ai
58
+ .chat('Give 5 top restaurants in London')
56
59
  .getArray(o => o
57
60
  .object(o => o
58
61
  .hasString('name')
59
- .hasString('address')
62
+ .canHaveString('description', 'A 50 character description')
60
63
  )
61
64
  )
62
- for await (const parsedPartialJson of parsedPartialJsonStream) {
63
- // do stuff with parsed partial json
64
- }
65
65
  ```
66
66
 
67
67
  ### Image out
package/build/index.d.ts CHANGED
@@ -765,6 +765,7 @@ export declare const AiModel: {
765
765
  */
766
766
  readonly o3_mini_2025_01_31: "o3-mini-2025-01-31";
767
767
  /**
768
+ * "OpenAI model ID: o4-mini"
768
769
  * | Attribute | Rating | Value |
769
770
  * |----------------|-----------------|----------------|
770
771
  * | Intelligence | ○○○ | Moderate |
@@ -881,7 +882,7 @@ export declare class BasicPrompt<PSArgs> implements AsyncGenerator<string>, Prom
881
882
  getString(): JsonPrompt<PSArgs, string>;
882
883
  getNumber(): JsonPrompt<PSArgs, number>;
883
884
  getObject<T_obj extends {}>(properties: (arg: TypeMemberSpec<{}>) => TypeMemberSpec<T_obj>): JsonPrompt<PSArgs, T_obj>;
884
- getArray<T_arr extends AnyJson>(element: (arg: EmptyTypeSpec<unknown>) => TypeSpec<T_arr>): JsonPrompt<PSArgs, T_arr[]>;
885
+ getArray<T_arr extends AnyJson>(element: (arg: EmptyTypeSpec<unknown>) => TypeSpec<T_arr>): JsonArrayPrompt<PSArgs, T_arr>;
885
886
  getAny(): JsonPrompt<PSArgs, AnyJson>;
886
887
  private getResponseAsString;
887
888
  }
@@ -1007,6 +1008,19 @@ export declare type ImageSize = '1024x1024' | '1536x1024' | '1024x1536' | '256x2
1007
1008
 
1008
1009
  export declare type JsonArray = AnyJson[];
1009
1010
 
1011
+ export declare class JsonArrayPrompt<PSArgs, T_arr extends AnyJson = AnyJson> extends JsonPrompt<PSArgs, T_arr[]> {
1012
+ protected readonly arrayElementGenerator: Flux<T_arr>;
1013
+ constructor(aiClient: AIClient, promptSupplier: (args: PSArgs) => Prompt, promptSupplierArgs: PSArgs, jsonTypeSupplier: ((value: EmptyTypeSpec<unknown>) => TypeSpec<T_arr[]>) | undefined, callingCodeLine: CodeLine, promptName: string | undefined, _temperature: number | undefined, _topP: number | undefined, _model: AiModelId | undefined);
1014
+ next(...[value]: [] | [any]): Promise<IteratorResult<T_arr>>;
1015
+ return(value: any): Promise<IteratorResult<T_arr, any>>;
1016
+ throw(e: any): Promise<IteratorResult<T_arr, any>>;
1017
+ [Symbol.asyncIterator](): AsyncGenerator<T_arr, any, any>;
1018
+ then<TResult1 = T_arr[], TResult2 = never>(onfulfilled?: ((value: T_arr[]) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): Promise<TResult1 | TResult2>;
1019
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined): Promise<T_arr[] | TResult>;
1020
+ finally(onfinally?: (() => void) | null | undefined): Promise<T_arr[]>;
1021
+ get [Symbol.toStringTag](): string;
1022
+ }
1023
+
1010
1024
  export declare type JsonExcerpt = {
1011
1025
  token?: Token;
1012
1026
  source?: string;
@@ -1017,17 +1031,17 @@ export declare type JsonObject = {
1017
1031
  };
1018
1032
 
1019
1033
  export declare class JsonPrompt<PSArgs, Json extends AnyJson = AnyJson> extends StreamedJsonChildElement<Json> implements AsyncGenerator<AnyJson>, Promise<Json> {
1020
- private aiClient;
1021
- private promptSupplier;
1022
- private promptSupplierArgs;
1023
- private jsonTypeSupplier;
1024
- private callingCodeLine;
1025
- private promptName;
1026
- private _temperature;
1027
- private _topP;
1028
- private _model;
1029
- private readonly stringGenerator;
1030
- private readonly partialJsonGenerator;
1034
+ protected aiClient: AIClient;
1035
+ protected promptSupplier: (args: PSArgs) => Prompt;
1036
+ protected promptSupplierArgs: PSArgs;
1037
+ protected jsonTypeSupplier: ((value: EmptyTypeSpec<unknown>) => TypeSpec<Json>) | undefined;
1038
+ protected callingCodeLine: CodeLine;
1039
+ protected promptName: string | undefined;
1040
+ protected _temperature: number | undefined;
1041
+ protected _topP: number | undefined;
1042
+ protected _model: AiModelId | undefined;
1043
+ protected readonly stringGenerator: AsyncGenerator<string>;
1044
+ protected readonly partialJsonGenerator: AsyncGenerator<AnyJson>;
1031
1045
  constructor(aiClient: AIClient, promptSupplier: (args: PSArgs) => Prompt, promptSupplierArgs: PSArgs, jsonTypeSupplier: ((value: EmptyTypeSpec<unknown>) => TypeSpec<Json>) | undefined, callingCodeLine: CodeLine, promptName: string | undefined, _temperature: number | undefined, _topP: number | undefined, _model: AiModelId | undefined);
1032
1046
  next(...[value]: [] | [any]): Promise<IteratorResult<AnyJson, any>>;
1033
1047
  return(value: any): Promise<IteratorResult<AnyJson, any>>;
@@ -1058,8 +1072,10 @@ export declare class JsonPrompt<PSArgs, Json extends AnyJson = AnyJson> extends
1058
1072
  * but not both.
1059
1073
  */
1060
1074
  topP(topP: number): this;
1061
- private getResponse;
1062
- private getResponseAsString;
1075
+ protected getResponse(): Promise<Json>;
1076
+ private _responseAsStringPromise?;
1077
+ protected getResponseAsString(): Promise<string>;
1078
+ protected _getResponseAsString(): Promise<string>;
1063
1079
  }
1064
1080
 
1065
1081
  export declare type Message = SystemMessage | UserMessage | AssistantMessage;
package/build/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var t=Object.create,e=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.getPrototypeOf,s={}.hasOwnProperty,o=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),a=(o,a,u)=>(u=null!=o?t(n(o)):{},((t,n,o,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let o of i(n))!s.call(t,o)&&void 0!==o&&e(t,o,{get:()=>n[o],enumerable:!(a=r(n,o))||a.enumerable});return t})(!a&&o&&o.t?u:e(u,"default",{value:o,enumerable:!0}),o)),u=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=class t{generator;upstream;handleCancel;i=!1;constructor(t,e,i){let n=this;this.generator=async function*(){try{yield*t}catch(t){throw yield r,t}finally{n.i=!0}}(),this.upstream=e,this.handleCancel=i}[Symbol.asyncIterator](){return this}async next(...t){let e=await this.generator.next(t);return e.value!==r?e:await this.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}async cancel(t){if(!this.closed){if(void 0!==this.upstream)return this.upstream.cancel(t);void 0!==this.handleCancel?this.handleCancel(t):await this.throw(t)}}async then(t,e){try{let e=await this.asList();return null!=t?await t(e):e}catch(t){if(null!=e)return e(t);throw t}}async catch(t){try{return this.asList()}catch(e){if(null!=t)return t(e);throw e}}async finally(t){let e=await this.asList();return t?.(),e}get[Symbol.toStringTag](){return"Flux"}subscribe(t){let e=void 0!==t?this.doOnEach(t):this,r=()=>{e.next().then((t=>{t.done||r()})).catch((t=>{console.error(t)}))};return r(),{unsubscribe:()=>this.return()}}filter(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t)&&(yield t)}),this)}untilExcl(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){if(e(t))break;yield t}}),this)}doOnEach(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t),yield t}),this)}doAfterLast(e){let r=this,i=[];return t.constructFromGeneratorFunction((async function*(){for await(let t of r)i.push(t),yield t;await e(i)}),this)}map(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield e(t)}),this)}take(e){let r=this;return t.constructFromGeneratorFunction((async function*(){let t=0;for await(let i of r){if(t>=e){r.cancel();break}t++,yield i}}),this)}flatMap(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){let r=e(t);if(Array.isArray(r))for(let t of r)yield t;else yield await r}}),this)}transform(e){let r=e(this);return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield t}),this)}async reduce(t,e){let r=e;for await(let e of this)r=t(r,e);return r}async asList(){let t=[];for await(let e of this)t.push(e);return t}async whenComplete(){for await(let t of this);}static create(e){let r,i=[],n=[],s=!1,o=()=>{for(s=!0;n.length>0;)n.shift().resolve({done:!0,value:void 0})};return e((t=>{if(s)throw Error("Cannot push to a completed generator");n.length>0?n.shift().resolve({done:!1,value:t}):i.push(t)}),o),t.fromGenerator({[Symbol.asyncIterator](){return this},next(...t){if(r){let t=r.value;return r=void 0,Promise.reject(t)}if(i.length>0){let t=i.shift();return Promise.resolve({done:!1,value:t})}return s?Promise.resolve({done:!0,value:void 0}):new Promise(((t,e)=>{n.push({resolve:t,reject:e})}))},return:()=>(o(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r=t,n.length>0&&n.shift()?.reject(),Promise.reject(t))})}static fromArray(e){return t.fromGeneratorFunction((async function*(){for(let t of e)yield t}))}static constructFromGeneratorFunction(e,r,i){return new t(e(),r,i)}static fromGeneratorFunction(e,r){return t.constructFromGeneratorFunction(e,void 0,r)}static fromGenerator(e,r){return new t(e,void 0,r)}static fromReadableStream(e,r){return t.fromGeneratorFunction((async function*(){let t=e.getReader();try{let e;for(;!(e=await t.read()).done;)yield e.value}finally{await t.cancel()}}),r)}get closed(){return this.i}};t.Flux=e;var r={}})),l=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=u();Object.defineProperty(t,"Flux",{enumerable:!0,get:function(){return e.Flux}})})),h=a(l(),1),p=a(l(),1),c=new TextDecoder,f=class extends Error{data;httpStatus=400;constructor(t,e){let r=t.map((t=>{if(t.expectedProp)return{expectedProp:(t.path+".").replace(/^root\./,"")+t.expectedProp};if(t.expectedType)return{expectedType:t.expectedType.map(g).join(" | "),path:t.path,insteadGot:t.value};if(t.unknownProp)return{unknownProp:(t.path+".").replace(/^root\./,"")+t.unknownProp};throw Error("illegal state")}));super(e??"Value is of the wrong format: "+JSON.stringify(r,null,2)),this.data=r}};function w(t){return new _([],t)}function d(t,e,r,i){let n=e.map((e=>function(t,e,r,i){let{ignoreUnknownProps:n=!0}=i;switch(e.type){case"array":return Array.isArray(t)?0===t.length?[]:d(t[0],e.elementType,r+"[..]",i):[{expectedType:[e],path:r,value:t}];case"boolean":return"boolean"!=typeof t?[{expectedType:[e],path:r,value:t}]:[];case"undefined":return void 0===t?[]:[{expectedType:[e],path:r,value:t}];case"object":{if("object"!=typeof t||null===t)return[{expectedType:[e],path:r,value:t}];let s=[];for(let n in e.props){let o=e.props[n];if(!(n in t)){o.optional||s.push({expectedProp:n,path:r,value:t});continue}let a=o.optional?[...o.type,{type:"undefined"}]:o.type;s.push(...d(t[n],a,r+"."+n,i))}if(!n)for(let i in t)i in e.props||s.push({unknownProp:i,path:r,value:t});return s}case"string":return"string"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"null":return null===t?[]:[{expectedType:[e],path:r,value:t}];case"number":return"number"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"constant":return t!==e.value||Number.isNaN(t)?[{expectedType:[e],path:r,value:t}]:[]}}(t,e,r,i)));if(n.some((t=>0===t.length)))return[];{let e=n.flatMap((t=>t.filter((t=>void 0!==t.expectedType&&t.path===r))));return e.length>0?[{expectedType:e.flatMap((t=>t.expectedType)),path:r,value:t}]:n.flatMap((t=>t))}}var m,_=class t{type;value;constructor(t=[],e){this.type=t,this.value=e}canBeArray(e){let r=e(new t([],this.value)),i=new t([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}canBeObject(e){let r=e(new t([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}hasString(t){return this.hasProperty(t,(t=>t.canBeString()))}canHaveProperty(t,e){return this.hasProperty(t,e,!0)}hasProperty(e,r,i=!1){let n=1===this.type.length?this.type[0]:void 0;if(void 0===n||"object"!==n.type)throw Error("illegal state");let{type:s}=r(new t([],this.value));return new t([{...n,props:{...n.props,[e]:{optional:i,type:s}}}],this.value)}canBeString(){return new t([...this.type,{type:"string"}],this.value)}canBeNumber(){return new t([...this.type,{type:"number"}],this.value)}canBeBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}canBeConstant(e){return new t([...this.type,{type:"constant",value:e}],this.value)}canBeNull(){return new t([...this.type,{type:"null"}],this.value)}canBeUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}andNothingElse(t={}){let e=d(this.value,this.type,"root",t);if(e.length>0)throw new f(e,t.errorMessage);return this.value}orDefaultTo(t,e={}){return d(this.value,this.type,"root",e).length>0?t:this.value}describe(){return y(this.type)}};function y(t,e=0){if(Array.isArray(t))return t.map((t=>y(t,e))).join(" | ");switch(t.type){case"array":return y(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":return"{\n"+Object.keys(t.props).map((r=>`${v(e+1)}${r}: ${y(t.props[r].type,e+1)}`)).join(",\n")+`\n${v(e)}}`;case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function v(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function g(t){return"constant"===t.type?`'${t.value}'`:t.type}import{config as b}from"dotenv";function A(){if(!m){b();let t=function(){let t="t";t+="ps",t="ht"+t,t+=":",t+="/",t+="/ap",t+="i.pr";let e="i";return e="d.a"+e,e="gri"+e,t+="ompt",t+e}();m=w(t).canBeString().andNothingElse({errorMessage:"PromptGrid API URL invalid: "+t})}return m}var E=class{constructor(t,e,r,i,n=!1){this.type=t,this.source=e,this.value=r,this.fieldName=i,this.maybeIncomplete=n}},T=class t{jsonBuffer="";highestOffsetParsed=-1;static toJsonTokenFlux(e){return(new t).processDataBuffer(e)}processDataBuffer(t){return t.flatMap((t=>this.getExcerpts(t)))}getExcerpts(t){this.jsonBuffer+=t;let e,r=[],i=new U(this.jsonBuffer);for(;e=this.nextToken(i);)i.currentTokenLocation().getCharOffset()>this.highestOffsetParsed&&(r.push({token:e}),this.highestOffsetParsed=i.currentTokenLocation().getCharOffset());return r.push({source:t}),r}nextToken(t){let e=t.nextToken();return"string"!=typeof e?e:void 0}},U=class{constructor(t){this.content=t}position=0;currentTokenType;parentFieldName;currentValue=null;nextToken(){let t=this.position;if(this.position>=this.content.length)return"string-ended";for(;this.position<this.content.length&&/\s/.test(this.content[this.position]);)this.position++;if(this.position>=this.content.length)return"string-ended";let e=t=>{let e=t;for(;e<this.content.length&&/\s/.test(this.content[e]);)e++;return","===this.content[e]?e+1:void 0},r=e=>this.content.substring(t,e),i=this.content[this.position];switch(i){case"{":return this.position++,this.currentTokenType="START_OBJECT",new E(this.currentTokenType,r(this.position),void 0,this.parentFieldName);case"}":{this.position++,this.currentTokenType="END_OBJECT",this.position=e(this.position)??this.position;let t=new E(this.currentTokenType,r(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,t}case"[":return this.position++,this.currentTokenType="START_ARRAY",new E(this.currentTokenType,r(this.position),void 0,this.parentFieldName);case"]":{this.position++,this.currentTokenType="END_ARRAY",this.position=e(this.position)??this.position;let t=new E(this.currentTokenType,r(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,t}case'"':let t=++this.position,n=this.content.indexOf('"',t);for(;n>0&&"\\"===this.content[n-1];)n=this.content.indexOf('"',n+1);if(-1===n)return"token-incomplete";let s=this.content.substring(t,n);this.position=n+1;let o=this.position;for(;o<this.content.length&&/\s/.test(this.content[o]);)o++;if(this.currentTokenType=o<this.content.length&&":"===this.content[o]?"FIELD_NAME":"VALUE_STRING","FIELD_NAME"===this.currentTokenType){this.position=o+1,this.position=e(this.position)??this.position;let t=new E(this.currentTokenType,r(this.position),s,void 0);return this.parentFieldName=s,t}{this.currentValue=s,this.position=e(this.position)??this.position;let t=new E(this.currentTokenType,r(this.position),s,"VALUE_STRING"===this.currentTokenType?this.parentFieldName:void 0);return this.parentFieldName=void 0,t}case"t":{let t=this.content.substring(this.position,this.position+4);if("true"===t)return this.position+=4,this.position=e(this.position)??this.position,this.currentTokenType="VALUE_TRUE",this.currentValue=!0,new E(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}case"f":{let t=this.content.substring(this.position,this.position+5);if("false"===t)return this.position+=5,this.position=e(this.position)??this.position,this.currentTokenType="VALUE_FALSE",this.currentValue=!1,new E(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName);if(t.length<5)return"token-incomplete";break}case"n":{let t=this.content.substring(this.position,this.position+4);if("null"===t)return this.position+=4,this.position=e(this.position)??this.position,this.currentTokenType="VALUE_NULL",this.currentValue=null,new E(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}default:if(/[0-9-]/.test(i)){let t="",i=!1;for(;this.position<this.content.length&&(/[0-9]/.test(this.content[this.position])||"-"===this.content[this.position]||"."===this.content[this.position]||"e"===this.content[this.position]||"E"===this.content[this.position]||"+"===this.content[this.position]);)"."===this.content[this.position]&&(i=!0),t+=this.content[this.position++];i?(this.currentTokenType="VALUE_NUMBER_FLOAT",this.currentValue=parseFloat(t)):(this.currentTokenType="VALUE_NUMBER_INT",this.currentValue=parseInt(t,10));let n=this.position>=this.content.length;return this.position=e(this.position)??this.position,new E(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName,n)}}throw new N("Invalid JSON at position "+this.position)}currentTokenLocation(){return{getCharOffset:()=>this.position}}},N=class extends Error{constructor(t){super(t),this.name="JsonParseException"}},L=a(l(),1);function S(t){return null!=t}var x=class{receivedJson=[];propertyCallbacks=new Map;onElementCallbacks=new Set;onCompleteCallbacks=new Set;onEachExcerptCallbacks=new Set;currentToken;state=new O;receivedExcerpts=[];onElement(t){return this.onElementCallbacks.add(t),this}onProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push(e),this}onJsonStringProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push((t=>{let r=new j,i=[],n=new F;t.onEachExcerpt((t=>{void 0!==t.source&&i.push(t.source);let e=i.join(""),s=this.endsOnUnevenNumberOfBackslashes(e)?e.substring(0,e.length-1):e;i.length=0;let o=s.replace(/\\"/g,'"').substring(1),a=null!=t.token?o.substring(0,o.length-1):o;r.getExcerpts(a).forEach((t=>n.push(t)))})),e(n)})),this}onEachExcerpt(t){return this.onEachExcerptCallbacks.add(t),this.receivedExcerpts.forEach(t),this}async then(t,e){try{let e=await this.getResponseAsPromise();return S(t)?await t(e):e}catch(t){if(S(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsPromise()}catch(e){if(S(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsPromise()}finally{t?.()}}get[Symbol.toStringTag](){return"StreamedJsonElement"}getResponseAsPromise(){return new Promise((t=>{this.onCompleteAs(t)}))}onComplete(t){this.o(this.toAsync(t),void 0)}o(t,e){this.onCompleteCallbacks.add({consumer:t,expectedTokenType:e})}onCompleteAsync(t){this.o(t,void 0)}onCompleteAs(t){this.onCompleteAsAsync(this.toAsync(t))}onCompleteAsAsync(t){this.o((e=>{let r=JSON.parse(e.replace(/,$/,""));return t(r)}),void 0)}onCompleteAsString(t){this.o(this.toAsync(t),new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsStringAsync(t){this.o(t,new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsInt(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsIntAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsNumber(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsNumberAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsBoolean(t){this.o(this.toAsync(t),new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}onCompleteAsBooleanAsync(t){this.o(t,new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}whenComplete(){return new Promise((t=>{this.onComplete((e=>t(e)))}))}asJsonFlux(){return L.Flux.create(((t,e)=>{this.onEachExcerpt((e=>{e.source&&t(e.source)})),this.o((async()=>e()))}))}whenCompleteAs(){return new Promise((t=>{this.onCompleteAs(t)}))}async push(t){let e=t.token;if(this.onEachExcerptCallbacks.forEach((e=>e(t))),this.isState(R))return this.state.child.push(t);if(!e)return;let r=e.type;if(this.currentToken=e,this.isState(O))switch(r){case"START_OBJECT":if(this.onElementCallbacks.size>0)throw Error("registered onElement for object");return this.state=new C,void this.receivedJson.push(e.source);case"START_ARRAY":if(this.propertyCallbacks.size>0)throw Error("registered onProperty for array");return this.state=new I,void this.receivedJson.push(e.source);case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":return this.receivedJson.push(e.source),this.end();default:throw new B(e)}else if(this.isState(C))switch(r){case"FIELD_NAME":return void this.receivedJson.push(e.source);case"END_OBJECT":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let r=new F;return r.onComplete((t=>{this.receivedJson.push(t),this.state=new C})),this.state=new V(r),this.propertyCallbacks.get(e.fieldName)?.forEach((t=>t(r))),r.push(t)}default:throw new B(e)}else if(this.isState(I))switch(r){case"END_ARRAY":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let e=new F;return e.onComplete((t=>{this.receivedJson.push(t),this.state=new I})),this.onElementCallbacks.forEach((t=>t(e))),this.state=new k(e),e.push(t)}default:throw new B(e)}throw Error("Unknown state")}async end(){if(void 0===this.currentToken)throw Error("Illegal state");this.onCompleteCallbacks.forEach((t=>{let e=t.expectedTokenType,r=(()=>{if(void 0===e)return this.receivedJson.join("");if(!e.has(this.currentToken.type))throw Error(`Expected token type ${Array.from(e).join(", ")} but got ${this.currentToken.type}`);return this.currentToken.value})();t.consumer(r)}))}isState(t){return this.state instanceof t}endsOnUnevenNumberOfBackslashes(t){let e=0;for(let r=t.length-1;r>=0&&"\\"===t[r];r--)e++;return e%2==1}toAsync(t){return async e=>{t(e)}}},P=class{},R=class extends P{constructor(t){super(),this.child=t}},O=class extends P{},I=class extends P{},k=class extends R{constructor(t){super(t)}},C=class extends P{},V=class extends R{constructor(t){super(t)}},B=class extends Error{constructor(t){super("Unexpected token: "+t.type),this.name="UnexpectedTokenException"}},j=class{getExcerpts(t){return[{source:t}]}},F=class extends x{constructor(){super()}},J=a(l(),1),$=class extends x{jsonTokenFlux;constructor(t){super();let e=this;this.jsonTokenFlux=J.Flux.fromGeneratorFunction((async function*(){let r;for await(let i of t)void 0!==i.token&&(r?.token?.maybeIncomplete&&r.token.type===i.token.type&&!i.token.maybeIncomplete&&await e.push(i),r=i.token),(void 0===i.token||!i.token.maybeIncomplete)&&await e.push(i),yield i;r?.token?.maybeIncomplete&&await e.push(r)}))}whenComplete(){return this.jsonTokenFlux.then((()=>this.receivedJson.join("")))}asJsonFlux(){return this.jsonTokenFlux.map((t=>t.source)).filter((t=>void 0!==t))}},M=class{parse(t){return new $(t)}};function G(t){try{return JSON.parse(t)}catch(e){throw Error(`Failed to parse JSON with error '${e.message}'. JSON was: ${t}`)}}function D(t){if(""===t.trim())return;let e=[],r=!1,i=t=>e.push(t),n=(...t)=>{let r=e[e.length-1];if(void 0===r||!t.includes(r))throw Error("illegal state");e.pop()},s=()=>Error(`Illegal state (json: ${t})`);for(let o of t){let t=e.length>0?e[e.length-1]:null,a=!1;if('"'===o)if(null===t)i('"value');else if("["===t||null===t)i('"value');else if("{"===t)i('"prop');else if('"prop":'===t)n('"prop":'),i('"value');else if('"prop'===t)r||(n('"prop'),i('"prop"'));else{if('"value'!==t)throw s();r||n('"value')}else if("["===o){if("["===t||null===t)i("[");else if('"prop":'===t)n('"prop":'),i("[");else if('"prop'!==t&&'"value'!==t)throw s()}else if("{"===o){if(null===t||"["===t||'"prop":'===t)i("{");else if('"prop'!==t&&'"value'!==t)throw s()}else if("\\"===o){if('"prop'!==t&&'"value'!==t)throw s();r||(a=!0)}else if(":"===o){if('"prop"'===t)n('"prop"'),i('"prop":');else if('"prop'!==t&&'"value'!==t)throw s()}else if("n"===o){if('"prop":'===t)n('"prop":'),i("n");else if("["===t||null===t)i("n");else if('"prop'!==t&&'"value'!==t)throw s()}else if("u"===o){if("n"===t)n("n"),i("nu");else if("tr"===t)n("tr"),i("tru");else if('"prop'!==t&&'"value'!==t)throw s()}else if("l"===o){if("nu"===t)n("nu"),i("nul");else if("nul"===t)n("nul");else if("fa"===t)n("fa"),i("fal");else if('"prop'!==t&&'"value'!==t)throw s()}else if("t"===o){if('"prop":'===t)n('"prop":'),i("t");else if('"prop'!==t&&'"value'!==t){if("["!==t&&null!==t)throw s();i("t")}}else if("r"===o){if("t"===t)n("t"),i("tr");else if('"prop'!==t&&'"value'!==t)throw s()}else if("e"===o){if("tru"===t)n("tru");else if("fals"===t)n("fals");else if('"prop'!==t&&'"value'!==t)throw s()}else if("f"===o){if('"prop":'===t)n('"prop":'),i("f");else if('"prop'!==t&&'"value'!==t){if("["!==t&&null!==t)throw s();i("f")}}else if("a"===o){if("f"===t)n("f"),i("fa");else if('"prop'!==t&&'"value'!==t)throw s()}else if("s"===o){if("fal"===t)n("fal"),i("fals");else if('"prop'!==t&&'"value'!==t)throw s()}else if("."===o){if('"prop":'===t)n('"prop":'),i("number.");else if('"prop'!==t&&'"value'!==t)if("{"===t)i("number.");else{if("["!==t&&null!==t)throw s();i("number.")}}else if(o.match(/[0-9]/)){if("number."===t)n("number.");else if('"prop'!==t&&'"value'!==t)if('"prop":'===t)n('"prop":');else if("{"!==t&&"["!==t&&null!==t)throw s()}else if("}"===o){if("{"===t)n("{");else if("number."===t)n("number."),n("{");else if('"prop'!==t&&'"value'!==t)throw s()}else if("]"===o){if("["===t)n("[");else if('"prop'!==t&&'"value'!==t)throw s()}else","===o&&"number."===t&&n("number.");r=a}let o=e.reverse().map((t=>{switch(t){case"{":return"}";case"[":return"]";case'"prop':return'": null';case'"prop"':return": null";case'"prop":':return" null";case"n":return"ull";case"nu":return"ll";case"nul":return"l";case"t":return"rue";case"tr":return"ue";case"tru":case"fals":return"e";case"f":return"alse";case"fa":return"lse";case"fal":return"se";case'"value':return'"';case"number.":return"0";default:throw s()}})).join("");return G((r?t.substring(0,t.length-1):t).replace(/( |\n|,)+$/,"")+o)}function H(t){if(void 0===t)throw Error("Value is undefined");return t}var Y=[];for(let t=0;t<256;++t)Y.push((t+256).toString(16).slice(1));import{randomFillSync as z}from"crypto";var q=new Uint8Array(256),K=q.length;import{randomUUID as Q}from"crypto";var W={randomUUID:Q},X=function(t,e,r){if(W.randomUUID&&!e&&!t)return W.randomUUID();let i=(t=t||{}).random??t.rng?.()??(K>q.length-16&&(z(q),K=0),q.slice(K,K+=16));if(i.length<16)throw Error("Random bytes length must be >= 16");if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,e){if((r=r||0)<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let t=0;t<16;++t)e[r+t]=i[t];return e}return function(t,e=0){return(Y[t[e+0]]+Y[t[e+1]]+Y[t[e+2]]+Y[t[e+3]]+"-"+Y[t[e+4]]+Y[t[e+5]]+"-"+Y[t[e+6]]+Y[t[e+7]]+"-"+Y[t[e+8]]+Y[t[e+9]]+"-"+Y[t[e+10]]+Y[t[e+11]]+Y[t[e+12]]+Y[t[e+13]]+Y[t[e+14]]+Y[t[e+15]]).toLowerCase()}(i)},Z=class extends Error{data;httpStatus=400;constructor(t,e){let r=t.map((t=>{if(t.expectedProp)return{expectedProp:(t.path+".").replace(/^root\./,"")+t.expectedProp};if(t.expectedType)return{expectedType:t.expectedType.map(ft).join(" | "),path:t.path,insteadGot:t.value};if(t.unknownProp)return{unknownProp:(t.path+".").replace(/^root\./,"")+t.unknownProp};throw Error("illegal state")}));super(e??"Value is of the wrong format: "+JSON.stringify(r,null,2)),this.data=r}};function tt(t){return new it([],t)}function et(t,e,r,i){let n=e.map((e=>function(t,e,r,i){let{ignoreUnknownProps:n=!0}=i;switch(e.type){case"array":return Array.isArray(t)?0===t.length?[]:et(t[0],e.elementType,r+"[..]",i):[{expectedType:[e],path:r,value:t}];case"boolean":return"boolean"!=typeof t?[{expectedType:[e],path:r,value:t}]:[];case"undefined":return void 0===t?[]:[{expectedType:[e],path:r,value:t}];case"object":{if("object"!=typeof t||null===t)return[{expectedType:[e],path:r,value:t}];let s=[];for(let n in e.props){let o=e.props[n];if(!(n in t)){o.optional||s.push({expectedProp:n,path:r,value:t});continue}let a=o.optional?[...o.type,{type:"undefined"}]:o.type;s.push(...et(t[n],a,r+"."+n,i))}if(!n)for(let i in t)i in e.props||s.push({unknownProp:i,path:r,value:t});return s}case"string":return"string"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"null":return null===t?[]:[{expectedType:[e],path:r,value:t}];case"number":return"number"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"constant":return t===e.value?[]:[{expectedType:[e],path:r,value:t}]}}(t,e,r,i)));if(n.some((t=>0===t.length)))return[];{let e=n.flatMap((t=>t.filter((t=>void 0!==t.expectedType&&t.path===r))));return e.length>0?[{expectedType:e.flatMap((t=>t.expectedType)),path:r,value:t}]:n.flatMap((t=>t))}}var rt=class{constructor(t,e,r=void 0){this.type=t,this.value=e,this.u=r}},it=class t extends rt{array(e){let r=e(new t([],this.value)),i=new nt([{type:"array",elementType:r.type}],this.value);return new nt([...this.type,...i.type],this.value)}object(t){let e=t(new st([{type:"object",props:{}}],this.value));return new nt([...this.type,...e.type],this.value)}string(){return new nt([...this.type,{type:"string"}],this.value)}number(){return new nt([...this.type,{type:"number"}],this.value)}boolean(){return new nt([...this.type,{type:"boolean"}],this.value)}constant(t,...e){return new ut([...this.type,{type:"constant",value:t},...(e??[]).map((t=>({type:"constant",value:t})))],this.value)}null(){return new nt([...this.type,{type:"null"}],this.value)}undefined(){return new nt([...this.type,{type:"undefined"}],this.value)}any(){return new nt([],this.value)}},nt=class t extends rt{orArray(e){let r=e(new t([],this.value)),i=new t([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new st([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}orString(){return new t([...this.type,{type:"string"}],this.value)}orNumber(){return new t([...this.type,{type:"number"}],this.value)}orBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}orConstant(t,...e){return new ut([...this.type,{type:"constant",value:t},...(e??[]).map((t=>({type:"constant",value:t})))],this.value)}orNull(){return new t([...this.type,{type:"null"}],this.value)}orUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}},st=class t{constructor(t,e){this.type=t,this.value=e}mayHave(t,e,r){return this.has(t,e,!0,r)}canHaveString(t,e){return this.mayHave(t,(t=>t.string()),e)}canHaveNumber(t,e){return this.mayHave(t,(t=>t.number()),e)}canHaveBoolean(t,e){return this.mayHave(t,(t=>t.boolean()),e)}canHaveConstant(t,[e,...r],i){return this.mayHave(t,(t=>t.constant(e,...r)),i)}has(e,r,i=!1,n){let{optional:s,comment:o}="string"==typeof i?{optional:!1,comment:i}:{optional:i,comment:n},a=1===this.type.length?this.type[0]:void 0;if(void 0===a||"object"!==a.type)throw Error("illegal state");let u=r(new at([],this.value)),l=u.type,h=u.l;return new t([{...a,props:{...a.props,[e]:{optional:s,type:l,comment:(()=>{let t=[...h,...void 0!==o?[o]:[]];return t.length>0?t.join(". "):void 0})()}}}],this.value)}hasString(t,e){return this.has(t,(t=>t.string()),!1,e)}hasNumber(t,e){return this.has(t,(t=>t.number()),!1,e)}hasBoolean(t,e){return this.has(t,(t=>t.boolean()),!1,e)}hasConstant(t,e,r,...i){let{constants:n,comment:s}=Array.isArray(e)?{constants:e,comment:r}:{constants:[e,...void 0!==r?[r]:[],...i],comment:void 0};return this.has(t,(t=>t.constant(...n)),!1,s)}},ot=class extends rt{constructor(t,e,r=[]){super(t,e),this.l=r}withComment(t){return new ut(this.type,this.value,[...this.l,t])}},at=class extends ot{array(t){let e=t(new it([],this.value)),r=new nt([{type:"array",elementType:e.type}],this.value);return new ut([...this.type,...r.type],this.value)}object(t){let e=t(new st([{type:"object",props:{}}],this.value));return new ut([...this.type,...e.type],this.value)}string(){return new ut([...this.type,{type:"string"}],this.value)}number(){return new ut([...this.type,{type:"number"}],this.value)}boolean(){return new ut([...this.type,{type:"boolean"}],this.value)}constant(...t){return new ut([...this.type,...t.map((t=>({type:"constant",value:t})))],this.value)}null(){return new ut([...this.type,{type:"null"}],this.value)}undefined(){return new ut([...this.type,{type:"undefined"}],this.value)}},ut=class t extends ot{orArray(e){let r=e(new nt([],this.value)),i=new nt([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new st([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}orString(){return new t([...this.type,{type:"string"}],this.value)}orNumber(){return new t([...this.type,{type:"number"}],this.value)}orBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}orConstant(...e){return new t([...this.type,...e.map((t=>({type:"constant",value:t})))],this.value)}orNull(){return new t([...this.type,{type:"null"}],this.value)}orUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}};function lt(t,e,r={}){let i=et(t,e.type,"root",r);if(i.length>0)throw new Z(i,r.errorMessage);return t}function ht(t){return pt(t.type)}function pt(t,e=0){if(Array.isArray(t))return t.map((t=>pt(t,e))).join(" | ");switch(t.type){case"array":return pt(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":{let r=Object.keys(t.props);return"{\n"+r.map(((i,n)=>{let s=t.props[i],o=pt(s.type,e+1),a=n<r.length-1?",":"",u=void 0!==s.comment?" // "+s.comment:"";return s.optional?`${ct(e+1)}[${i}: ${o}${a}]${u}\n`:`${ct(e+1)}${i}: ${o}${a}${u}\n`})).join("")+ct(e)+"}"}case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function ct(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function ft(t){return"constant"===t.type?`'${t.value}'`:t.type}async function wt(t,e,r="gpt-image-1",i){let n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t},body:JSON.stringify({model:r,prompt:e,size:i})});if(!n.ok){let t=await n.json();throw Error(`OpenAI API error: ${n.status} ${JSON.stringify(t)}`)}let s=await n.json();if(!s.data?.[0]?.b64_json)throw Error("Invalid response structure from OpenAI API");return Uint8Array.from(atob(s.data[0].b64_json),(t=>t.charCodeAt(0)))}import{writeFile as dt}from"fs";var mt={gpt_3_5_turbo:"gpt-3.5-turbo",gpt_3_5_turbo_0125:"gpt-3.5-turbo-0125",gpt_3_5_turbo_1106:"gpt-3.5-turbo-1106",gpt_3_5_turbo_16k:"gpt-3.5-turbo-16k",gpt_3_5_turbo_instruct:"gpt-3.5-turbo-instruct",gpt_3_5_turbo_instruct_0914:"gpt-3.5-turbo-instruct-0914",gpt_4:"gpt-4",gpt_4_0125_preview:"gpt-4-0125-preview",gpt_4_0613:"gpt-4-0613",gpt_4_1106_preview:"gpt-4-1106-preview",gpt_4_turbo:"gpt-4-turbo",gpt_4_turbo_2024_04_09:"gpt-4-turbo-2024-04-09",gpt_4_turbo_preview:"gpt-4-turbo-preview",gpt_4_1:"gpt-4.1",gpt_4_1_2025_04_14:"gpt-4.1-2025-04-14",gpt_4_1_mini:"gpt-4.1-mini",gpt_4_1_mini_2025_04_14:"gpt-4.1-mini-2025-04-14",gpt_4_1_nano:"gpt-4.1-nano",gpt_4_1_nano_2025_04_14:"gpt-4.1-nano-2025-04-14",gpt_4_5_preview:"gpt-4.5-preview",gpt_4_5_preview_2025_02_27:"gpt-4.5-preview-2025-02-27",gpt_4o:"gpt-4o",gpt_4o_2024_05_13:"gpt-4o-2024-05-13",gpt_4o_2024_08_06:"gpt-4o-2024-08-06",gpt_4o_2024_11_20:"gpt-4o-2024-11-20",gpt_4o_audio_preview:"gpt-4o-audio-preview",gpt_4o_audio_preview_2024_10_01:"gpt-4o-audio-preview-2024-10-01",gpt_4o_audio_preview_2024_12_17:"gpt-4o-audio-preview-2024-12-17",gpt_4o_mini:"gpt-4o-mini",gpt_4o_mini_2024_07_18:"gpt-4o-mini-2024-07-18",gpt_4o_mini_audio_preview:"gpt-4o-mini-audio-preview",gpt_4o_mini_audio_preview_2024_12_17:"gpt-4o-mini-audio-preview-2024-12-17",gpt_4o_mini_realtime_preview:"gpt-4o-mini-realtime-preview",gpt_4o_mini_realtime_preview_2024_12_17:"gpt-4o-mini-realtime-preview-2024-12-17",gpt_4o_mini_search_preview:"gpt-4o-mini-search-preview",gpt_4o_mini_search_preview_2025_03_11:"gpt-4o-mini-search-preview-2025-03-11",gpt_4o_mini_transcribe:"gpt-4o-mini-transcribe",gpt_4o_mini_tts:"gpt-4o-mini-tts",gpt_4o_realtime_preview:"gpt-4o-realtime-preview",gpt_4o_realtime_preview_2024_10_01:"gpt-4o-realtime-preview-2024-10-01",gpt_4o_realtime_preview_2024_12_17:"gpt-4o-realtime-preview-2024-12-17",gpt_4o_search_preview:"gpt-4o-search-preview",gpt_4o_search_preview_2025_03_11:"gpt-4o-search-preview-2025-03-11",gpt_4o_transcribe:"gpt-4o-transcribe",gpt_image_1:"gpt-image-1",o1:"o1",o1_2024_12_17:"o1-2024-12-17",o1_mini:"o1-mini",o1_mini_2024_09_12:"o1-mini-2024-09-12",o1_preview:"o1-preview",o1_preview_2024_09_12:"o1-preview-2024-09-12",o1_pro:"o1-pro",o1_pro_2025_03_19:"o1-pro-2025-03-19",o3:"o3",o3_2025_04_16:"o3-2025-04-16",o3_mini:"o3-mini",o3_mini_2025_01_31:"o3-mini-2025-01-31",o4_mini:"o4-mini",o4_mini_2025_04_16:"o4-mini-2025-04-16",omni_moderation_2024_09_26:"omni-moderation-2024-09-26",omni_moderation_latest:"omni-moderation-latest"},_t={dall_e_2:"dall-e-2",dall_e_3:"dall-e-3",gpt_image_1:"gpt-image-1"},yt=class{constructor(t,e){this.apiKeys=t,this.config=e}chat(t,e,...r){let{toPrompt:i}=(()=>{if("function"==typeof t)return{toPrompt:t,args:e};if("string"==typeof t)return{toPrompt:()=>t,args:void 0};if(Array.isArray(t)){let e=0===t.length?[{user:""}]:t;return{toPrompt:()=>e,args:void 0}}{let i=[t,...void 0!==e?[e]:[],...r],n=0===i.length?[{user:""}]:i;return{toPrompt:()=>n,args:void 0}}})();return new xt(this,i,e,kt(),void 0,void 0,void 0)}image(t){return new vt(t,void 0,void 0,this)}},vt=class{constructor(t,e,r,i){this.prompt=t,this.h=e,this.p=r,this.aiClient=i}async then(t,e){try{let e=await this.getResponseAsString();return S(t)?await t(e):e}catch(t){if(S(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(S(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsString()}finally{t?.()}}get[Symbol.toStringTag](){return"ImagePrompt"}model(t){return this.h=t,this}size(t){return this.p=t,this}toFile(t){return new gt(this.prompt,this.h,this.p,t,this.aiClient)}async getResponseAsString(){let t=w(await this.aiClient.apiKeys.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"});return await wt(t,this.prompt)}},gt=class{constructor(t,e,r,i,n){this.prompt=t,this.h=e,this.p=r,this.fileName=i,this.aiClient=n}async then(t,e){try{let e=await this.getResponseAsFile();return S(t)?await t(e):e}catch(t){if(S(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsFile()}catch(e){if(S(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsFile()}finally{t?.()}}get[Symbol.toStringTag](){return"ImageFilePrompt"}model(t){return this.h=t,this}size(t){return this.p=t,this}async getResponseAsFile(){let t=w(await this.aiClient.apiKeys.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),e=await wt(t,this.prompt,this.h,this.p);return new Promise(((t,r)=>{dt(this.fileName,e,(i=>{i?r(i):t(new File([e],this.fileName,{type:"image/png"}))}))}))}},bt=new yt(void 0,{});function At(t){let e=Tt(t);bt.apiKeys=Ut(e),bt.config=e}function Et(t){let e=Tt(t);return new yt(Ut(e),e)}function Tt(t){return{promptGridApiKey:(()=>{let e="string"==typeof t?t:t.promptGridApiKey;return lt(e,tt(e).string().orUndefined(),{errorMessage:"Please provide a valid API key; got "+e})})(),apiKeys:"object"==typeof t&&null!==t?t.apiKeys:void 0,debugMode:"object"==typeof t&&null!==t&&t.debugMode}}function Ut(t){let e=t.promptGridApiKey,r=t.apiKeys,i=void 0!==e?(async()=>{let t=await(async()=>{try{return await fetch(A()+"/handshake",{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"promptgun",Authorization:"Bearer "+e}})}catch{throw Error("HTTP called failed when doing handshake")}})();if(200!==t.status){let e=await t.text();throw Error(`Handshake failed with status ${t.status}, body: ${e}`)}return await t.json()})():void 0;return{promptgrid:e,openai:(async()=>r?.openai??(await i)?.apiKeys.openai)()}}var Nt=new Map;function Lt(t){let e=t??bt;if(void 0===e.apiKeys)throw Error("No LLM set up. Call setupPromptGun first: ```import { setupPromptGun } from 'promptgun';\n\nsetupPromptGun({openAI: \"YOUR_OPENAI_API_KEY\"});\n```");return new St(e,kt())}var St=class{constructor(t,e){this.aiClient=t,this.callingCodeLine=e}completeChat(t,e){return new xt(this.aiClient,t,e,kt(),void 0,void 0,void 0)}},xt=class{constructor(t,e,r,i,n,s,o){this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.callingCodeLine=i,this.m=n,this._=s,this.h=o;let a=this;this.generator=async function*(){yield*await Ot(a.aiClient,o,a.promptSupplier(a.promptSupplierArgs),!1,a.promptName,n,s,i)}()}generator;promptName;name(t){return this.promptName=t,this}model(t){return this.h=t,this}temperature(t){return this.m=t,this}topP(t){return this._=t,this}next(...[t]){return this.generator.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async then(t,e){try{let e=await this.getResponseAsString();return S(t)?await t(e):e}catch(t){if(S(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(S(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsString()}finally{t?.()}}get[Symbol.toStringTag](){return"BasicPrompt"}get(t){return new Pt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,t,kt(),this.promptName,this.m,this._,this.h)}getBoolean(){return this.get((t=>t.boolean()))}getString(){return this.get((t=>t.string()))}getNumber(){return this.get((t=>t.number()))}getObject(t){return this.get((e=>e.object(t)))}getArray(t){return this.get((e=>e.array(t)))}getAny(){return this.get((t=>t.any()))}async getResponseAsString(){let t="";for await(let e of this)t+=e;return t}},Pt=class extends F{constructor(t,e,r,i,n,s,o,a,u){let l=async function*(){yield*await Ot(t,u,e(r),void 0===i||i(tt(void 0)),s,o,a,n)}(),p=h.Flux.fromGenerator(l),c=(new T).processDataBuffer(p);super(),this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.jsonTypeSupplier=i,this.callingCodeLine=n,this.promptName=s,this.m=o,this._=a,this.h=u;let f=this,w=(new M).parse(c);void 0!==i?w.onProperty("result",(t=>t.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)})))):w.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)})),this.stringGenerator=async function*(){for await(let t of c)void 0!==t.token?w.push(t):void 0!==t.source&&(yield t.source)}(),this.partialJsonGenerator=async function*(){let t="";for await(let e of f.stringGenerator){t+=e;let r=D(t);yield void 0!==i?r?.result:r}}()}stringGenerator;partialJsonGenerator;next(...[t]){return this.partialJsonGenerator.next(t)}return(t){return this.partialJsonGenerator.return(t)}throw(t){return this.partialJsonGenerator.throw(t)}[Symbol.asyncIterator](){return this.partialJsonGenerator}async then(t,e){try{let e=await this.getResponse();return S(t)?await t(e):e}catch(t){if(S(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(S(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"BasicPrompt"}name(t){return this.promptName=t,this}model(t){return this.h=t,this}temperature(t){return this.m=t,this}topP(t){return this._=t,this}async getResponse(){let t=await this.getResponseAsString(),e=this.jsonTypeSupplier,r=G(t),i=void 0!==e?r?.result:r;if(void 0===e)return i;try{return lt(i,e(tt(i)))}catch{return console.debug('AI forgot to pack result in {"result": ...} wrapper, continuing by using complete result'),lt(r,e(tt(i)))}}async getResponseAsString(){let t="";for await(let e of this.stringGenerator)t+=e;return t}};function Rt(t){return t??"gpt-4o"}async function*Ot(t,e,r,i,n,s,o,a){let u=new Map;try{let l=w(await t.apiKeys.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),h=function(t){let e=t=>({role:void 0!==t.user?"user":void 0!==t.system?"system":"assistant",content:H(t.user??t.system??t.assistant)});return"string"==typeof t?[{role:"user",content:t}]:Array.isArray(t)?t.map(e):[e(t)]}(r),f=(()=>{if(!i)return h;let t=(()=>{let t=h.length-1;for(;t>=0&&"user"===h[t].role;)t--;return t})();return[...h.slice(0,t+1),{role:"system",content:It(0,i)},...h.slice(t+1)]})(),{fileName:d,lineNumber:m}=a;if(d&&void 0!==m&&Array.from(Nt.keys()).filter((t=>t.startsWith(d+":"))).map((t=>parseInt(t.split(":")[1],10))).length>1&&!n)throw Error(`Multiple prompts found in ${d}. Please specify a name using .name() method.`);let _={id:n,callingCodeLine:a},y=X(),v={},g=(e,r)=>{let i=X(),n=async()=>{v.currentSave=v.save,v.save=void 0,await async function(t,e){try{if(void 0===e)return;let r=await fetch(A()+"/api/conversations",{method:"PUT",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e},body:JSON.stringify(t)});if(!r.ok)throw Error(`Got ${r.status} when attempting to save conversation, with body: ${await r.text()}`)}catch(t){console.error("Error saving conversation",t)}}(e,t.apiKeys.promptgrid),await new Promise((t=>setTimeout(t,100))),await(v.save?.callback()),v.currentSave=void 0};void 0!==v.save&&u.delete(v.save.uuid),v.save={uuid:i,callback:n},void 0===v.currentSave&&u.set(i,{chunk:r,promise:n().then()})};g({conversationUuid:y,prompt:_,messages:f.map((t=>({messageUuid:X(),role:t.role,content:t.content||""})))});let b=X();g({conversationUuid:y,prompt:_,messages:[{messageUuid:b,role:"assistant",content:""}]});let E=function({model:t,prompt:e,apiToken:r,temperature:i,topP:n,requireJsonResponse:s}){return p.Flux.fromGeneratorFunction((async function*(){let o=new AbortController,a=await fetch("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:"Bearer "+r},method:"POST",signal:o.signal,body:JSON.stringify({model:t,messages:e,stream:!0,temperature:i,top_p:n,response_format:s?{type:"json_object"}:void 0})});if(a.status<200||a.status>=300){let t=function(t){try{return JSON.parse(t).error.message}catch{return t}}(await a.text());throw Error("OpenAPI reported: "+t)}if(null===a.body)throw Error("illegal state");let u="";yield*p.Flux.fromReadableStream(a.body,(()=>o.abort())).map((t=>c.decode(t,{stream:!0}))).flatMap((t=>t.replaceAll("data: [DONE]","").replace(/^data: /,"").split("data: "))).map((t=>t.replace(/[\n ]*$/,"").trim())).flatMap((t=>{u+=t;try{let t=JSON.parse(u);return u="",[t]}catch{return console.error("Received partial json chunk: "+t),[]}})).map((t=>t.choices[0])).untilExcl((t=>null!=t.finish_reason)).map((t=>t.delta.content)).filter((t=>void 0!==t))}))}({model:Rt(e),prompt:f,apiToken:l,temperature:s,topP:o,requireJsonResponse:!1!==i}),T="";yield*E.doOnEach((t=>{T+=t,g({conversationUuid:y,prompt:_,messages:[{messageUuid:b,role:"assistant",content:T}]},t)}))}finally{if(t.config.debugMode){let t=Array.from(u.values()).map((t=>t.promise));await Promise.all(t)}}}function It(t,e){{if(!0===e)return"Respond with JSON";let t=e;return"Respond with JSON matching the Typescript-style type spec below, noting\n- when a value can be null if stated explicitly, e.g. 'string | null'\n- an optional property (denoted with squared brackets) is achieved in JSON by not including it, not by setting it to null\n\nThe type:\n"+ht(new it([],void 0).object((e=>e.has("result",(()=>new ut(t.type,t.value))))))}}function kt(){let t=(Error().stack??"").split("\n").map((t=>t.trim())).filter((t=>t.startsWith("at ")))[2],e=t.match(/[^(]+\([^)]+\)/),{functionName:r,fileName:i,lineNumber:n}=e?t.match("at (?<functionName>[^(]*) ((?<scheme>.*://)?(?<fileName>[^:]*):(?<lineNumber>[0-9]+):(?<colNumber>[0-9]+))").groups:t.match("at (?<scheme>.*://)?(?<fileName>[^:]*):(?<lineNumber>[0-9]+):(?<colNumber>[0-9]+)").groups;return{stacktraceFrame:w(t).canBeString().andNothingElse(),fileName:w(i).canBeString().andNothingElse(),lineNumber:w(parseInt(n)).canBeNumber().andNothingElse(),functionName:w(r).canBeString().canBeUndefined().andNothingElse()}}export{yt as AIClient,mt as AiModel,xt as BasicPrompt,at as EmptyPropTypeSpec,it as EmptyTypeSpec,ut as FullPropTypeSpec,nt as FullTypeSpec,gt as ImageFilePrompt,vt as ImagePrompt,Pt as JsonPrompt,_t as OpenaiImageModel,St as PromptBase,ot as PropTypeSpec,F as StreamedJsonChildElement,$ as StreamedJsonRootElement,st as TypeMemberSpec,rt as TypeSpec,bt as ai,kt as getCallerFileNameAndLineNumber,Et as newAIClient,Ut as obtainAiClientData,D as parsePartialJson,Lt as promptAI,At as setupAI};
1
+ var t=Object.create,e=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.getPrototypeOf,s={}.hasOwnProperty,o=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),a=(o,a,h)=>(h=null!=o?t(n(o)):{},((t,n,o,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let o of i(n))!s.call(t,o)&&void 0!==o&&e(t,o,{get:()=>n[o],enumerable:!(a=r(n,o))||a.enumerable});return t})(!a&&o&&o.t?h:e(h,"default",{value:o,enumerable:!0}),o)),h=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=class t{generator;upstream;handleCancel;i=!1;constructor(t,e,i){let n=this;this.generator=async function*(){try{yield*t}catch(t){throw yield r,t}finally{n.i=!0}}(),this.upstream=e,this.handleCancel=i}[Symbol.asyncIterator](){return this}async next(...t){let e=await this.generator.next(t);return e.value!==r?e:await this.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}async cancel(t){if(!this.closed){if(void 0!==this.upstream)return this.upstream.cancel(t);void 0!==this.handleCancel?this.handleCancel(t):await this.throw(t)}}async then(t,e){try{let e=await this.asList();return null!=t?await t(e):e}catch(t){if(null!=e)return e(t);throw t}}async catch(t){try{return this.asList()}catch(e){if(null!=t)return t(e);throw e}}async finally(t){let e=await this.asList();return t?.(),e}get[Symbol.toStringTag](){return"Flux"}subscribe(t){let e=void 0!==t?this.doOnEach(t):this,r=()=>{e.next().then((t=>{t.done||r()})).catch((t=>{console.error(t)}))};return r(),{unsubscribe:()=>this.return()}}filter(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t)&&(yield t)}),this)}untilExcl(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){if(e(t))break;yield t}}),this)}doOnEach(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)e(t),yield t}),this)}doAfterLast(e){let r=this,i=[];return t.constructFromGeneratorFunction((async function*(){for await(let t of r)i.push(t),yield t;await e(i)}),this)}map(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield e(t)}),this)}take(e){let r=this;return t.constructFromGeneratorFunction((async function*(){let t=0;for await(let i of r){if(t>=e){r.cancel();break}t++,yield i}}),this)}flatMap(e){let r=this;return t.constructFromGeneratorFunction((async function*(){for await(let t of r){let r=e(t);if(Array.isArray(r))for(let t of r)yield t;else yield await r}}),this)}transform(e){let r=e(this);return t.constructFromGeneratorFunction((async function*(){for await(let t of r)yield t}),this)}async reduce(t,e){let r=e;for await(let e of this)r=t(r,e);return r}async asList(){let t=[];for await(let e of this)t.push(e);return t}async whenComplete(){for await(let t of this);}static create(e){let r,i=[],n=[],s=!1,o=()=>{for(s=!0;n.length>0;)n.shift().resolve({done:!0,value:void 0})};return e((t=>{if(s)throw Error("Cannot push to a completed generator");n.length>0?n.shift().resolve({done:!1,value:t}):i.push(t)}),o),t.fromGenerator({[Symbol.asyncIterator](){return this},next(...t){if(r){let t=r.value;return r=void 0,Promise.reject(t)}if(i.length>0){let t=i.shift();return Promise.resolve({done:!1,value:t})}return s?Promise.resolve({done:!0,value:void 0}):new Promise(((t,e)=>{n.push({resolve:t,reject:e})}))},return:()=>(o(),Promise.resolve({done:!0,value:void 0})),throw:t=>(r=t,n.length>0&&n.shift()?.reject(),Promise.reject(t))})}static fromArray(e){return t.fromGeneratorFunction((async function*(){for(let t of e)yield t}))}static constructFromGeneratorFunction(e,r,i){return new t(e(),r,i)}static fromGeneratorFunction(e,r){return t.constructFromGeneratorFunction(e,void 0,r)}static fromGenerator(e,r){return new t(e,void 0,r)}static fromReadableStream(e,r){return t.fromGeneratorFunction((async function*(){let t=e.getReader();try{let e;for(;!(e=await t.read()).done;)yield e.value}finally{await t.cancel()}}),r)}get closed(){return this.i}};t.Flux=e;var r={}})),u=o((t=>{"use strict";Object.defineProperty(t,"t",{value:!0}),t.Flux=void 0;var e=h();Object.defineProperty(t,"Flux",{enumerable:!0,get:function(){return e.Flux}})})),l=a(u(),1),p=a(u(),1),c=new TextDecoder,f=class extends Error{data;httpStatus=400;constructor(t,e){let r=t.map((t=>{if(t.expectedProp)return{expectedProp:(t.path+".").replace(/^root\./,"")+t.expectedProp};if(t.expectedType)return{expectedType:t.expectedType.map(v).join(" | "),path:t.path,insteadGot:t.value};if(t.unknownProp)return{unknownProp:(t.path+".").replace(/^root\./,"")+t.unknownProp};throw Error("illegal state")}));super(e??"Value is of the wrong format: "+JSON.stringify(r,null,2)),this.data=r}};function w(t){return new m([],t)}function d(t,e,r,i){let n=e.map((e=>function(t,e,r,i){let{ignoreUnknownProps:n=!0}=i;switch(e.type){case"array":return Array.isArray(t)?0===t.length?[]:d(t[0],e.elementType,r+"[..]",i):[{expectedType:[e],path:r,value:t}];case"boolean":return"boolean"!=typeof t?[{expectedType:[e],path:r,value:t}]:[];case"undefined":return void 0===t?[]:[{expectedType:[e],path:r,value:t}];case"object":{if("object"!=typeof t||null===t)return[{expectedType:[e],path:r,value:t}];let s=[];for(let n in e.props){let o=e.props[n];if(!(n in t)){o.optional||s.push({expectedProp:n,path:r,value:t});continue}let a=o.optional?[...o.type,{type:"undefined"}]:o.type;s.push(...d(t[n],a,r+"."+n,i))}if(!n)for(let i in t)i in e.props||s.push({unknownProp:i,path:r,value:t});return s}case"string":return"string"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"null":return null===t?[]:[{expectedType:[e],path:r,value:t}];case"number":return"number"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"constant":return t!==e.value||Number.isNaN(t)?[{expectedType:[e],path:r,value:t}]:[]}}(t,e,r,i)));if(n.some((t=>0===t.length)))return[];{let e=n.flatMap((t=>t.filter((t=>void 0!==t.expectedType&&t.path===r))));return e.length>0?[{expectedType:e.flatMap((t=>t.expectedType)),path:r,value:t}]:n.flatMap((t=>t))}}var y,m=class t{type;value;constructor(t=[],e){this.type=t,this.value=e}canBeArray(e){let r=e(new t([],this.value)),i=new t([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}canBeObject(e){let r=e(new t([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}hasString(t){return this.hasProperty(t,(t=>t.canBeString()))}canHaveProperty(t,e){return this.hasProperty(t,e,!0)}hasProperty(e,r,i=!1){let n=1===this.type.length?this.type[0]:void 0;if(void 0===n||"object"!==n.type)throw Error("illegal state");let{type:s}=r(new t([],this.value));return new t([{...n,props:{...n.props,[e]:{optional:i,type:s}}}],this.value)}canBeString(){return new t([...this.type,{type:"string"}],this.value)}canBeNumber(){return new t([...this.type,{type:"number"}],this.value)}canBeBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}canBeConstant(e){return new t([...this.type,{type:"constant",value:e}],this.value)}canBeNull(){return new t([...this.type,{type:"null"}],this.value)}canBeUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}andNothingElse(t={}){let e=d(this.value,this.type,"root",t);if(e.length>0)throw new f(e,t.errorMessage);return this.value}orDefaultTo(t,e={}){return d(this.value,this.type,"root",e).length>0?t:this.value}describe(){return _(this.type)}};function _(t,e=0){if(Array.isArray(t))return t.map((t=>_(t,e))).join(" | ");switch(t.type){case"array":return _(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":return"{\n"+Object.keys(t.props).map((r=>`${g(e+1)}${r}: ${_(t.props[r].type,e+1)}`)).join(",\n")+`\n${g(e)}}`;case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function g(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function v(t){return"constant"===t.type?`'${t.value}'`:t.type}import{config as b}from"dotenv";function A(){if(!y){b();let t=function(){let t="t";t+="ps",t="ht"+t,t+=":",t+="/",t+="/ap",t+="i.pr";let e="i";return e="d.a"+e,e="gri"+e,t+="ompt",t+e}();y=w(t).canBeString().andNothingElse({errorMessage:"PromptGrid API URL invalid: "+t})}return y}var E=class{constructor(t,e,r,i,n=!1){this.type=t,this.source=e,this.value=r,this.fieldName=i,this.maybeIncomplete=n}},T=class t{jsonBuffer="";highestOffsetParsed=-1;static toJsonTokenFlux(e){return(new t).processDataBuffer(e)}processDataBuffer(t){return t.flatMap((t=>this.getExcerpts(t)))}getExcerpts(t){this.jsonBuffer+=t;let e,r=[],i=new U(this.jsonBuffer);for(;e=this.nextToken(i);)i.currentTokenLocation().getCharOffset()>this.highestOffsetParsed&&(r.push({token:e}),this.highestOffsetParsed=i.currentTokenLocation().getCharOffset());return r.push({source:t}),r}nextToken(t){let e=t.nextToken();return"string"!=typeof e?e:void 0}},U=class{constructor(t){this.content=t}position=0;currentTokenType;parentFieldName;currentValue=null;nextToken(){let t=this.position;if(this.position>=this.content.length)return"string-ended";for(;this.position<this.content.length&&/\s/.test(this.content[this.position]);)this.position++;if(this.position>=this.content.length)return"string-ended";let e=t=>{let e=t;for(;e<this.content.length&&/\s/.test(this.content[e]);)e++;return","===this.content[e]?e+1:void 0},r=e=>this.content.substring(t,e),i=this.content[this.position];switch(i){case"{":return this.position++,this.currentTokenType="START_OBJECT",new E(this.currentTokenType,r(this.position),void 0,this.parentFieldName);case"}":{this.position++,this.currentTokenType="END_OBJECT",this.position=e(this.position)??this.position;let t=new E(this.currentTokenType,r(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,t}case"[":return this.position++,this.currentTokenType="START_ARRAY",new E(this.currentTokenType,r(this.position),void 0,this.parentFieldName);case"]":{this.position++,this.currentTokenType="END_ARRAY",this.position=e(this.position)??this.position;let t=new E(this.currentTokenType,r(this.position),void 0,this.parentFieldName);return this.parentFieldName=void 0,t}case'"':let t=++this.position,n=this.content.indexOf('"',t);for(;n>0&&"\\"===this.content[n-1];)n=this.content.indexOf('"',n+1);if(-1===n)return"token-incomplete";let s=this.content.substring(t,n);this.position=n+1;let o=this.position;for(;o<this.content.length&&/\s/.test(this.content[o]);)o++;if(this.currentTokenType=o<this.content.length&&":"===this.content[o]?"FIELD_NAME":"VALUE_STRING","FIELD_NAME"===this.currentTokenType){this.position=o+1,this.position=e(this.position)??this.position;let t=new E(this.currentTokenType,r(this.position),s,void 0);return this.parentFieldName=s,t}{this.currentValue=s,this.position=e(this.position)??this.position;let t=new E(this.currentTokenType,r(this.position),s,"VALUE_STRING"===this.currentTokenType?this.parentFieldName:void 0);return this.parentFieldName=void 0,t}case"t":{let t=this.content.substring(this.position,this.position+4);if("true"===t)return this.position+=4,this.position=e(this.position)??this.position,this.currentTokenType="VALUE_TRUE",this.currentValue=!0,new E(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}case"f":{let t=this.content.substring(this.position,this.position+5);if("false"===t)return this.position+=5,this.position=e(this.position)??this.position,this.currentTokenType="VALUE_FALSE",this.currentValue=!1,new E(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName);if(t.length<5)return"token-incomplete";break}case"n":{let t=this.content.substring(this.position,this.position+4);if("null"===t)return this.position+=4,this.position=e(this.position)??this.position,this.currentTokenType="VALUE_NULL",this.currentValue=null,new E(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName);if(t.length<4)return"token-incomplete";break}default:if(/[0-9-]/.test(i)){let t="",i=!1;for(;this.position<this.content.length&&(/[0-9]/.test(this.content[this.position])||"-"===this.content[this.position]||"."===this.content[this.position]||"e"===this.content[this.position]||"E"===this.content[this.position]||"+"===this.content[this.position]);)"."===this.content[this.position]&&(i=!0),t+=this.content[this.position++];i?(this.currentTokenType="VALUE_NUMBER_FLOAT",this.currentValue=parseFloat(t)):(this.currentTokenType="VALUE_NUMBER_INT",this.currentValue=parseInt(t,10));let n=this.position>=this.content.length;return this.position=e(this.position)??this.position,new E(this.currentTokenType,r(this.position),this.currentValue,this.parentFieldName,n)}}throw new N("Invalid JSON at position "+this.position)}currentTokenLocation(){return{getCharOffset:()=>this.position}}},N=class extends Error{constructor(t){super(t),this.name="JsonParseException"}},S=a(u(),1);function L(t){return null!=t}var P=class{receivedJson=[];propertyCallbacks=new Map;onElementCallbacks=new Set;onCompleteCallbacks=new Set;onEachExcerptCallbacks=new Set;currentToken;state=new O;receivedExcerpts=[];onElement(t){return this.onElementCallbacks.add(t),this}onProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push(e),this}onJsonStringProperty(t,e){return this.propertyCallbacks.has(t)||this.propertyCallbacks.set(t,[]),this.propertyCallbacks.get(t).push((t=>{let r=new j,i=[],n=new J;t.onEachExcerpt((t=>{void 0!==t.source&&i.push(t.source);let e=i.join(""),s=this.endsOnUnevenNumberOfBackslashes(e)?e.substring(0,e.length-1):e;i.length=0;let o=s.replace(/\\"/g,'"').substring(1),a=null!=t.token?o.substring(0,o.length-1):o;r.getExcerpts(a).forEach((t=>n.push(t)))})),e(n)})),this}onEachExcerpt(t){return this.onEachExcerptCallbacks.add(t),this.receivedExcerpts.forEach(t),this}async then(t,e){try{let e=await this.getResponseAsPromise();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsPromise()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsPromise()}finally{t?.()}}get[Symbol.toStringTag](){return"StreamedJsonElement"}getResponseAsPromise(){return new Promise((t=>{this.onCompleteAs(t)}))}onComplete(t){this.o(this.toAsync(t),void 0)}o(t,e){this.onCompleteCallbacks.add({consumer:t,expectedTokenType:e})}onCompleteAsync(t){this.o(t,void 0)}onCompleteAs(t){this.onCompleteAsAsync(this.toAsync(t))}onCompleteAsAsync(t){this.o((e=>{let r=JSON.parse(e.replace(/,$/,""));return t(r)}),void 0)}onCompleteAsString(t){this.o(this.toAsync(t),new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsStringAsync(t){this.o(t,new Set(["VALUE_STRING","VALUE_NULL"]))}onCompleteAsInt(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsIntAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NULL"]))}onCompleteAsNumber(t){this.o(this.toAsync(t),new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsNumberAsync(t){this.o(t,new Set(["VALUE_NUMBER_INT","VALUE_NUMBER_FLOAT","VALUE_NULL"]))}onCompleteAsBoolean(t){this.o(this.toAsync(t),new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}onCompleteAsBooleanAsync(t){this.o(t,new Set(["VALUE_TRUE","VALUE_FALSE","VALUE_NULL"]))}whenComplete(){return new Promise((t=>{this.onComplete((e=>t(e)))}))}asJsonFlux(){return S.Flux.create(((t,e)=>{this.onEachExcerpt((e=>{e.source&&t(e.source)})),this.o((async()=>e()))}))}whenCompleteAs(){return new Promise((t=>{this.onCompleteAs(t)}))}async push(t){let e=t.token;if(this.onEachExcerptCallbacks.forEach((e=>e(t))),this.isState(R))return this.state.child.push(t);if(!e)return;let r=e.type;if(this.currentToken=e,this.isState(O))switch(r){case"START_OBJECT":if(this.onElementCallbacks.size>0)throw Error("registered onElement for object");return this.state=new C,void this.receivedJson.push(e.source);case"START_ARRAY":if(this.propertyCallbacks.size>0)throw Error("registered onProperty for array");return this.state=new I,void this.receivedJson.push(e.source);case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":return this.receivedJson.push(e.source),this.end();default:throw new B(e)}else if(this.isState(C))switch(r){case"FIELD_NAME":return void this.receivedJson.push(e.source);case"END_OBJECT":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let r=new J;return r.onComplete((t=>{this.receivedJson.push(t),this.state=new C})),this.state=new V(r),this.propertyCallbacks.get(e.fieldName)?.forEach((t=>t(r))),r.push(t)}default:throw new B(e)}else if(this.isState(I))switch(r){case"END_ARRAY":return this.receivedJson.push(e.source),this.end();case"START_OBJECT":case"START_ARRAY":case"VALUE_STRING":case"VALUE_NUMBER_INT":case"VALUE_NUMBER_FLOAT":case"VALUE_TRUE":case"VALUE_FALSE":case"VALUE_NULL":{let e=new J;return e.onComplete((t=>{this.receivedJson.push(t),this.state=new I})),this.onElementCallbacks.forEach((t=>t(e))),this.state=new k(e),e.push(t)}default:throw new B(e)}throw Error("Unknown state")}async end(){if(void 0===this.currentToken)throw Error("Illegal state");this.onCompleteCallbacks.forEach((t=>{let e=t.expectedTokenType,r=(()=>{if(void 0===e)return this.receivedJson.join("");if(!e.has(this.currentToken.type))throw Error(`Expected token type ${Array.from(e).join(", ")} but got ${this.currentToken.type}`);return this.currentToken.value})();t.consumer(r)}))}isState(t){return this.state instanceof t}endsOnUnevenNumberOfBackslashes(t){let e=0;for(let r=t.length-1;r>=0&&"\\"===t[r];r--)e++;return e%2==1}toAsync(t){return async e=>{t(e)}}},x=class{},R=class extends x{constructor(t){super(),this.child=t}},O=class extends x{},I=class extends x{},k=class extends R{constructor(t){super(t)}},C=class extends x{},V=class extends R{constructor(t){super(t)}},B=class extends Error{constructor(t){super("Unexpected token: "+t.type),this.name="UnexpectedTokenException"}},j=class{getExcerpts(t){return[{source:t}]}},J=class extends P{constructor(){super()}},F=a(u(),1),$=class extends P{jsonTokenFlux;constructor(t){super();let e=this;this.jsonTokenFlux=F.Flux.fromGeneratorFunction((async function*(){let r;for await(let i of t)void 0!==i.token&&(r?.token?.maybeIncomplete&&r.token.type===i.token.type&&!i.token.maybeIncomplete&&await e.push(i),r=i.token),(void 0===i.token||!i.token.maybeIncomplete)&&await e.push(i),yield i;r?.token?.maybeIncomplete&&await e.push(r)}))}whenComplete(){return this.jsonTokenFlux.then((()=>this.receivedJson.join("")))}asJsonFlux(){return this.jsonTokenFlux.map((t=>t.source)).filter((t=>void 0!==t))}},M=class{parse(t){return new $(t)}};function G(t){try{return JSON.parse(t)}catch(e){throw Error(`Failed to parse JSON with error '${e.message}'. JSON was: ${t}`)}}function D(t){if(""===t.trim())return;let e=[],r=!1,i=t=>e.push(t),n=(...t)=>{let r=e[e.length-1];if(void 0===r||!t.includes(r))throw Error("illegal state");e.pop()},s=()=>Error(`Illegal state (json: ${t})`);for(let o of t){let t=e.length>0?e[e.length-1]:null,a=!1;if('"'===o)if(null===t)i('"value');else if("["===t||null===t)i('"value');else if("{"===t)i('"prop');else if('"prop":'===t)n('"prop":'),i('"value');else if('"prop'===t)r||(n('"prop'),i('"prop"'));else{if('"value'!==t)throw s();r||n('"value')}else if("["===o){if("["===t||null===t)i("[");else if('"prop":'===t)n('"prop":'),i("[");else if('"prop'!==t&&'"value'!==t)throw s()}else if("{"===o){if(null===t||"["===t||'"prop":'===t)i("{");else if('"prop'!==t&&'"value'!==t)throw s()}else if("\\"===o){if('"prop'!==t&&'"value'!==t)throw s();r||(a=!0)}else if(":"===o){if('"prop"'===t)n('"prop"'),i('"prop":');else if('"prop'!==t&&'"value'!==t)throw s()}else if("n"===o){if('"prop":'===t)n('"prop":'),i("n");else if("["===t||null===t)i("n");else if('"prop'!==t&&'"value'!==t)throw s()}else if("u"===o){if("n"===t)n("n"),i("nu");else if("tr"===t)n("tr"),i("tru");else if('"prop'!==t&&'"value'!==t)throw s()}else if("l"===o){if("nu"===t)n("nu"),i("nul");else if("nul"===t)n("nul");else if("fa"===t)n("fa"),i("fal");else if('"prop'!==t&&'"value'!==t)throw s()}else if("t"===o){if('"prop":'===t)n('"prop":'),i("t");else if('"prop'!==t&&'"value'!==t){if("["!==t&&null!==t)throw s();i("t")}}else if("r"===o){if("t"===t)n("t"),i("tr");else if('"prop'!==t&&'"value'!==t)throw s()}else if("e"===o){if("tru"===t)n("tru");else if("fals"===t)n("fals");else if('"prop'!==t&&'"value'!==t)throw s()}else if("f"===o){if('"prop":'===t)n('"prop":'),i("f");else if('"prop'!==t&&'"value'!==t){if("["!==t&&null!==t)throw s();i("f")}}else if("a"===o){if("f"===t)n("f"),i("fa");else if('"prop'!==t&&'"value'!==t)throw s()}else if("s"===o){if("fal"===t)n("fal"),i("fals");else if('"prop'!==t&&'"value'!==t)throw s()}else if("."===o){if('"prop":'===t)n('"prop":'),i("number.");else if('"prop'!==t&&'"value'!==t)if("{"===t)i("number.");else{if("["!==t&&null!==t)throw s();i("number.")}}else if(o.match(/[0-9]/)){if("number."===t)n("number.");else if('"prop'!==t&&'"value'!==t)if('"prop":'===t)n('"prop":');else if("{"!==t&&"["!==t&&null!==t)throw s()}else if("}"===o){if("{"===t)n("{");else if("number."===t)n("number."),n("{");else if('"prop'!==t&&'"value'!==t)throw s()}else if("]"===o){if("["===t)n("[");else if('"prop'!==t&&'"value'!==t)throw s()}else","===o&&"number."===t&&n("number.");r=a}let o=e.reverse().map((t=>{switch(t){case"{":return"}";case"[":return"]";case'"prop':return'": null';case'"prop"':return": null";case'"prop":':return" null";case"n":return"ull";case"nu":return"ll";case"nul":return"l";case"t":return"rue";case"tr":return"ue";case"tru":case"fals":return"e";case"f":return"alse";case"fa":return"lse";case"fal":return"se";case'"value':return'"';case"number.":return"0";default:throw s()}})).join("");return G((r?t.substring(0,t.length-1):t).replace(/( |\n|,)+$/,"")+o)}function H(t){if(void 0===t)throw Error("Value is undefined");return t}var Y=[];for(let t=0;t<256;++t)Y.push((t+256).toString(16).slice(1));import{randomFillSync as z}from"crypto";var q=new Uint8Array(256),K=q.length;import{randomUUID as Q}from"crypto";var W={randomUUID:Q},X=function(t,e,r){if(W.randomUUID&&!e&&!t)return W.randomUUID();let i=(t=t||{}).random??t.rng?.()??(K>q.length-16&&(z(q),K=0),q.slice(K,K+=16));if(i.length<16)throw Error("Random bytes length must be >= 16");if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,e){if((r=r||0)<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let t=0;t<16;++t)e[r+t]=i[t];return e}return function(t,e=0){return(Y[t[e+0]]+Y[t[e+1]]+Y[t[e+2]]+Y[t[e+3]]+"-"+Y[t[e+4]]+Y[t[e+5]]+"-"+Y[t[e+6]]+Y[t[e+7]]+"-"+Y[t[e+8]]+Y[t[e+9]]+"-"+Y[t[e+10]]+Y[t[e+11]]+Y[t[e+12]]+Y[t[e+13]]+Y[t[e+14]]+Y[t[e+15]]).toLowerCase()}(i)},Z=class extends Error{data;httpStatus=400;constructor(t,e){let r=t.map((t=>{if(t.expectedProp)return{expectedProp:(t.path+".").replace(/^root\./,"")+t.expectedProp};if(t.expectedType)return{expectedType:t.expectedType.map(ft).join(" | "),path:t.path,insteadGot:t.value};if(t.unknownProp)return{unknownProp:(t.path+".").replace(/^root\./,"")+t.unknownProp};throw Error("illegal state")}));super(e??"Value is of the wrong format: "+JSON.stringify(r,null,2)),this.data=r}};function tt(t){return new it([],t)}function et(t,e,r,i){let n=e.map((e=>function(t,e,r,i){let{ignoreUnknownProps:n=!0}=i;switch(e.type){case"array":return Array.isArray(t)?0===t.length?[]:et(t[0],e.elementType,r+"[..]",i):[{expectedType:[e],path:r,value:t}];case"boolean":return"boolean"!=typeof t?[{expectedType:[e],path:r,value:t}]:[];case"undefined":return void 0===t?[]:[{expectedType:[e],path:r,value:t}];case"object":{if("object"!=typeof t||null===t)return[{expectedType:[e],path:r,value:t}];let s=[];for(let n in e.props){let o=e.props[n];if(!(n in t)){o.optional||s.push({expectedProp:n,path:r,value:t});continue}let a=o.optional?[...o.type,{type:"undefined"}]:o.type;s.push(...et(t[n],a,r+"."+n,i))}if(!n)for(let i in t)i in e.props||s.push({unknownProp:i,path:r,value:t});return s}case"string":return"string"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"null":return null===t?[]:[{expectedType:[e],path:r,value:t}];case"number":return"number"==typeof t?[]:[{expectedType:[e],path:r,value:t}];case"constant":return t===e.value?[]:[{expectedType:[e],path:r,value:t}]}}(t,e,r,i)));if(n.some((t=>0===t.length)))return[];{let e=n.flatMap((t=>t.filter((t=>void 0!==t.expectedType&&t.path===r))));return e.length>0?[{expectedType:e.flatMap((t=>t.expectedType)),path:r,value:t}]:n.flatMap((t=>t))}}var rt=class{constructor(t,e,r=void 0){this.type=t,this.value=e,this.h=r}},it=class t extends rt{array(e){let r=e(new t([],this.value)),i=new nt([{type:"array",elementType:r.type}],this.value);return new nt([...this.type,...i.type],this.value)}object(t){let e=t(new st([{type:"object",props:{}}],this.value));return new nt([...this.type,...e.type],this.value)}string(){return new nt([...this.type,{type:"string"}],this.value)}number(){return new nt([...this.type,{type:"number"}],this.value)}boolean(){return new nt([...this.type,{type:"boolean"}],this.value)}constant(t,...e){return new ht([...this.type,{type:"constant",value:t},...(e??[]).map((t=>({type:"constant",value:t})))],this.value)}null(){return new nt([...this.type,{type:"null"}],this.value)}undefined(){return new nt([...this.type,{type:"undefined"}],this.value)}any(){return new nt([],this.value)}},nt=class t extends rt{orArray(e){let r=e(new t([],this.value)),i=new t([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new st([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}orString(){return new t([...this.type,{type:"string"}],this.value)}orNumber(){return new t([...this.type,{type:"number"}],this.value)}orBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}orConstant(t,...e){return new ht([...this.type,{type:"constant",value:t},...(e??[]).map((t=>({type:"constant",value:t})))],this.value)}orNull(){return new t([...this.type,{type:"null"}],this.value)}orUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}},st=class t{constructor(t,e){this.type=t,this.value=e}mayHave(t,e,r){return this.has(t,e,!0,r)}canHaveString(t,e){return this.mayHave(t,(t=>t.string()),e)}canHaveNumber(t,e){return this.mayHave(t,(t=>t.number()),e)}canHaveBoolean(t,e){return this.mayHave(t,(t=>t.boolean()),e)}canHaveConstant(t,[e,...r],i){return this.mayHave(t,(t=>t.constant(e,...r)),i)}has(e,r,i=!1,n){let{optional:s,comment:o}="string"==typeof i?{optional:!1,comment:i}:{optional:i,comment:n},a=1===this.type.length?this.type[0]:void 0;if(void 0===a||"object"!==a.type)throw Error("illegal state");let h=r(new at([],this.value)),u=h.type,l=h.u;return new t([{...a,props:{...a.props,[e]:{optional:s,type:u,comment:(()=>{let t=[...l,...void 0!==o?[o]:[]];return t.length>0?t.join(". "):void 0})()}}}],this.value)}hasString(t,e){return this.has(t,(t=>t.string()),!1,e)}hasNumber(t,e){return this.has(t,(t=>t.number()),!1,e)}hasBoolean(t,e){return this.has(t,(t=>t.boolean()),!1,e)}hasConstant(t,e,r,...i){let{constants:n,comment:s}=Array.isArray(e)?{constants:e,comment:r}:{constants:[e,...void 0!==r?[r]:[],...i],comment:void 0};return this.has(t,(t=>t.constant(...n)),!1,s)}},ot=class extends rt{constructor(t,e,r=[]){super(t,e),this.u=r}withComment(t){return new ht(this.type,this.value,[...this.u,t])}},at=class extends ot{array(t){let e=t(new it([],this.value)),r=new nt([{type:"array",elementType:e.type}],this.value);return new ht([...this.type,...r.type],this.value)}object(t){let e=t(new st([{type:"object",props:{}}],this.value));return new ht([...this.type,...e.type],this.value)}string(){return new ht([...this.type,{type:"string"}],this.value)}number(){return new ht([...this.type,{type:"number"}],this.value)}boolean(){return new ht([...this.type,{type:"boolean"}],this.value)}constant(...t){return new ht([...this.type,...t.map((t=>({type:"constant",value:t})))],this.value)}null(){return new ht([...this.type,{type:"null"}],this.value)}undefined(){return new ht([...this.type,{type:"undefined"}],this.value)}},ht=class t extends ot{orArray(e){let r=e(new nt([],this.value)),i=new nt([{type:"array",elementType:r.type}],this.value);return new t([...this.type,...i.type],this.value)}orObject(e){let r=e(new st([{type:"object",props:{}}],this.value));return new t([...this.type,...r.type],this.value)}orString(){return new t([...this.type,{type:"string"}],this.value)}orNumber(){return new t([...this.type,{type:"number"}],this.value)}orBoolean(){return new t([...this.type,{type:"boolean"}],this.value)}orConstant(...e){return new t([...this.type,...e.map((t=>({type:"constant",value:t})))],this.value)}orNull(){return new t([...this.type,{type:"null"}],this.value)}orUndefined(){return new t([...this.type,{type:"undefined"}],this.value)}};function ut(t,e,r={}){let i=et(t,e.type,"root",r);if(i.length>0)throw new Z(i,r.errorMessage);return t}function lt(t){return pt(t.type)}function pt(t,e=0){if(Array.isArray(t))return t.map((t=>pt(t,e))).join(" | ");switch(t.type){case"array":return pt(t.elementType,e)+"[]";case"boolean":return"boolean";case"undefined":return"undefined";case"object":{let r=Object.keys(t.props);return"{\n"+r.map(((i,n)=>{let s=t.props[i],o=pt(s.type,e+1),a=n<r.length-1?",":"",h=void 0!==s.comment?" // "+s.comment:"";return s.optional?`${ct(e+1)}[${i}: ${o}${a}]${h}\n`:`${ct(e+1)}${i}: ${o}${a}${h}\n`})).join("")+ct(e)+"}"}case"string":return"string";case"null":return"null";case"number":return"number";case"constant":return`"${t.value}"`}}function ct(t){let e="";for(let r=0;r<t;r++)e+=" ";return e}function ft(t){return"constant"===t.type?`'${t.value}'`:t.type}async function wt(t,e,r="gpt-image-1",i){let n=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t},body:JSON.stringify({model:r,prompt:e,size:i})});if(!n.ok){let t=await n.json();throw Error(`OpenAI API error: ${n.status} ${JSON.stringify(t)}`)}let s=await n.json();if(!s.data?.[0]?.b64_json)throw Error("Invalid response structure from OpenAI API");return Uint8Array.from(atob(s.data[0].b64_json),(t=>t.charCodeAt(0)))}import{writeFile as dt}from"fs";var yt={gpt_3_5_turbo:"gpt-3.5-turbo",gpt_3_5_turbo_0125:"gpt-3.5-turbo-0125",gpt_3_5_turbo_1106:"gpt-3.5-turbo-1106",gpt_3_5_turbo_16k:"gpt-3.5-turbo-16k",gpt_3_5_turbo_instruct:"gpt-3.5-turbo-instruct",gpt_3_5_turbo_instruct_0914:"gpt-3.5-turbo-instruct-0914",gpt_4:"gpt-4",gpt_4_0125_preview:"gpt-4-0125-preview",gpt_4_0613:"gpt-4-0613",gpt_4_1106_preview:"gpt-4-1106-preview",gpt_4_turbo:"gpt-4-turbo",gpt_4_turbo_2024_04_09:"gpt-4-turbo-2024-04-09",gpt_4_turbo_preview:"gpt-4-turbo-preview",gpt_4_1:"gpt-4.1",gpt_4_1_2025_04_14:"gpt-4.1-2025-04-14",gpt_4_1_mini:"gpt-4.1-mini",gpt_4_1_mini_2025_04_14:"gpt-4.1-mini-2025-04-14",gpt_4_1_nano:"gpt-4.1-nano",gpt_4_1_nano_2025_04_14:"gpt-4.1-nano-2025-04-14",gpt_4_5_preview:"gpt-4.5-preview",gpt_4_5_preview_2025_02_27:"gpt-4.5-preview-2025-02-27",gpt_4o:"gpt-4o",gpt_4o_2024_05_13:"gpt-4o-2024-05-13",gpt_4o_2024_08_06:"gpt-4o-2024-08-06",gpt_4o_2024_11_20:"gpt-4o-2024-11-20",gpt_4o_audio_preview:"gpt-4o-audio-preview",gpt_4o_audio_preview_2024_10_01:"gpt-4o-audio-preview-2024-10-01",gpt_4o_audio_preview_2024_12_17:"gpt-4o-audio-preview-2024-12-17",gpt_4o_mini:"gpt-4o-mini",gpt_4o_mini_2024_07_18:"gpt-4o-mini-2024-07-18",gpt_4o_mini_audio_preview:"gpt-4o-mini-audio-preview",gpt_4o_mini_audio_preview_2024_12_17:"gpt-4o-mini-audio-preview-2024-12-17",gpt_4o_mini_realtime_preview:"gpt-4o-mini-realtime-preview",gpt_4o_mini_realtime_preview_2024_12_17:"gpt-4o-mini-realtime-preview-2024-12-17",gpt_4o_mini_search_preview:"gpt-4o-mini-search-preview",gpt_4o_mini_search_preview_2025_03_11:"gpt-4o-mini-search-preview-2025-03-11",gpt_4o_mini_transcribe:"gpt-4o-mini-transcribe",gpt_4o_mini_tts:"gpt-4o-mini-tts",gpt_4o_realtime_preview:"gpt-4o-realtime-preview",gpt_4o_realtime_preview_2024_10_01:"gpt-4o-realtime-preview-2024-10-01",gpt_4o_realtime_preview_2024_12_17:"gpt-4o-realtime-preview-2024-12-17",gpt_4o_search_preview:"gpt-4o-search-preview",gpt_4o_search_preview_2025_03_11:"gpt-4o-search-preview-2025-03-11",gpt_4o_transcribe:"gpt-4o-transcribe",gpt_image_1:"gpt-image-1",o1:"o1",o1_2024_12_17:"o1-2024-12-17",o1_mini:"o1-mini",o1_mini_2024_09_12:"o1-mini-2024-09-12",o1_preview:"o1-preview",o1_preview_2024_09_12:"o1-preview-2024-09-12",o1_pro:"o1-pro",o1_pro_2025_03_19:"o1-pro-2025-03-19",o3:"o3",o3_2025_04_16:"o3-2025-04-16",o3_mini:"o3-mini",o3_mini_2025_01_31:"o3-mini-2025-01-31",o4_mini:"o4-mini",o4_mini_2025_04_16:"o4-mini-2025-04-16",omni_moderation_2024_09_26:"omni-moderation-2024-09-26",omni_moderation_latest:"omni-moderation-latest"},mt={dall_e_2:"dall-e-2",dall_e_3:"dall-e-3",gpt_image_1:"gpt-image-1"},_t=class{constructor(t,e){this.apiKeys=t,this.config=e}chat(t,e,...r){let{toPrompt:i}=(()=>{if("function"==typeof t)return{toPrompt:t,args:e};if("string"==typeof t)return{toPrompt:()=>t,args:void 0};if(Array.isArray(t)){let e=0===t.length?[{user:""}]:t;return{toPrompt:()=>e,args:void 0}}{let i=[t,...void 0!==e?[e]:[],...r],n=0===i.length?[{user:""}]:i;return{toPrompt:()=>n,args:void 0}}})();return new Pt(this,i,e,Ct(),void 0,void 0,void 0)}image(t){return new gt(t,void 0,void 0,this)}},gt=class{constructor(t,e,r,i){this.prompt=t,this.l=e,this.p=r,this.aiClient=i}async then(t,e){try{let e=await this.getResponseAsString();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsString()}finally{t?.()}}get[Symbol.toStringTag](){return"ImagePrompt"}model(t){return this.l=t,this}size(t){return this.p=t,this}toFile(t){return new vt(this.prompt,this.l,this.p,t,this.aiClient)}async getResponseAsString(){let t=w(await this.aiClient.apiKeys.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"});return await wt(t,this.prompt)}},vt=class{constructor(t,e,r,i,n){this.prompt=t,this.l=e,this.p=r,this.fileName=i,this.aiClient=n}async then(t,e){try{let e=await this.getResponseAsFile();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsFile()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsFile()}finally{t?.()}}get[Symbol.toStringTag](){return"ImageFilePrompt"}model(t){return this.l=t,this}size(t){return this.p=t,this}async getResponseAsFile(){let t=w(await this.aiClient.apiKeys.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),e=await wt(t,this.prompt,this.l,this.p);return new Promise(((t,r)=>{dt(this.fileName,e,(i=>{i?r(i):t(new File([e],this.fileName,{type:"image/png"}))}))}))}},bt=new _t(void 0,{});function At(t){let e=Tt(t);bt.apiKeys=Ut(e),bt.config=e}function Et(t){let e=Tt(t);return new _t(Ut(e),e)}function Tt(t){return{promptGridApiKey:(()=>{let e="string"==typeof t?t:t.promptGridApiKey;return ut(e,tt(e).string().orUndefined(),{errorMessage:"Please provide a valid API key; got "+e})})(),apiKeys:"object"==typeof t&&null!==t?t.apiKeys:void 0,debugMode:"object"==typeof t&&null!==t&&t.debugMode}}function Ut(t){let e=t.promptGridApiKey,r=t.apiKeys,i=void 0!==e?(async()=>{let t=await(async()=>{try{return await fetch(A()+"/handshake",{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"promptgun",Authorization:"Bearer "+e}})}catch{throw Error("HTTP called failed when doing handshake")}})();if(200!==t.status){let e=await t.text();throw Error(`Handshake failed with status ${t.status}, body: ${e}`)}return await t.json()})():void 0;return{promptgrid:e,openai:(async()=>r?.openai??(await i)?.apiKeys.openai)()}}var Nt=new Map;function St(t){let e=t??bt;if(void 0===e.apiKeys)throw Error("No LLM set up. Call setupPromptGun first: ```import { setupPromptGun } from 'promptgun';\n\nsetupPromptGun({openAI: \"YOUR_OPENAI_API_KEY\"});\n```");return new Lt(e,Ct())}var Lt=class{constructor(t,e){this.aiClient=t,this.callingCodeLine=e}completeChat(t,e){return new Pt(this.aiClient,t,e,Ct(),void 0,void 0,void 0)}},Pt=class{constructor(t,e,r,i,n,s,o){this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.callingCodeLine=i,this.m=n,this._=s,this.l=o;let a=this;this.generator=async function*(){yield*await It(a.aiClient,o,a.promptSupplier(a.promptSupplierArgs),!1,a.promptName,n,s,i)}()}generator;promptName;name(t){return this.promptName=t,this}model(t){return this.l=t,this}temperature(t){return this.m=t,this}topP(t){return this._=t,this}next(...[t]){return this.generator.next(t)}return(t){return this.generator.return(t)}throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async then(t,e){try{let e=await this.getResponseAsString();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponseAsString()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponseAsString()}finally{t?.()}}get[Symbol.toStringTag](){return"BasicPrompt"}get(t){return new xt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,t,Ct(),this.promptName,this.m,this._,this.l)}getBoolean(){return this.get((t=>t.boolean()))}getString(){return this.get((t=>t.string()))}getNumber(){return this.get((t=>t.number()))}getObject(t){return this.get((e=>e.object(t)))}getArray(t){return new Rt(this.aiClient,this.promptSupplier,this.promptSupplierArgs,(e=>e.array(t)),this.callingCodeLine,this.promptName,this.m,this._,this.l)}getAny(){return this.get((t=>t.any()))}async getResponseAsString(){let t="";for await(let e of this)t+=e;return t}},xt=class extends J{constructor(t,e,r,i,n,s,o,a,h){let u=async function*(){yield*await It(t,h,e(r),void 0===i||i(tt(void 0)),s,o,a,n)}(),p=l.Flux.fromGenerator(u),c=(new T).processDataBuffer(p);super(),this.aiClient=t,this.promptSupplier=e,this.promptSupplierArgs=r,this.jsonTypeSupplier=i,this.callingCodeLine=n,this.promptName=s,this.m=o,this._=a,this.l=h;let f=this,w=(new M).parse(c);void 0!==i?w.onProperty("result",(t=>t.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)})))):w.onEachExcerpt((t=>{void 0!==t.token&&this.push(t)})),this.stringGenerator=async function*(){for await(let t of c)void 0!==t.token?w.push(t):void 0!==t.source&&(yield t.source)}(),this.partialJsonGenerator=async function*(){let t="";for await(let e of f.stringGenerator){t+=e;let r=D(t);yield void 0!==i?r?.result:r}}()}stringGenerator;partialJsonGenerator;next(...[t]){return this.partialJsonGenerator.next(t)}return(t){return this.partialJsonGenerator.return(t)}throw(t){return this.partialJsonGenerator.throw(t)}[Symbol.asyncIterator](){return this.partialJsonGenerator}async then(t,e){try{let e=await this.getResponse();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"JsonPrompt"}name(t){return this.promptName=t,this}model(t){return this.l=t,this}temperature(t){return this.m=t,this}topP(t){return this._=t,this}async getResponse(){let t=await this.getResponseAsString(),e=this.jsonTypeSupplier,r=G(t),i=void 0!==e?r?.result:r;if(void 0===e)return i;try{return ut(i,e(tt(i)))}catch{return console.debug('AI forgot to pack result in {"result": ...} wrapper, continuing by using complete result'),ut(r,e(tt(i)))}}v;getResponseAsString(){return void 0===this.v&&(this.v=this.A()),this.v}async A(){let t="";for await(let e of this.stringGenerator)t+=e;return t}},Rt=class extends xt{arrayElementGenerator;constructor(t,e,r,i,n,s,o,a,h){super(t,e,r,i,n,s,o,a,h);let u=this;this.arrayElementGenerator=l.Flux.create((async(t,e)=>{await u.onElement((async e=>{t(await e)})),e()}))}next(...[t]){return this.arrayElementGenerator.next(t)}return(t){return this.arrayElementGenerator.return(t)}throw(t){return this.arrayElementGenerator.throw(t)}[Symbol.asyncIterator](){return this.arrayElementGenerator}async then(t,e){try{let e=await this.getResponse();return L(t)?await t(e):e}catch(t){if(L(e))return await e(t);throw t}}async catch(t){try{return await this.getResponse()}catch(e){if(L(t))return t(e);throw e}}async finally(t){try{return await this.getResponse()}finally{t?.()}}get[Symbol.toStringTag](){return"JsonArrayPrompt"}};function Ot(t){return t??"gpt-4o"}async function*It(t,e,r,i,n,s,o,a){let h=new Map;try{let u=w(await t.apiKeys.openai).canBeString().andNothingElse({errorMessage:"No OpenAI access token set"}),l=function(t){let e=t=>({role:void 0!==t.user?"user":void 0!==t.system?"system":"assistant",content:H(t.user??t.system??t.assistant)});return"string"==typeof t?[{role:"user",content:t}]:Array.isArray(t)?t.map(e):[e(t)]}(r),f=(()=>{if(!i)return l;let t=(()=>{let t=l.length-1;for(;t>=0&&"user"===l[t].role;)t--;return t})();return[...l.slice(0,t+1),{role:"system",content:kt(0,i)},...l.slice(t+1)]})(),{fileName:d,lineNumber:y}=a;if(d&&void 0!==y&&Array.from(Nt.keys()).filter((t=>t.startsWith(d+":"))).map((t=>parseInt(t.split(":")[1],10))).length>1&&!n)throw Error(`Multiple prompts found in ${d}. Please specify a name using .name() method.`);let m={id:n,callingCodeLine:a},_=X(),g={},v=(e,r)=>{let i=X(),n=async()=>{g.currentSave=g.save,g.save=void 0,await async function(t,e){try{if(void 0===e)return;let r=await fetch(A()+"/api/conversations",{method:"PUT",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e},body:JSON.stringify(t)});if(!r.ok)throw Error(`Got ${r.status} when attempting to save conversation, with body: ${await r.text()}`)}catch(t){console.error("Error saving conversation",t)}}(e,t.apiKeys.promptgrid),await new Promise((t=>setTimeout(t,100))),await(g.save?.callback()),g.currentSave=void 0};void 0!==g.save&&h.delete(g.save.uuid),g.save={uuid:i,callback:n},void 0===g.currentSave&&h.set(i,{chunk:r,promise:n().then()})};v({conversationUuid:_,prompt:m,messages:f.map((t=>({messageUuid:X(),role:t.role,content:t.content||""})))});let b=X();v({conversationUuid:_,prompt:m,messages:[{messageUuid:b,role:"assistant",content:""}]});let E=function({model:t,prompt:e,apiToken:r,temperature:i,topP:n,requireJsonResponse:s}){return p.Flux.fromGeneratorFunction((async function*(){let o=new AbortController,a=await fetch("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:"Bearer "+r},method:"POST",signal:o.signal,body:JSON.stringify({model:t,messages:e,stream:!0,temperature:i,top_p:n,response_format:s?{type:"json_object"}:void 0})});if(a.status<200||a.status>=300){let t=function(t){try{return JSON.parse(t).error.message}catch{return t}}(await a.text());throw Error("OpenAPI reported: "+t)}if(null===a.body)throw Error("illegal state");let h="";yield*p.Flux.fromReadableStream(a.body,(()=>o.abort())).map((t=>c.decode(t,{stream:!0}))).flatMap((t=>t.replaceAll("data: [DONE]","").replace(/^data: /,"").split("data: "))).map((t=>t.replace(/[\n ]*$/,"").trim())).flatMap((t=>{h+=t;try{let t=JSON.parse(h);return h="",[t]}catch{return console.error("Received partial json chunk: "+t),[]}})).map((t=>t.choices[0])).untilExcl((t=>null!=t.finish_reason)).map((t=>t.delta.content)).filter((t=>void 0!==t))}))}({model:Ot(e),prompt:f,apiToken:u,temperature:s,topP:o,requireJsonResponse:!1!==i}),T="";yield*E.doOnEach((t=>{T+=t,v({conversationUuid:_,prompt:m,messages:[{messageUuid:b,role:"assistant",content:T}]},t)}))}finally{if(t.config.debugMode){let t=Array.from(h.values()).map((t=>t.promise));await Promise.all(t)}}}function kt(t,e){{if(!0===e)return"Respond with JSON";let t=e;return"Respond with JSON matching the Typescript-style type spec below, noting\n- when a value can be null if stated explicitly, e.g. 'string | null'\n- an optional property (denoted with squared brackets) is achieved in JSON by not including it, not by setting it to null\n\nThe type:\n"+lt(new it([],void 0).object((e=>e.has("result",(()=>new ht(t.type,t.value))))))}}function Ct(){let t=(Error().stack??"").split("\n").map((t=>t.trim())).filter((t=>t.startsWith("at ")))[2],e=t.match(/[^(]+\([^)]+\)/),{functionName:r,fileName:i,lineNumber:n}=e?t.match("at (?<functionName>[^(]*) ((?<scheme>.*://)?(?<fileName>[^:]*):(?<lineNumber>[0-9]+):(?<colNumber>[0-9]+))").groups:t.match("at (?<scheme>.*://)?(?<fileName>[^:]*):(?<lineNumber>[0-9]+):(?<colNumber>[0-9]+)").groups;return{stacktraceFrame:w(t).canBeString().andNothingElse(),fileName:w(i).canBeString().andNothingElse(),lineNumber:w(parseInt(n)).canBeNumber().andNothingElse(),functionName:w(r).canBeString().canBeUndefined().andNothingElse()}}export{_t as AIClient,yt as AiModel,Pt as BasicPrompt,at as EmptyPropTypeSpec,it as EmptyTypeSpec,ht as FullPropTypeSpec,nt as FullTypeSpec,vt as ImageFilePrompt,gt as ImagePrompt,Rt as JsonArrayPrompt,xt as JsonPrompt,mt as OpenaiImageModel,Lt as PromptBase,ot as PropTypeSpec,J as StreamedJsonChildElement,$ as StreamedJsonRootElement,st as TypeMemberSpec,rt as TypeSpec,bt as ai,Ct as getCallerFileNameAndLineNumber,Et as newAIClient,Ut as obtainAiClientData,D as parsePartialJson,St as promptAI,At as setupAI};
2
2
  //# sourceMappingURL=index.js.map